Reputation: 25
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. How can I achieve this?
Upvotes: 0
Views: 692
Reputation: 347184
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 ;)
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
Upvotes: 4