[英]Layout for placing buttons in a panel in java swing
I'm trying to place my buttons in a manner similar to what has been shown here:我正在尝试以类似于此处显示的方式放置按钮:
I've tried using the GridLayout
, with some amount of spaces between columns and rows, but to no avail.我试过使用
GridLayout
,列和行之间有一些空格,但无济于事。 How can I achieve this?我怎样才能做到这一点?
There are a number of ways you might achieve this depending on what you want to achieve, personally, I'd use a GridBagLayout
, but that's because I like it;)根据您想要实现的目标,您可以通过多种方式实现这一目标,我个人会使用
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);
}
}
}
You could also do something using multiple panels, but that would depend on your desired needs您也可以使用多个面板来做某事,但这取决于您的需求
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.