Java多个复选框和执行多个语句

时间:2018-10-22 19:37:33

标签: java swing checkbox

编程新手,而Java是我正在学习的第一门语言。

我在思考正在构建的此应用程序的逻辑时遇到困难。该应用程序非常简单:它具有五个复选框和一个同步按钮。选择一个复选框,然后单击“同步”,它会运行与特定复选框关联的cmd命令。

但是,我希望能够选中多个复选框并单击“同步”,使它们全部都可用,而不是一次执行一个。我目前有一个if语句(如果选中了复选框并且按下了同步按钮)运行“ xyz”命令(与该复选框相对应)。但是它仅在第一个复选框(如果)运行,然后退出。

谢谢!

编辑。下面的代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.Scanner;

class RcSync extends JFrame implements ActionListener{

    Container contentPane = getContentPane();

    JPanel top = new JPanel();
    JPanel center = new JPanel();
    JPanel bottom = new JPanel();

    JScrollPane mainScrollFrame = new JScrollPane(center);

    JLabel displayMessage = new JLabel("Please select a item, and click sync:");
    Font customFontHeader = new Font("", Font.BOLD,15);

    JButton syncButton = new JButton("Sync");
    JButton cancelButton = new JButton("Cancel");

    String[] database = {"Apple","Pineapple","Orange","Pear","Fig"};
    JCheckBox chk1 = new JCheckBox(database[0]);
    JCheckBox chk2 = new JCheckBox(database[1]);
    JCheckBox chk3 = new JCheckBox(database[2]);
    JCheckBox chk4 = new JCheckBox(database[3]);
    JCheckBox chk5 = new JCheckBox(database[4]);
    JCheckBox chk6 = new JCheckBox(database[5]);


    public RcSync() {
        super ("Sync Application");
        setSize (400,450);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        add(top);
        setVisible(true);

        top.add(displayMessage);
        displayMessage.setFont(customFontHeader);

        center.add(chk1);
        center.add(chk2);
        center.add(chk3);
        center.add(chk4);
        center.add(chk5);

        bottom.add(syncButton);
        syncButton.addActionListener(this);
        cancelButton.addActionListener(new CloseListener());
        bottom.add(cancelButton);
        bottom.add(emailButton);
        emailButton.addActionListener(this);

        contentPane.add("North", top);
        contentPane.add("South", bottom);
        this.getContentPane().add(mainScrollFrame, BorderLayout.CENTER);
        center.setLayout(new BoxLayout(center, BoxLayout.Y_AXIS));
    }

    public void actionPerformed(ActionEvent event){

        if ((event.getSource() == syncButton) && (chk1.isSelected())) {
            try {
                Runtime.getRuntime().exec("cmd /c start \"\" C:\\File\\script.bat " + chk1.getText());
            } catch (IOException e) {
                e.printStackTrace();}
        }
        if ((event.getSource() == syncButton) && (chk2.isSelected())) {
            try {
                Runtime.getRuntime().exec("cmd /c start \"\" C:\\File\\script.bat " + chk2.getText());
            } catch (IOException e) {
                e.printStackTrace();}
        }
        if ((event.getSource() == syncButton) && (chk3.isSelected())) {
            try {
                Runtime.getRuntime().exec("cmd /c start \"\" C:\\File\\script.bat " + chk3.getText());
            } catch (IOException e) {
                e.printStackTrace();}
        }
        if ((event.getSource() == syncButton) && (chk4.isSelected())) {
            try {
                Runtime.getRuntime().exec("cmd /c start \"\" C:\\File\\script.bat " + chk4.getText());
            } catch (IOException e) {
                e.printStackTrace();}
        }
        if ((event.getSource() == syncButton) && (chk5.isSelected())) {
            try {
                Runtime.getRuntime().exec("cmd /c start \"\" C:\\File\\script.bat " + chk5.getText());
            } catch (IOException e) {
                e.printStackTrace();}
        }

    }

    private class CloseListener implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        System.exit(0);
        }
    }

    public static void main (String[]args){

            RsSync gui = new RcSsync();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

由于您为问题提供了更多背景信息,因此我已经编辑了答复。 粘贴在下面:是我解决您的问题的方法,带有说明的有效代码,以及我必须通过关联代码解决的错误:

方法 :为每个复选框关联一个布尔值,该值对应于最终用户是否已选择了该选项。单击同步按钮后,查找已选中的复选框。这些复选框将从其isSelected()方法返回真实值。对于每个选中的复选框,将相关命令添加到 List 中,该列表包含要在最终用户的计算机上运行的所有命令。遍历此列表,直到没有命令可运行为止。

代码

import javax.swing.*;
import java.util.ArrayList;
import java.awt.*;
import java.awt.event.*;
import java.util.List;

class RcSync extends JFrame implements ActionListener{

    Container contentPane = getContentPane();

    JPanel top = new JPanel();
    JPanel center = new JPanel();
    JPanel bottom = new JPanel();

    JScrollPane mainScrollFrame = new JScrollPane(center);

    JLabel displayMessage = new JLabel("Please select a item, and click sync:");
    Font customFontHeader = new Font("", Font.BOLD,15);

    JButton syncButton = new JButton("Sync");
    JButton cancelButton = new JButton("Cancel");

    // Encapsulate your checkboxes to commands, since there is one 
   // to one relationship and makes future changes easier since there is a single point of change
    String[] database = {"Apple","Pineapple","Orange","Pear","Fig"};
    CheckboxCommand chk1 =  new CheckboxCommand("Checkbox 1 cmd", new JCheckBox(database[0]));
    CheckboxCommand chk2 =  new CheckboxCommand("Checkbox 2 cmd", new JCheckBox(database[1]));
    CheckboxCommand chk3 =  new CheckboxCommand("Checkbox 3 cmd", new JCheckBox(database[2]));
    CheckboxCommand chk4 =  new CheckboxCommand("Checkbox 4 cmd", new JCheckBox(database[3]));
    CheckboxCommand chk5 =  new CheckboxCommand("Checkbox 5 cmd", new JCheckBox(database[4]));


    public RcSync() {
        super ("Sync Application");
        setSize (400,450);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        add(top);
        setVisible(true);

        top.add(displayMessage);
        displayMessage.setFont(customFontHeader);

        center.add(chk1.checkbox);
        center.add(chk2.checkbox);
        center.add(chk3.checkbox);
        center.add(chk4.checkbox);
        center.add(chk5.checkbox);

        bottom.add(syncButton);
        syncButton.addActionListener(this);
        cancelButton.addActionListener(new CloseListener());
        bottom.add(cancelButton);
        // TODO email button doesn't exist, assuming copy/paste error?
        //        bottom.add(emailButton);
        //        emailButton.addActionListener(this);

        contentPane.add("North", top);
        contentPane.add("South", bottom);
        this.getContentPane().add(mainScrollFrame, BorderLayout.CENTER);
        center.setLayout(new BoxLayout(center, BoxLayout.Y_AXIS));
    }

    public void actionPerformed(ActionEvent event){
       // Implements the approach I described initially
        if (event.getSource() == syncButton){
            List<String> cmdsToRun = new ArrayList<>();
            if (chk1.isSelected()){
                cmdsToRun.add(chk1.getCmdToRun());
            }
            if (chk2.isSelected()){
                cmdsToRun.add(chk2.getCmdToRun());
            }
            if (chk3.isSelected()){
                cmdsToRun.add(chk3.getCmdToRun());
            }
            if (chk4.isSelected()){
                cmdsToRun.add(chk4.getCmdToRun());
            }
            if (chk5.isSelected()){
                cmdsToRun.add(chk5.getCmdToRun());
            }
            // Note: for verification purposes I just print out your commands
            // since they're hard coded to your particular environment
            System.out.println(cmdsToRun);

           // This is where you would loop through your command list i.e.
           // for (int x=0; x<cmdsToRun; x++){ //run command at cmdToRun.get(x); }
        }

    }

    private class CloseListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    }

    // encapsulating your checkboxes to commands
    private class CheckboxCommand {
        private String cmdToRun;
        private boolean isSelected;
        private JCheckBox checkbox;

        public CheckboxCommand(String cmdToRun, JCheckBox checkbox) {
            this.cmdToRun = cmdToRun;
            this.checkbox = checkbox;
        }

        public String getCmdToRun() {
            return cmdToRun;
        }

        public void setCmdToRun(String cmdToRun) {
            this.cmdToRun = cmdToRun;
        }

        public boolean isSelected() {
            return this.checkbox.isSelected();
        }

        public void setSelected(boolean selected) {
            isSelected = selected;
        }
    }

    public static void main (String[]args){
        // Fixed your typo error to run the swing interface
        RcSync gui = new RcSync();
    }
}

验证正确的代码:

Code Verification

关键见解:将复选框的命令封装到一个私有类中,因为存在一对一的关系,这将使您的代码具有单个更改点,通常这是最佳做法:)

旁注: 我实际上并没有在您的终端上运行您的命令,因为它们与您的特定计算机有关。即与本地脚本相关联,因此我打印了 dummy 命令以证明代码功能适当。我在代码中添加了一个注释块,以显示可以在其中添加环境特定代码的地方,即Runtime.getRuntime().exec("<CMD>");

要纠正的错误:

我删除了这一行:JCheckBox chk6 = new JCheckBox(database[5]);,因为这将引发indexOutOfBounds异常,因为内存数据库变量中只有5个元素,而不是6个。

emailButton不存在,所以我将其注释掉:

// bottom.add(emailButton);
// emailButton.addActionListener(this);

这是一个错字,不会运行gui:RsSync gui = new RcSsync();,所以我适当地更改了它:RcSync gui = new RcSync();

希望这会有所帮助! :)