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.
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.
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);
setVisible()
method of the JFrame
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.