[英]Layout for placing buttons in a panel in java swing
我正在嘗試以類似於此處顯示的方式放置按鈕:
我試過使用GridLayout
,列和行之間有一些空格,但無濟於事。 我怎樣才能做到這一點?
根據您想要實現的目標,您可以通過多種方式實現這一目標,我個人會使用GridBagLayout
,但那是因為我喜歡它;)
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 2;
//gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
add(new JButton("Up"), gbc);
gbc.gridx = 0;
add(new JButton("Left"), gbc);
gbc.gridx = 2;
add(new JButton("Right"), gbc);
gbc.gridx = 1;
add(new JButton("Down"), gbc);
}
}
}
您也可以使用多個面板來做某事,但這取決於您的需求
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.