好的,所以我无法使用网格布局以这种格式排列窗口,我想将每个标签及其文本字段排列到单独的行,然后在底部有一个居中的按钮。
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);
}
}
答案 0 :(得分:4)
//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。因此,您可以向框架添加多个面板。一个面板包含您的标签/文本字段,另一个面板包含您的按钮。