I have 3 classes (3 separate files).

  1. just launching the application
  2. The class draws the form with one JLabel and JButton.

I want the JLabel text to change when I click on the button, but so that the event handler is in the 3rd grade. How to organize it?

one)

import javax.swing.*; public class App { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Form(); } }); } } 

2)

 import javax.swing.*; import java.awt.*; public class Form { JFrame jForm; Form(){ jForm = new JFrame("Test"); JPanel jp = new JPanel(new FlowLayout()); jForm.setBounds(500,500,200,200); JLabel jl = new JLabel("Text"); jp.add(jl); JButton jb = new JButton("Button"); jp.add(jb); jForm.setContentPane(jp); jForm.setVisible(true); } } 

3)

 import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Controller implements ActionListener { @Override public void actionPerformed(ActionEvent e) { } } 
  • one
    text information is better to attach as text: a) easier to read; b) can be copied; c) the search works. You can correct the question text by clicking below to edit the question text - aleksandr barakin

1 answer 1

 public class Controller implements ActionListener { private final JLabel label; public Controller(JLabel label) { this.label = label; } @Override public void actionPerformed(ActionEvent e) { label.setText("Hello"); } } jb.addActionListener(new Controller(jl)); 
  • I need to change from the Controller class in the Form Jlabel class, but how do I pass the form reference there? - rayvoid
  • @rayvoid supplemented the answer. - Sergey Gornostaev 2:53 pm