Java Swing 布局和菜单
Java Swing Layouts and Menus
好的,所以我在使用网格布局以这种格式排列 window 时遇到问题,我想将每个标签及其文本字段排列到单独的行中,然后在底部有一个居中的按钮.
public class Main extends JFrame {
//below is how i want to format the frame
/*label textfield
label textfield
label textfield
button*/
JPanel panel = new JPanel();
JLabel nameLabel = new JLabel("Name");
JTextField nameText = new JTextField(15);
JLabel addressLabel = new JLabel("Address");
JTextField addressText = new JTextField(15);
public Main(){
setTitle("JSWING");
setLayout(new GridLayout(3,2));
setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
setVisible(true);
setSize(450,250);
//setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel.add(nameLabel);
panel.add(nameText);
panel.add(addressLabel);
panel.add(addressText);
add(panel);
}
public static void main(String[] args){
Main mainFrame = new Main();
//mainFrame.setVisible(true);
}
}
//setVisible(true); // don't do this until all components are added to the frame.
...
add(panel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
JButton button = new JButton("Button");
buttonPanel.add( button );
add(buttonPanel, BorderLayout.PAGE_END);
setVisible(true);
框架的默认布局管理器是 BorderLayout。因此,您可以将多个面板添加到框架中。一个面板包含您的 labels/text 字段,另一个面板包含您的按钮。
好的,所以我在使用网格布局以这种格式排列 window 时遇到问题,我想将每个标签及其文本字段排列到单独的行中,然后在底部有一个居中的按钮.
public class Main extends JFrame {
//below is how i want to format the frame
/*label textfield
label textfield
label textfield
button*/
JPanel panel = new JPanel();
JLabel nameLabel = new JLabel("Name");
JTextField nameText = new JTextField(15);
JLabel addressLabel = new JLabel("Address");
JTextField addressText = new JTextField(15);
public Main(){
setTitle("JSWING");
setLayout(new GridLayout(3,2));
setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
setVisible(true);
setSize(450,250);
//setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel.add(nameLabel);
panel.add(nameText);
panel.add(addressLabel);
panel.add(addressText);
add(panel);
}
public static void main(String[] args){
Main mainFrame = new Main();
//mainFrame.setVisible(true);
}
}
//setVisible(true); // don't do this until all components are added to the frame.
...
add(panel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
JButton button = new JButton("Button");
buttonPanel.add( button );
add(buttonPanel, BorderLayout.PAGE_END);
setVisible(true);
框架的默认布局管理器是 BorderLayout。因此,您可以将多个面板添加到框架中。一个面板包含您的 labels/text 字段,另一个面板包含您的按钮。