Java GUI - 定位

标签 java swing user-interface layout-manager gridbaglayout

我试图将两个按钮放置在左上角。但它们始终位于顶部中心。

我已经尝试过这个:

jp = new JPanel();
jp.setLayout(new GridBagLayout());

GridBagConstraints c = new GridBagConstraints();

//c.anchor = GridBagConstraints.BASELINE_TRAILING;
c.anchor = GridBagConstraints.WEST;

c.gridx = 0;
c.gridy = 0;
jp.add(test, c);
c.gridy++;
jp.add(atest, c);
add(jp);

但它仍然位于中心,而不是左侧 ( /image/dHdmZ.png )。

enter image description here

这是我拍的照片。红色是我希望按钮的样子的草图。

<小时/>

更新:

 ArrayList<String> atest = new ArrayList<String>();
    JLabel[ ] asd = new JLabel[100];

    int temp = 0;



GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 0;
c.gridy = 0;
atest.add("Hello");
atest.add("haelp");
atest.add("yummy");
atest.add("whats wrong");

for(String server : servers)
{
    asd[temp] = new JLabel();
    asd[temp].setText(server);
    jp.add(asd[temp], c);
    c.weighty++;
    c.gridy++;
    temp++;

}

我试图从数组中读取字符串并将其添加为左侧的标签。 效果不太好,结果如下: http://prntscr.com/26a9rb 如果 gridbaglayout 是不好的方法,我应该采用哪种方法?

最佳答案

阅读 Swing 教程中关于 How to Use GridBagLayout 的部分了解这些限制如何发挥作用。关于 weightx,weighty 的部分应该可以解决您的问题。

关于Java GUI - 定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20020688/

相关文章:

javascript - 使用 CryptoJS 的 Java SHA-1 到 javascript

java - 问题子类化 JTextField : initial text value is not displayed

java - 如何在java swing中弹出错误来检查酒店入住日期是否应该早于退房日期?

user-interface - 用于基于 Web 的管理界面的免费表单、图标、样式等集

java - Javax Swing GUI 应用程序的单元测试问题 - 合适的 JDK 7 选项?

java - 指向子菜单后的菜单 "stay hovered"

java - Prometheus 客户端是同步还是异步?

java - Android 上的 jackson : NoClassDefFoundError ObjectMapper error

java - Google firebase 检查 child 是否存在

java - 在 Java/Swing 中更改助记符修饰键