Help making a grid inside of a JPanel
I thought the logical way to do this was with a GridLayout. However I have found that to not be the case. I need to make a grid of perfect squares that is also a square (10 x 10) or (50 x 50). When I use GridLayout, it decides to make all of my buttons rectangles. Is there a better way to do this?
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class buttonGrid extends JFrame
{
private JPanel buttonPanel, leftPanel, rightPanel, bottomPanel;
private JScrollPane buttonScroll, leftScroll, rightScroll, bottomScroll;
public buttonGrid()
{
super("GridLayout Sucks");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
this.setSize(400, 400);
leftPanel = new JPanel();
leftPanel.setLayout(new GridLayout(10, 1, 1, 1));
for (int i = 0; i < 10; i++)
{
JButton button = new JButton("L" + i);
leftPanel.add(button, i);
}
leftScroll = new JScrollPane(leftPanel);
leftScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
rightPanel = new JPanel();
rightPanel.setLayout(new GridLayout(10, 1, 1, 1));
for (int i = 0; i < 10; i++)
{
JButton button = new JButton("R" + i);
rightPanel.add(button, i);
}
rightScroll = new JScrollPane(rightPanel);
rightScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(30, 30, 1, 1));
for (int i = 0; i < 30; i++)
{
for (int j = 0; j < 30; j++)
{
JButton button = new JButton(j + "," + i);
buttonPanel.add(button);
}
}
buttonScroll = new JScrollPane(buttonPanel);
buttonScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
buttonScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
this.add(buttonScroll, BorderLayout.CENTER);
this.add(rightScroll, BorderLayout.EAST);
this.add(leftScroll, BorderLayout.WEST);
this.setVisible(true);
}
public static void main(String[] args)
{
new buttonGrid();
}
}
Thanks for reading my post. I know its not the best code. I actually have an entire project and this is just an aspect of the project that I am trying to get right.