I tried creating simple GUI using JFrame with below code.
package sorting_array_gui;
package sorting_array_gui;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
public class userwindow extends JFrame {
private static final long serialVersionUID = 1L;
public userwindow() {
super("A Programm to Sort Your Array");
setSize(1000,600);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
JPanel p1= new JPanel();
JButton b1= new JButton("Click Here");
p1.add(b1);
JTextField t1= new JTextField();
p1.add(t1);
JLabel l1= new JLabel("This is a Lable");
p1.add(l1);
add(p1,BorderLayout.CENTER);
}
}
When I added JTextfield , JPlane misbehaved and even JButton and JLabel stoped showing.
Why is that happening.
解决方案
"When I added JTextfield , JPlane misbehaved and even JButton and JLabel stoped showing."
I don't get this behavior with your code. But you should note the below.
setVisible(true); should be that last thing you do after adding all components.
public userwindow() {
super("A Programm to Sort Your Array");
JPanel p1= new JPanel();
JButton b1= new JButton("Click Here");
p1.add(b1);
JTextField t1= new JTextField();
p1.add(t1);
JLabel l1= new JLabel("This is a Lable");
p1.add(l1);
add(p1,BorderLayout.CENTER);
pack();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
Also, you should set a size to your text field using the constructor that sets the column size
JTextField t1 = new JTextField(20);
Also, you should use pack() instead of setSize(). If you just pack(), everything should be visible, as the preferred sizes of all the components are respected.
Also note, if you want to add any other components to the JFrame you need to specify a BorderLayout position for each component, with no positions being used more than once.
See Laying out Components Within a Container