I have a label and a button in a class called FrameTest, when i press the button, a method named buttonpressed get’s executed from the class Test. In this buttonpressed method i will set a text to the label found in the FrameTest class.
The problem i have is that, the text for the label is not getting set. The reason is that i am creating a separate object to call the buttonpressed method;
public void actionPerformed(ActionEvent arg0) {
Test t = new Test();
t.buttonpress();
}
and i am creating a separate object in the main method of the Test class to create the UI.
public static void main(String[] args) {
FrameTest f = new FrameTest();
f.mainScreen();
}
The full code as follows;
public class FrameTest extends JFrame {
private JPanel contentPane;
private JLabel lblLabel;
private FrameTest ft = this;
//private FrameTest frame;
/**
* Launch the application.
*/
public void mainScreen() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
//FrameTest frame = new FrameTest();
//setVisible(true);
FrameTest frame = ft;
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void writeLabel(String k){
this.lblLabel.setText(k);
}
public FrameTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState(JFrame.MAXIMIZED_BOTH);
//setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
lblLabel = new JLabel("LABEL");
contentPane.add(lblLabel, BorderLayout.CENTER);
JButton btnNewButton = new JButton("Press");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Test t = new Test();
t.buttonpress();
}
});
contentPane.add(btnNewButton, BorderLayout.WEST);
//pack();
setLocationByPlatform(true);
}
}
Test Class
public class Test {
public static void main(String[] args) {
FrameTest f = new FrameTest();
f.mainScreen();
}
public void buttonpress(){
FrameTest f = new FrameTest();
f.writeLabel("Button was pressed");
}
1) Dont extend
JFrameclass unnecessarily.2) dont use
setContentPane()unless thats what you want. Rather just simplyJFrame#add(..).3) Steer away from
EventQueueand useSwingUtilitiesblock rather4) Dont forget to call
JFrame#pack();before settingJFramevisible.5) Java naming convention is CamelCase so
buttonPress()is correct notbuttonpress()Here is an example I made (basically your code fixed):
Test.java: (This is the main class which will create an instance of your
FrameTestand has the method to changeJLabeltext)FrameTest.java: (This class will show the
JFrameand create a new instance of classTestto callbuttonPress()):