I know and saw a few threads on this issue but none of them led me a solution so far. As a beginner, I pushed myself so hard to find a solution on my own but this is the maximum that I could've done.
I'd like to change lbl (in Class A), through btn (in Class B) and with this code, I am having a really long error message but it shows this line in Class B (a.setText("Changed!");).
Thanks.
Class A:
private JFrame frame;
private JPanel panel;
private JLabel lbl;
public a() {
form();
labels();
frame.add(panel);
frame.setVisible(true);
}
public void form(){
frame = new JFrame("Frame");
frame.setSize(100, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(null);
}
public void labels() {
lbl = new JLabel("1");
lbl.setBounds(30, 20, 10, 10);
panel.add(lbl);
}
public void setText(String text) {
lbl.setText(text);
System.out.println("executed");
panel.validate();
panel.repaint();
}
public static void main(String[] args) {
new a();
}
Class B:
private JFrame frame;
private JPanel panel;
private JButton btn;
a a;
public b() {
form();
buttons();
frame.add(panel);
frame.setVisible(true);
}
public void form(){
frame = new JFrame("Frame");
frame.setSize(100, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(null);
}
public void buttons() {
btn = new JButton("Click me to change!");
btn.setBounds(30, 20, 10, 10);
btn.addActionListener(new ChangeHandler());
panel.add(btn);
}
class ChangeHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
a.setText("Changed!");
}
}
public static void main(String[] args) {
new b();
}