I need to create a gui in java which will take a string from a user and then user will click on submit button.On clicking the submit button,the user will do some processing on the string and then give output on screen(gui).
I have written the following code till now but when I run this code,it doesn't give any output.
public class userinterface extends javax.swing.JFrame {
public userinterface() {
initComponents();
}
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel5;
private javax.swing.JTextField jTextField1;
// End of variables declaration
public void show() {
String str = jTextField1.getText();
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Execute when button is pressed
System.out.println("You clicked the button,str");
}
});
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new userinterface().setVisible(true);
userinterface obj = new userinterface();
obj.show();
}
});
}
}
Please tell me where am I doing wrong ? How can I make the output display on gui screen?
Thanks.
2 Answers 2
Your problem is you've overridden the essential method show() without realizing it, and this prevents the JFrame from displaying. Change the name of this method to something different:
public void myShow() {
// String str = jTextField1.getText(); // not useful
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
System.out.println("You clicked the button,str");
}
});
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
// new userinterface().setVisible(true);
userinterface obj = new userinterface();
// obj.show();
obj.myShow();
obj.setVisible(true);
}
});
}
This is another reason that we all should strive not to extend classes unless absolutely necessary, since doing so can occasionally cause very difficult to debug errors.
I was able to debug this by placing println's throughout your code and seeing that show() was being called even when it wasn't explicitly being called by me.
1 Comment
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JLabel label = new JLabel("this is GUI boi");
frame.setSize(500, 500);
panel.add(label);
frame.add(panel);
frame.setVisible(true);
- you have to instantiate all the gui components
- you have to call the
setVisible()method of the JFrame - you have to set a width and height of the JFrame
- you have add the components to a parent component(like a label to a panel and that panel to a frame)
initComponents()without the class having the method. Have you gone through the Oracle Swing tutorials? The basic Java tutorials?