简体   繁体   English

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

[英]Java Multiple Checkboxes and Executing Multiple Statements

new to programming and Java is the first language I'm learning. 编程新手,Java是我正在学习的第一门语言。

I'm having difficulty thinking through the logic on this application I'm building. 我在思考正在构建的此应用程序的逻辑时遇到困难。 The application is really simple: it has say five checkboxes and a sync button. 该应用程序非常简单:它具有五个复选框和一个同步按钮。 You select a checkbox and click sync and it runs a cmd command associated with the specific checkbox. 选择一个复选框,然后单击“同步”,它会运行与特定复选框关联的cmd命令。

However, I would like to be able to check multiple checkboxes and hit sync and have them all go instead of doing it one at a time. 但是,我希望能够选中多个复选框并单击“同步”,使它们全部都可用,而不是一次执行一个。 I currently have an if statement (if the checkbox is selected and sync button is pressed) run "xyz" command (that corresponds to that checkbox). 我目前有一个if语句(如果选中了复选框并且按下了同步按钮)运行“ xyz”命令(与该复选框相对应)。 But it only runs for the first checkbox (if) and then quits. 但是它只在第一个复选框(如果)运行,然后退出。

Thanks! 谢谢!

Edit. 编辑。 Code below: 代码如下:

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

I have edited my response since you provided more context to your question. 由于您为问题提供了更多背景信息,因此我已经编辑了我的回复。 Pasted below : is my approach to solving your problem, working code with explanation, and errors I had to resolve with your associated code: 粘贴在以下 :是我解决问题的方法,带说明的工作代码以及必须使用关联代码解决的错误:

Approach : Associate a boolean value for each checkbox corresponding to whether or not that option has been 'selected by the end user' . 方法 :为每个复选框关联一个布尔值,该值对应于该选项是否已被“最终用户选择” When the sync button is clicked, find which checkboxes have been selected. 单击同步按钮后,查找已选中的复选框。 These checkboxes will return a true value from their isSelected() method. 这些复选框将从其isSelected()方法返回一个真值。 For each checkbox selected add the associated command into a List containing all the commands to be ran on the end user's machine. 对于每个选定的复选框中添加相关联的命令到含有所有的命令的列表要在最终用户的计算机上运行。 Iterate through this list until there are no commands left to be ran. 遍历此列表,直到没有剩下要运行的命令为止。

Code : 代码

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

Verification of correct code: 验证正确的代码:

代码验证

Key Insight: I encapsulated your commands to checkboxes into a private class since there is a one to one relationship and this will allow your code to have a single point of change, which in general is a best practice :) 关键见解:由于存在一对一关系 ,因此我将复选框的命令封装到一个私有类中,这将使您的代码具有单个更改点,通常,这是最佳做法:)

Side Note: I don't actually run your commands on my end since they're tied to your particular machine . 旁注: 由于命令与您的特定计算机有关,因此我实际上不会在终端上运行您的命令 Ie associated to local scripts, so I printed out dummy commands to prove the code functions appropriately. 即与本地脚本相关联,因此我打印出虚拟命令以证明代码功能适当。 I added a comment block in the code to show where you can add your environment specific code ie Runtime.getRuntime().exec("<CMD>"); 我在代码中添加了一个注释块,以显示可以在其中添加环境特定代码的地方,即Runtime.getRuntime().exec("<CMD>");

Errors to be fixed: 错误要解决:

I removed this line: JCheckBox chk6 = new JCheckBox(database[5]); 我删除了这一行: JCheckBox chk6 = new JCheckBox(database[5]); since this will throw an indexOutOfBounds exception since there are only 5 elements in your in-memory database variable not 6. 因为这将引发indexOutOfBounds异常,因为内存数据库变量中只有5个元素,而不是6个。

emailButton doesn't exist so I commented it out: emailButton不存在,所以我将其注释掉:

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

This is a typo and won't run the gui: RsSync gui = new RcSsync(); 这是一个错字,不会运行gui: RsSync gui = new RcSsync(); so I changed it appropriately: RcSync gui = new RcSync(); 所以我适当地更改了它: RcSync gui = new RcSync();

Hopefully that helps! 希望有帮助! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM