我真的建議您使用網格包佈局,如果你使用的揮杆。其他佈局留下了許多不足之處。這都是一個偏好問題,如果你願意,你可以手動佈置 - 沒有正確的答案。
我更喜歡GridBag(或MigLayout - 對於他們自己的)的原因是,你有一個組件的首選大小和填充的概念。它已經有一段時間,因爲我編寫了鞦韆(我會盡力保持這種方式!),但你基本上是尋找類似:
{
//Pseudo Code, I'd have to go read the API again, I wrote a set of utilities so I wouldn't have to think about it.
GridBagConstraints constraints = ....;
constraints.weightX = 1.0; //fill the area by X
constraints.weightY = 1.0; //fill by Y
constraints.fill = GridBagConstraints.BOTH; //or one...
component.setPreferredSize(image.size());
layout.add(component, constraints);
}
基本上你在做什麼,在說「使用我的首選大小「作爲最低限度」,但根據這些規則進行填充。
另一種不使用佈局的方法是自己定位組件(這絕對沒有錯)。
{
JPanel panel =...;
panel.setLayout(null);
...
myButton3.setX(0);
myButton3.setY(2 * buttonHeight); //third button
myButton.setSize(myButton.getPreferredSize()); //which I assume you set
...
panel.add(myButton3);
...
}
無論如何,有很多選擇。不要覺得你需要使用佈局,寫你自己的。你應該關心這些事情,讓它工作,但你不應該受苦。佈局通常非常易於實現,您不應該害怕擺脫這種情況。所有這一切,GridBag會做你想做的。或者,Mig很棒,有一些很好的GUI編輯器。
UPDATE - > ------------------------------- 下面是一個簡潔的例子 - 我真誠地不主張這種編程風格,我只是不希望類垃圾郵件的例子。
package _tests;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class Grids extends JFrame
{
private static final long serialVersionUID = 1L;
public static void main(String ... args)
{
new Grids().setVisible(true);
}
public Grids()
{
//Null layout example
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(250, 300);
setMinimumSize(new Dimension(285, 300)); //Windows 8 ~ border size + scrollbar
setTitle("Test layouts");
JPanel scrollTarget = new JPanel()
{
private static final long serialVersionUID = 1L;
{
setSize(250, 1000);
setPreferredSize(new Dimension(250, 1000));
//setLayout(null); -- uncomment for absolute
setLayout(new GridBagLayout());
int lastX = 0;
int lastY = 0;
for(int i = 0; i < 5; i++)
{
final String label = "Button " + i;
JButton tmp = new JButton()
{
private static final long serialVersionUID = 1L;
{
setText(label);
setPreferredSize(new Dimension(250, 200)); //Preferred
}
};
tmp.setSize(tmp.getPreferredSize()); //What you're layout usually does..
//add(tmp);
//tmp.setLocation(lastX, lastY);
//lastY += tmp.getHeight();
add(tmp, getButtonConstraint(0, i));
}
}
};
add(new JScrollPane(scrollTarget));
}
private GridBagConstraints getButtonConstraint(int x, int y)
{
GridBagConstraints tmp = new GridBagConstraints();
tmp.fill = GridBagConstraints.BOTH;
tmp.weightx = 1.0;
tmp.weighty = 1.0;
tmp.gridx = x;
tmp.gridy = y;
tmp.anchor = GridBagConstraints.NORTHEAST;
return tmp;
}
}
這是我們學院教我們使用的。問題應該是,爲什麼是Java而不是C++? ;) –
@KrisPurdy在UI元素方面更具靈活性。 – GGrec
就你而言,它更多的是爲什麼Swing而不是HTML5?使用CSS設計用戶界面非常容易!語言都是一樣的,但支持它們的框架對於快速構建某些內容來說更爲重要。 –