Denisowator Denisowator - 1 year ago 84
Java Question

Check both JCheckBox and JButton in Java

So I finished working on an interface for my program, but now I need to actually make my program do stuff. I have been using Java for a while now, but some things (like this one) are still very new to me

I have searched extensively, on here, on other sites, and on the Oracle website. But the closest I could find to what I need, was this exact question, only for JavaScript.

What I have is a button, and 17 checkboxes.

What I need to do (for every single checkbox), is check if the checkbox is checked, and if it is, also check if the button is clicked (it's not a toggle button btw). And then run a code.

Now for the sake of the code having as few lines as possible, I was hoping to do something like making the main code call upon another .class file, which would be the code that executes if both the button and checkbox return true. Instead of pasting the code for every single checkbox boolean.

So simply put, this is what I need:

If (JCheckBox is checked) {
If (JButton is pressed) {
Call other .class file

else {


Now this would have to go under every single checkbox, and I would need to check for the button every single time. So alternatively, I could just put all the code for the booleans, under the JButton's code, and save a lot of lines. But I don't know if it's possible to check for one object, in another object's code block.

Here is a snippet of the code for the button and one of the checkboxes.

//"Clean" button
JButton btnClean = new JButton("Clean");
btnClean.setBounds(244, 149, 100, 50);
btnClean.setFont(new Font("Arial", Font.PLAIN, 20));

//Checkbox "Temporary Files" (Registry)
JCheckBox chckbxTemporaryFilesRegistry = new JCheckBox("Temporary Files");
chckbxTemporaryFilesRegistry.setBounds(12, 80, 162, 15);

So from the pseudo-code above this snippet, you can see that I want to put a set of "if" statements, either in the checkbox, or the button code block. Depending on which one would be more efficient, and then call upon another class file that is located in the same folder as the main class file (the one that makes the interface).

Answer Source

You can use a ActionListener. This listener runs some code when the button is prssed. First make sure you implement the ActionListener

implements ActionListener

Then add the button to the Action Listener.


Now, you can edit your ActionPerfomed method

 public void actionPerformed (ActionEvent ae){


I hope that solves you problem. Have a nice day.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download