请有人能够对我的代码提供一些了解。我想让天平选项卡上的按钮与左上角对齐。我尝试过不同的布局管理器,但似乎都会导致按钮位于中心的相同或类似结果
public class DefaultView extends JFrame {
public DefaultView() {
JButton SendBalInc = new JButton();
SendBalInc.setText("Balance");
GridBagConstraints c = new GridBagConstraints();
GridBagLayout gridbag = new GridBagLayout();
c.fill = GridBagConstraints.BOTH;
// Bal.fill = GridBagConstraints.NONE;
JPanel window = new JPanel();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800, 600);
// this.setUndecorated(true);
window.setBackground(Color.WHITE);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setBackground(Color.WHITE);
JComponent panel1 = makeTextPanel("Panel #1");
tabbedPane.addTab("PIN ", panel1);
JPanel panel2 = new JPanel();
Box box = Box.createHorizontalBox();
box.add(Box.createHorizontalGlue());
box.add(SendBalInc);
panel2.setBackground(Color.WHITE);
panel2.add(box);
tabbedPane.addTab("Balance", panel2);
JComponent panel3 = makeTextPanel("Panel #3");
tabbedPane.addTab("Dep", panel3);
JComponent panel4 = makeTextPanel("Panel #4");
tabbedPane.addTab("Bill", panel4);
window.setLayout(new GridLayout(1, 2));
window.add(tabbedPane);
this.add(window);
}
protected JComponent makeTextPanel(String text) {
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
return panel;
}
}
答案 0 :(得分:2)
我更喜欢GridBagLayout:
final JPanel panel2 = new JPanel();
panel2.setLayout(new GridBagLayout());
panel2.setBackground(Color.WHITE);
final GridBagConstraints cons = new GridBagConstraints();
cons.weightx = 1D;
cons.weighty = 1D;
cons.anchor = GridBagConstraints.NORTHWEST;
panel2.add(box, cons);
tabbedPane.addTab("Balance", panel2);
注意:不需要框
答案 1 :(得分:0)
您可以简单地使用BoxLayout
JPanel panel2 = new JPanel();
panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
panel2.setBackground(Color.WHITE);
panel2.add(SendBalInc);
但我认为Betlista对GridBag的回答可能更合适,因为您有更多选择可以在未来进一步调整布局。
答案 2 :(得分:0)
创建Box并将其直接添加到JTabbedPane,而不是先将其放在面板中。并使该框成为一个垂直框,以便您可以通过在每个子项上设置setAlignmentX来控制其子项的对齐。
Box box = Box.createVerticalBox();
box.add(SendBalInc);
tabbedPane.addTab("Balance", box);
答案 3 :(得分:0)
您可以添加以下内容以将按钮对齐到左侧:
panel2.setLayout(new FlowLayout(FlowLayout.LEFT));
您可以在文档{{3p>中找到更多信息