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

时间:2012-10-11 22:58:39

标签: java swing jlabel jtextfield grouplayout

所以,这是我的问题:我使用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);

1 个答案:

答案 0 :(得分:2)

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

而不是“GroupLayout layout = new GroupLayout(window);”,使用“GroupLayout layout = new GroupLayout(panel); //构建面板后,当然是”。

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

之前

RC