Click here to Skip to main content
15,890,690 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
Hi, how can I click the checkbox in another class. Could you please help me? Thanks.

This code in class2.java. No error but no effect, too.
Java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
      class1 click=new class1();
      click.jCheckBox1.setSelected(true);  // jCheckBox1 in class1.java
   }
Posted
Updated 11-Jan-16 3:26am
v3
Comments
Sergey Alexandrovich Kryukov 11-Jan-16 10:19am    
There are classes (types) and instances. You need to understand it, to start with. "To another class" is nonsense.
—SA

It should really crash your app. You create a new instance of class1, try to click a checkbox in it which you have not yet created, then leave this method, at which time this object gets deleted. You need to select the checkbox that exists on the screen, and in your original object, that you (presumably) created at the beginning of your program.
 
Share this answer
 
The problem is: class1 is not fully instantiated yet.
You should use Swingutilities.invokelater(...).
 
Share this answer
 
Comments
bugsoul 12-Jan-16 4:31am    
Thanks Roland, but I can't understand. Could you please give an example or link abouth this.
Roland 57 12-Jan-16 9:44am    
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
final class1 click = new class1();
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
click.jCheckBox1.setSelected(true);
}
}
);
}
bugsoul 12-Jan-16 10:37am    
I try exactly, but nothing happen,again.
Java
package test;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;

/**
 *
 * @author Roland
 */
public class Test {
    
    private static class A extends JFrame {
        {
            JButton b = new JButton("click");
            add(b);
            pack();
            b.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    B f = new B();
                    f.cb.setSelected(true);
                }
            });
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        }
    };
    
    private static class B extends JFrame {
        public JCheckBox cb = new JCheckBox("Hallo");
    
        {
            add(cb);
            pack();
            setVisible(true);
        }
    };
    
    public static void main(String[] args) {
        new A().setVisible(true);
    }
    
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900