gpt4 book ai didi

java - 我无法将其与 Jpanel 的右侧部分对齐

转载 作者:行者123 更新时间:2023-12-02 03:09:58 26 4
gpt4 key购买 nike

我试图将左侧的所有按钮全部对齐,但无论我做什么,它似乎总是留在中间,我尝试过“c.anchor = GridBagConstraints.EAST;”但这没有帮助,现在我陷入困境,请帮忙。

    JButton Button1 = new JButton("<html> Li <center> <small> 7 <br> 3<small/> <center/> <html/> ");
JButton Button2 = new JButton("<html> Na <center> <small> 32<br> 11<small/> <center/> <html/> ");
JButton Button3 = new JButton("<html>K<center><small> 39 <br> 19<small/> <center/> <html/> ");



GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int width = gd.getDisplayMode().getWidth();
int height = gd.getDisplayMode().getHeight();

Button1.setPreferredSize(new Dimension(50, 50));
Button2.setPreferredSize(new Dimension(50, 50));
Button3.setPreferredSize(new Dimension(50, 50));


GridBagLayout layout = new GridBagLayout() ;
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;

c.anchor = GridBagConstraints.EAST;
setLayout(layout);
add(Button1, c);
add(Button2, c);
add(Button3, c);
add(exit);
setSize(width, height);
setExtendedState(JFrame.MAXIMIZED_BOTH);
//TODO Align to left
setUndecorated(true);
setLocationRelativeTo(null);

最佳答案

c.gridx = 0;
c.anchor = GridBagConstraints.EAST;
setLayout(layout);
add(Button1, c);
add(Button2, c);
add(Button3, c);
add(exit);

一方面,您将所有组件添加到同一个单元格中,因为您使用相同的约束。如果您希望它们位于不同的行,那么您需要为每个组件指定不同的“gridy”值。

it always seems to stay in the center,

除非您指定 weightx/weighty 值,否则这是默认行为。

更简单的方法是将 JPanel 与 GridLayout 一起使用。将所有按钮添加到面板中。最后,使用以下方法将面板添加到框架中:

frame.add(buttonPanel, BorderLayout.LINE_START);

我建议您首先阅读 Swing 教程 Layout Managers 中的部分。 。上面提到的所有布局管理器都有工作示例。

其他问题:

  1. 变量名称不应以大写字符开头。
  2. 不要在组件上使用 setPreferredSize()。每个组件应确定其自己的首选尺寸。然后布局管理器将使用此信息。
  3. GUI 代码应在事件调度线程 (EDT) 上执行。

Swing 教程都遵循上述标准,因此请下载演示代码来学习。

关于java - 我无法将其与 Jpanel 的右侧部分对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41200313/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com