在 JPanel 中使用 GroupLayout 来对齐 JTextFields 和 JLabels



所以,这是我的问题:我使用oracle文档作为我项目的示例,但是当我运行程序时,它显示为一个中间带有"每周工资:"的框。我做错了什么?

JFrame window = new JFrame();
window.setTitle("Weekly Pay");
window.setSize(300, 150);
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Color lGray = new Color(209, 209, 209);
GroupLayout layout = new GroupLayout(window);
JPanel panel = new JPanel();
panel.setBackground(lGray);
panel.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
JLabel id = new JLabel("ID Number");
JLabel hw = new JLabel("Hourly Wage");
JLabel rh = new JLabel("Regular Hours");
JLabel oh = new JLabel("Overtime Hours");
JButton calc = new JButton("Calculate");
JTextField idEntry = new JTextField(); //where the user imputs their ID
JTextField hwEntry = new JTextField(); //where the user imputs their hourly wage
JTextField rhEntry = new JTextField(); //where the user imputs their regular hours
JTextField ohEntry = new JTextField(); //where the user imputs their overtime hours
JLabel wp = new JLabel("Weekly Pay:");    
GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();    
hGroup.addGroup(layout.createParallelGroup().
  addComponent(id).addComponent(hw).addComponent(rh).addComponent(oh).addComponent(calc));
hGroup.addGroup(layout.createParallelGroup().
  addComponent(idEntry).addComponent(hwEntry).addComponent(rhEntry).addComponent(ohEntry).addComponent(wp));
layout.setHorizontalGroup(hGroup);
GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();    
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
    addComponent(id).addComponent(idEntry));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
    addComponent(hw).addComponent(hwEntry));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
    addComponent(rh).addComponent(rhEntry));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
    addComponent(oh).addComponent(ohEntry));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
    addComponent(calc).addComponent(wp));
layout.setVerticalGroup(vGroup);
window.setVisible(true);

有两个主要问题:您将组布局管理器设置在框架上,而不是面板上,并且实际上并没有将面板放在框架/窗口上(因为Java UI编程中有一种称为窗口的东西,我质疑将框架保存为"窗口"的变量的命名)。

不要使用"GroupLayout layout = new GroupLayout(

window);",而是使用"GroupLayout layout = new GroupLayout(panel);当然,在面板建成之后"。

然后使用 "window.add(panel);" 将面板放在框架/窗口中;我会把这个和"window.pack();"放在"window.setVisible(true);"之前

;

钢筋混凝土

相关内容

  • 没有找到相关文章

最新更新