简体   繁体   中英

Java Multiple Checkboxes and Executing Multiple Statements

new to programming and Java is the first language I'm learning.

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.

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). 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. 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>");

Errors to be fixed:

I removed this line: 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.

emailButton doesn't exist so I commented it out:

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

This is a typo and won't run the gui: RsSync gui = new RcSsync(); so I changed it appropriately: RcSync gui = new RcSync();

Hopefully that helps! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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