I tried to write a "calculator" and that the frame and the listener were in separate classes, but something happens during the check, that is, the b1 button on which it stuck addActionListener(listener) does not work, that is, added a textfield that needs to be filled with the answer but this does not happen .
The listener itself is obtained by creating an instance of it and initialized in the main class, and through the set method the Lister is added to the frame, and by analogy the same initialized frame is in the listener class, that is, they have instances of each other.
Yes, of course, the calculator consists of one button and the answer must be the entered increased number by one. And what is written for sure in Nuba, you can not pay attention to it. The main thing is tell me where the error is.
When writing a frame with the same frame class and the listener nested in it, everything works fine.
Main class:
import javax.swing.*; public class MainCalc { public static void main(String[] args){ Listener listener = new Listener(); Frame frame = new Frame("windows self 1/33.3"); frame.setListener(listener); listener.setFrame(frame); listener.getFrame().setVisible(true); listener.getFrame().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); listener.getFrame().setSize(200, 200); listener.getFrame().setResizable(false); listener.getFrame().setLocationRelativeTo(null); } } Listener:
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; public class Listener implements ActionListener{ private Frame fr = null; public void actionPerformed(ActionEvent e){ try { if(e.getSource() == fr.b1){ int i = Integer.parseInt(fr.tm.getText()); i++; String a = ""+i; fr.lm.setText(a); } } catch (Exception e1) { JOptionPane.showMessageDialog(null, "Enter NUMBER"); } } public Frame getFrame(){ return fr; } public void setFrame(Frame fr) { this.fr = fr; } } Frame class:
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Frame extends JFrame{ JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b0, bm, bp, bdot, beq, bmul, bdiv; JTextField tm, tme1, tme2; JLabel lm; private Listener listener = null; public void setListener(Listener listener){ this.listener = listener; } public Listener getListener(){ return listener; } public Frame(String s){ super(s); setLayout(new FlowLayout()); b1 = new JButton("unit"); tm = new JTextField(10); lm = new JLabel("text here"); add(b1); add(tm); add(lm); b1.addActionListener(listener); } }