Java动态添加按钮

时间:2015-11-18 00:07:39

标签: java swing jframe

我正在创建一个应用程序中心,我需要从属性文件中读取以检索应用程序名称和快捷方式,这是我检索的信息。

属性文件的格式:apps = chrome#youtube#eclipse#controlpanel

controlpanelpath = blahblah

我可以检索此信息,但我需要添加有多少应用程序的按钮。     例如,我添加了一个应用程序,然后当我重新启动应用程序时,它将显示为一个按钮。

    import java.io.File;
     import java.io.FileInputStream;
     import java.io.FileNotFoundException;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.io.OutputStream;
     import java.io.PrintWriter;
    import java.io.UnsupportedEncodingException;
 import java.util.Properties;

   import org.omg.CORBA.portable.InputStream;

   public class appmanager {
   public static String iconpath, path, name;

     public static Properties prop = new Properties();
     public static String result = "";
     public static String filename = "apps.properties";
       public static String appdata = System.getenv("APPDATA");
     public static String configpath = appdata + "\\" + filename;
     public static File properties = new File(configpath);
   public static OutputStream output = null;

     public static String apps[];
     public static String raw_apps;

    public static void gather() throws IOException{

    output = new FileOutputStream(configpath);
    raw_apps = prop.getProperty("apps");
    apps=raw_apps.split(",");
    //Add app path with the name in apps array



    //add button to Jframe 'hud'



    output.close();

    }


public static void retrieve() throws IOException{

    if(properties.exists()){
    create();


    }
    else{


        gather();




    }





}

public static void send(){

}
public static void add(){
    iconpath=appdetails.file;
    path=MainGui.file;
}
public static void create() throws IOException{

    System.out.println(configpath);

    output = new FileOutputStream(configpath);




    output.close();

        }
          }

主应用中心jframe在另一个类中,它被称为“hud”。

BTW我只需要添加按钮的部分应用数量!感谢

1 个答案:

答案 0 :(得分:3)

面向对象的方法:

以下方法使用JSON配置文件。使用Google的GSON库解析文件,配置文件中的信息是应用程序用来构建按钮的信息。

已经过测试和验证。您可能需要删除或更改应用程序的应用程序路径才能正常运行。

注意:您需要一个依赖关系管理系统,即Maven或Gradle来拉入GSON,或者您可以下载一个jar并手动链接它。

截图

Screenshot

结构

这是应用程序的骨架结构。

> AppLauncher/
  > src/
    > app/
      > component/
        - AppButton.java
      > config/
        > dto/
          - AppConfig.java
          - RootConfig.java
     > view/
       - AppDashboard.java
    > resources/
      - appConfig.json
    - AppLauncher.java

类和文件

AppLauncher

这是应用程序启动程序,它在读取配置文件后启动应用程序。

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

import app.config.dto.RootConfig;
import app.config.reader.ConfigReader;
import app.view.AppDashboard;

public class AppLauncher {
    public static final String APP_TITLE = "App Launcher";

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame(APP_TITLE);
                RootConfig config = ConfigReader.read("/resources/appConfig.json");
                AppDashboard dashboard = new AppDashboard(config);

                System.out.println(config);

                frame.setContentPane(dashboard);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

AppDashboard

此视图包含配置中定义的每个应用程序的按钮。

package app.view;

import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JPanel;

import app.component.AppButton;
import app.config.dto.AppConfig;
import app.config.dto.RootConfig;

public class AppDashboard extends JPanel {
    private static final long serialVersionUID = -3885872923055669204L;

    private RootConfig config;
    private List<AppButton> buttons;

    public AppDashboard(RootConfig config) {
        super(new FlowLayout());

        this.config = config;

        buttons = new ArrayList<AppButton>();

        for (AppConfig appConfig : config.getApplications()) {
            buttons.add(new AppButton(appConfig));
        }

        createChildren();
    }

    protected void createChildren() {
        for (AppButton button : buttons) {
            this.add(button);
        }
    }
}

AppButton

这是应用程序按钮,当按钮被触发时,该按钮具有文本标签和启动操作。这可以扩展为呈现应用程序的图标。

package app.component;

import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.JButton;

import app.config.dto.AppConfig;

public class AppButton extends JButton {
    private static final long serialVersionUID = -730609116042003884L;

    private AppConfig config;

    public AppButton(AppConfig config) {
        super();

        this.config = config;

        setAction(new AbstractAction(config.getName()) {
            private static final long serialVersionUID = -2999563123610952893L;

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    launch();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
    }

    private String[] procArguments() {
        List<String> commands = config.getArguments();

        commands.add(0, config.getPath());

        return commands.toArray(new String[commands.size()]);
    }

    /**
     * @see http://stackoverflow.com/questions/13991007/execute-external-program-in-java
     */
    public void launch() throws IOException {
        String[] args = procArguments();
        Process process = new ProcessBuilder(args).start();
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;

        System.out.printf("Output of running %s is:", Arrays.toString(args));

        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
}

ConfigReader

它处理读取JSON配置文件并将其编组到java DTO(数据传输对象)中,该文件将由应用程序的组件使用。

package app.config.reader;

import java.io.InputStreamReader;

import com.google.gson.Gson;

import app.config.dto.RootConfig;

public class ConfigReader {
    private static ClassLoader loader = ConfigReader.class.getClassLoader();

    public static RootConfig read(String filename) {
        return new Gson().fromJson(getInputStream(filename), RootConfig.class);
    }

    private static InputStreamReader getInputStream(String filename) {
        return new InputStreamReader(loader.getResourceAsStream(filename));
    }
}

RootConfig

这是包含应用程序配置的配置的根目录。

package app.config.dto;

import java.util.List;

public class RootConfig {
    private List<AppConfig> applications;

    public List<AppConfig> getApplications() {
        return applications;
    }

    public void setApplications(List<AppConfig> applications) {
        this.applications = applications;
    }

    @Override
    public String toString() {
        return "RootConfig [applications=" + applications + "]";
    }
}

的AppConfig

这是描述应用程序的应用程序配置。

package app.config.dto;

import java.util.List;

public class AppConfig {
    private String name;
    private String path;
    private List<String> arguments;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public List<String> getArguments() {
        return arguments;
    }

    public void setArguments(List<String> arguments) {
        this.arguments = arguments;
    }

    @Override
    public String toString() {
        return "AppConfig [name=" + name + ", path=" + path + ", arguments=" + arguments + "]";
    }
}

appConfig.json

这是配置文件,应用程序将读取该文件来创建按钮。

{
    "applications" : [
        {
            "name" : "Chrome",
            "path" : "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe",
            "arguments" : []
        }, {
            "name" : "Eclipse",
            "path" : "C:/Eclipse/current/eclipse.exe",
            "arguments" : []
        }, {
            "name" : "Control Panel",
            "path" : "C:/Windows/System32/control.exe",
            "arguments" : []
        }
    ]
}

pom.xml依赖项

这些是程序解析JSON文件所需的Maven依赖项。您可以使用另一个解析库,例如Jackson或JsonLib。

<dependencies>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.4</version>
    </dependency>
</dependencies>
相关问题