Problem: Not able to update swing component from another class.
Objective: When user clicks the update button, the text in "nameLabel" will change to "John Doe".
I attempted the solutions from stackoverflow regarding this issue but had no success.
Here is a very simple example, not sure what I'm doing wrong.
GUI.java
package TestGUI.TestGUI;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GUI {
JLabel nameLabel;
JButton updateButton;
JFrame frame;
JPanel panel;
public void display() {
frame = new JFrame();
panel = new JPanel(new BorderLayout());
frame.setTitle("BlackJack Game");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
nameLabel = new JLabel("No Name");
updateButton = new JButton("Update");
panel.add(nameLabel, BorderLayout.NORTH);
panel.add(updateButton, BorderLayout.SOUTH);
updateButton.addActionListener(new EventListener());
}
public void setNameLabel(String name) {
nameLabel.setText(name);
}
}
EventListener.java
package TestGUI.TestGUI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class EventListener implements ActionListener {
//private Card card;
private GUI gui;
public EventListener(GUI gui) {
this.gui = gui;
}
public EventListener() {
// TODO Auto-generated constructor stub
}
public void actionPerformed(ActionEvent actionEvent) {
String actionCommand = actionEvent.getActionCommand();
if(actionCommand.equals("Update")) {
gui.setNameLabel("John Doe");
}
}
}
App.java
package TestGUI.TestGUI;
public class App
{
public static void main( String[] args )
{
GUI gui = new GUI();
gui.display();
}
}
The following error is produced, when the "update" button is clicked.