I have got 2 different GridLayout
of buttons. They represent a game board and I like to add a title and a border to the GridLayout
to distinguish the user's board from the PC's board. The Gridlayout
is done, but I don't know how to add the title.
Like this?
Code below:
JFrame frame = new JFrame("GridLayout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout());
// Create the two grids
JPanel grid1 = new JPanel(new GridLayout(2,2,2,2));
JPanel grid2 = new JPanel(new GridLayout(2,2,2,2));
// Create borders
Border empty = BorderFactory.createEmptyBorder(10, 10, 10, 10);
Border blackLine = BorderFactory.createLineBorder(Color.black);
CompoundBorder line = new CompoundBorder(empty, blackLine);
Border grid1Border = BorderFactory.createTitledBorder(line, "Grid 1");
Border grid2Border = BorderFactory.createTitledBorder(line, "Grid 2");
//Grid 1
grid1.add(new JButton("Button 1"));
grid1.add(new JButton("Button 2"));
grid1.add(new JButton("Button 3"));
grid1.add(new JButton("Button 4"));
grid1.setBorder(grid1Border);
//Grid 2
grid2.add(new JButton("Button 5"));
grid2.add(new JButton("Button 6"));
grid2.add(new JButton("Button 7"));
grid2.add(new JButton("Button 8"));
grid2.setBorder(grid2Border);
frame.getContentPane().add(grid1);
frame.getContentPane().add(grid2);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Note: you can find the full list of constructors for further customization of the border (like color, position of text, justification of text) here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.