I tried to find the answer, but I will come soon. I am new to java. I have 4 classes (1 main with JFrame and 3 JPanels). The main class creates a JFrame and adds 3 panels to it. What I'm trying to do is update the JLabel or JTextField panel to 1 (panel A) from an ActionEvent in another panel (panel B). The ActionEvent in panel B runs the method in panel A, which runs the setText () method and the repaint () method. I cannot get JLabel or JTextField to update with new text.
Here is my code:
App.java
public class App { public static void main(String[] args) { JFrame nameFrame = new JFrame("Name Form"); nameFrame.setLayout(new BorderLayout()); nameFrame.setSize(300,150); nameFrame.setLocationRelativeTo(null); nameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); MiddlePanel middlePanel = new MiddlePanel(); nameFrame.add(middlePanel, BorderLayout.CENTER); BottomPanel bottomPanel = new BottomPanel(); nameFrame.add(bottomPanel, BorderLayout.SOUTH); nameFrame.setVisible(true); } }
Bottottpanel.java
import java.awt.FlowLayout; import javax.swing.JLabel; import javax.swing.JPanel; public class BottomPanel extends JPanel { private JLabel welcomeLabel = new JLabel("Old Text"); BottomPanel() { super(new FlowLayout()); add(welcomeLabel); } public void setText(String text) { welcomeLabel.setText(text); repaint(); } }
MiddlePanel.java
import java.awt.BorderLayout; import javax.swing.JButton; import javax.swing.JTextArea; import javax.swing.JPanel; import java.awt.event.*; import java.awt.Graphics; public class MiddlePanel extends JPanel { MiddlePanel() { super(new BorderLayout()); JButton okButton = new JButton("OK"); okButton.setSize(20, 20); OKButtonListener okButtonListener = new OKButtonListener(); okButton.addActionListener(okButtonListener); add(okButton, BorderLayout.EAST); } class OKButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { BottomPanel bottomPanel = new BottomPanel(); bottomPanel.setText("New Text"); } } }
Thanks for any help.
source share