【问题标题】:Java Multiple Checkboxes and Executing Multiple StatementsJava 多个复选框和执行多个语句
【发布时间】:2018-10-25 00:46:14
【问题描述】:

刚接触编程,Java 是我学习的第一门语言。

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

但是,我希望能够选中多个复选框并点击同步,然后让它们全部执行,而不是一次执行一个。我目前有一个 if 语句(如果选中了复选框并按下了同步按钮)运行“xyz”命令(对应于该复选框)。但它只针对第一个复选框 (if) 运行,然后退出。

谢谢!

编辑。代码如下:

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 和复选框 2 选择了运行命令 1 和命令 2,我可以使用另一个。但我需要能够扩展,如果我有 20 多个复选框,这将很麻烦。
  • 请发布您的代码。
  • 为什么不对每个复选框只使用一个 if 语句(而不是听起来像 if-else if 语句)

标签: java swing checkbox


【解决方案1】:

由于您为您的问题提供了更多背景信息,因此我已经编辑了我的回复。 粘贴在下面:是我解决您的问题的方法、带有解释的工作代码以及我必须使用您的关联代码解决的错误:

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

代码

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();
    }
}

验证正确代码:

关键洞察:将您的复选框命令封装到一个私有类中,因为存在一对一的关系,这将允许您的代码具有单点更改,通常是最佳实践:)

旁注: 我实际上并没有在我这边运行你的命令,因为它们与你的特定机器相关联。 IE。与本地脚本相关联,所以我打印出 dummy 命令来证明代码功能正确。我在代码中添加了一个注释块,以显示您可以在哪里添加特定于环境的代码,即Runtime.getRuntime().exec("&lt;CMD&gt;");

要修复的错误:

我删除了这一行: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();

希望对您有所帮助! :)

【讨论】:

    猜你喜欢
    • 2012-06-11
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 2017-02-02
    相关资源
    最近更新 更多