使用WPF实现一个快速切换JDK版本的客户端工具

发现网上一键切换JDK环境的方法都是在mac或Linux下的,本人主力电脑是Windows,于是看了一下WPF的文档,自己开发了一个客户端。

直接上代码吧:

using JavaSwitch.Properties;
using Newtonsoft.Json;
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Forms;

namespace JavaSwitch
{
    public class ListItem
    {
        public string Text { get; set; }
        public bool IsSelected { get; set; }

        public ListItem(string text)
        {
            Text = text;
        }
    }

    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public ObservableCollection<ListItem> Items { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            // 从本地加载已有的数据
            LoadDataFromJson();
            // 数据绑定上下文
            DataContext = this;
        }

        private void Button_Add(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog
            {
                // 设置初始目录
                RootFolder = Environment.SpecialFolder.Desktop
            };
            // 这个方法可以显示文件夹选择对话框
            folderBrowserDialog.ShowDialog();
            // 获取选择的文件夹的全路径名
            string directoryPath = folderBrowserDialog.SelectedPath;

            // 打印出选择的路径
            Console.WriteLine(directoryPath);

            if (string.IsNullOrEmpty(directoryPath))
            {
                return;
            }

            // 持久化到本地
            var newItem = new ListItem(directoryPath);
            Items.Add(newItem);
            SaveDataToJson();
        }

        /// <summary>
        /// 删除一项
        /// </summary>
        private void Button_Delete(object sender, RoutedEventArgs e)
        {
            var deleteButton = sender as System.Windows.Controls.Button;
            if (deleteButton != null)
            {
                var listItem = deleteButton.DataContext as ListItem;
                if (listItem != null)
                {
                    Items.Remove(listItem);
                    SaveDataToJson();
                }
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            // 打开环境变量设置页面 rundll32 sysdm.cpl,EditEnvironmentVariables
            Process.Start("rundll32.exe", "sysdm.cpl,EditEnvironmentVariables");
            //string originalPath = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
            //System.Windows.MessageBox.Show("Original Path: " + originalPath);
        }

        private void RadioButton_Click(object sender, RoutedEventArgs e)
        {
            var radioButton = sender as System.Windows.Controls.RadioButton;
            if (radioButton != null)
            {
                var listItem = radioButton.DataContext as ListItem;
                if (listItem != null)
                {
                    foreach (var item in Items)
                    {
                        item.IsSelected = item == listItem;
                        if (item.IsSelected)
                        {
                            // 设置环境变量
                            // 执行bash命令:setx JAVA_PATH "%JAVA_HOME%\bin;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar;" /M
                            Process.Start("cmd", "/c setx JAVA_PATH \"" + item.Text + "\\bin;" + item.Text + "\\lib\\dt.jar;" + item.Text + "\\lib\\tools.jar;\" /M");
                            // 执行bash命令:refreshenv.cmd
                            Process.Start("cmd", "/c refreshenv.cmd");
                        }
                    }
                }
            }
            SaveDataToJson();
        }

        private string ENV_DATA = "JavaEnvironment.json";
        /// <summary>
        /// 保存数据到本地
        /// </summary>
        private void SaveDataToJson()
        {
            var json = JsonConvert.SerializeObject(Items, Formatting.Indented);
            File.WriteAllText(ENV_DATA, json);
        }

        /// <summary>
        /// 从本地加载数据
        /// </summary>
        private void LoadDataFromJson()
        {
            if (File.Exists(ENV_DATA))
            {
                var json = File.ReadAllText(ENV_DATA);
                Items = JsonConvert.DeserializeObject<ObservableCollection<ListItem>>(json);
            }
            else
            {
                Items = new ObservableCollection<ListItem>();
            }
        }
    }
}

布局文件:

<Window x:Class="JavaSwitch.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:JavaSwitch"
        mc:Ignorable="d"
        Title="Java环境切换" Height="450" Width="800">
    <Grid>
        <TextBlock FontSize="18" FontWeight="Bold" Foreground="#ffbe4d4d"  HorizontalAlignment="Left" Margin="10,10,0,0" TextWrapping="Wrap" Text="请用管理员身份打开本程序,否则没有权限修改设置!" VerticalAlignment="Top" Width="586"/>
        <TextBlock FontSize="16" HorizontalAlignment="Left" Margin="10,47,0,0" TextWrapping="Wrap" Text="第一步:打开系统变量-Path,检查并添加%JAVA_PATH%(已添加则不用重复添加)" VerticalAlignment="Top" Width="629"/>
        <TextBlock FontSize="16" HorizontalAlignment="Left" Margin="10,84,0,0" TextWrapping="Wrap" Text="第二步:添加已安装的JDK文件夹" VerticalAlignment="Top" Width="263"/>
        <Button FontSize="16" Content="检查环境变量" HorizontalAlignment="Left" Margin="639,47,0,0" VerticalAlignment="Top" Click="Button_Click_1"/>
        <Button FontSize="16" Content="添加一个Java环境" HorizontalAlignment="Left" Margin="257,82,0,0" VerticalAlignment="Top" Click="Button_Add"/>
        <TextBlock FontSize="16" HorizontalAlignment="Left" Margin="10,123,0,0" TextWrapping="Wrap" Text="第三步:点击按钮切换环境" VerticalAlignment="Top"/>
        <ListBox x:Name="listBox" ItemsSource="{Binding Items}" Margin="0,156,0,0">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Margin="0, 10, 0, 10">
                        <Viewbox Height="22" VerticalAlignment="Center">
                            <RadioButton x:Name="radioButton" GroupName="RadioGroup" IsChecked="{Binding IsSelected, Mode=TwoWay}" Click="RadioButton_Click" />
                        </Viewbox>
                        <TextBlock Text="{Binding Text}" VerticalAlignment="Center"  FontSize="16" Margin="10,0,0,0"/>
                        <Button Content="删除" VerticalAlignment="Center" Click="Button_Delete" FontSize="16" Margin="20,0,0,0"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

    </Grid>
</Window>

github链接:https://github.com/ITAnt/JavaSwitch

安装文件在根目录的release文件夹

相关推荐
国通快递驿站22 分钟前
助力企业信息化,开源免费工作流引擎AntFlow推出重榜功能tidb支持,为工作流引擎水平扩展提供无限可能
java·spring boot·spring·开源·tidb·activiti
千穹凌帝38 分钟前
SpinalHDL之结构(八)
开发语言·前端·mcu·fpga开发·fpga
kill bert40 分钟前
第18周 3-过滤器
java
好看资源平台1 小时前
C++游戏开发:构建高性能、沉浸式游戏体验的关键
开发语言·c++·游戏
quweiie1 小时前
paypal支付v2.0(php)支付代码
android·开发语言·php
Swxctx1 小时前
Go版数据结构 -【4.1 二叉树】
开发语言·数据结构·golang·go版数据结构
网安康sir1 小时前
2024年三个月自学网络安全(黑客技术)教程。
开发语言·网络·安全·web安全·php
一 乐1 小时前
畅阅读小程序|畅阅读系统|基于java的畅阅读系统小程序设计与实现(源码+数据库+文档)
java·小程序·vue·源码·springboot·阅读小程序
流星白龙1 小时前
【C++算法】6.双指针_有效三角形的个数
开发语言·c++·算法
九离十2 小时前
初识C语言(四)
c语言·开发语言