使用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文件夹

效果图

上一篇:前端面试题(三)


下一篇:rabbitMQ 简单使用