我有一個JPanel,例如,如果我點擊按鈕「插入」,我可以添加一個JButton和一個JLabel。我的問題是我需要在JButton下插入JLabel。 JLabel文本必須以JButton文本爲中心。之後,我想要一個10像素左右的空間再次使用我的「INSERT」按鈕,並在同一個方向上在JButton和JLabel上水平添加一對新對。我需要什麼樣的Java佈局?
謝謝!
PD:請嘗試補充您的問題。
我有一個JPanel,例如,如果我點擊按鈕「插入」,我可以添加一個JButton和一個JLabel。我的問題是我需要在JButton下插入JLabel。 JLabel文本必須以JButton文本爲中心。之後,我想要一個10像素左右的空間再次使用我的「INSERT」按鈕,並在同一個方向上在JButton和JLabel上水平添加一對新對。我需要什麼樣的Java佈局?
謝謝!
PD:請嘗試補充您的問題。
下面是一個簡單的例子,顯示一個動態的(這是我假設你想要的)設置允許插入未定義數量的面板:
public class AwesomeAnswer {
public static void main(String[] args) {
// please not that this is only an example and not a
// Swing thread safe way of starting a JFrame
JFrame frame = new JFrame();
JPanel content = (JPanel)frame.getContentPane();
// create our top panel that will hold all of the inserted panels
JPanel page = new JPanel();
page.setLayout(new BoxLayout(page, BoxLayout.Y_AXIS));
// add our page to the frame content pane
content.add(page);
// add two button/label panels
page.add(insert("This is an awesome answer", "Accept"));
page.add(insert("Say thank you", "Thank"));
frame.pack();
frame.setVisible(true);
}
public static final JPanel insert(String labelText, String buttonText) {
// create the label and the button
JLabel lbl = new JLabel(labelText);
JButton btn = new JButton(buttonText);
// create the panel that will hold the label and the button
JPanel wrapPanel = new JPanel(new GridBagLayout());
wrapPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// tell the grid bag how to behave
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 0;
gbc.gridheight = 2;
// make the button centered
JPanel buttonPanel = new JPanel(new FlowLayout(0, 0, FlowLayout.CENTER));
buttonPanel.add(btn);
// make the label centered
JPanel labelPanel = new JPanel(new FlowLayout(0, 0, FlowLayout.CENTER));
labelPanel.add(lbl);
// add our button and label to the grid bag with our constraints
wrapPanel.add(buttonPanel, gbc);
wrapPanel.add(labelPanel, gbc);
return wrapPanel;
}
}
謝謝你的幫助! – Chu 2012-04-28 00:39:32
我認爲你有類似的東西
rootPane
+-----panelButton
| +------JButton
|
+-----panelPanels
+-----panel
+---JButton
+---JLabel
的SpringLayout
可以幫助你
SpringUtilities.makeGrid(panel,
2, 1, //rows, cols
0, 0, //initialX, initialY
5, 5);//xPad, yPad
我會試試這個選擇。謝謝您的回答! – Chu 2012-04-28 00:40:19
http://docs.oracle.com/javase/tutori al/uiswing/layout/box.html – Andrew 2012-04-27 20:47:46
我認爲我應該在啓動GUI之前有一個設計(如屏幕)。 – 2012-04-27 21:03:48