我试图将两个按钮放置在左上角。但它们始终位于顶部中心。
我已经尝试过这个:
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 )。
这是我拍的照片。红色是我希望按钮的样子的草图。
<小时/>更新:
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/