Reputation: 7894
I'm trying to create a JDialog like the Symbol dialog in Microsoft Word that you get by choosing Symbol... from the Insert menu. Basically, it's an n x m (n and m are not known until runtime) grid of small buttons. I've got a first version of this working nicely using a GridLayout. The problem is that when you resize the dialog (and there is a requirement that you should be able to resize it), the size of the buttons changes. I need the size of the buttons to remain constant.
But I want the dimensions of the grid containing the buttons to change. For example, if the dialog gets wider, but stays the same height, the number of rows should lessen, while the number of columns increases.
I've thought of a couple of ways to fix this:
What is the best way to solve this layout problem?
Upvotes: 3
Views: 9308
Reputation: 324137
if the dialog gets wider, but stays the same height, the number of rows should lessen, while the number of columns increases.
Wrap Layout might be what you are looking for.
Upvotes: 2
Reputation: 137382
Create a buttons panel with GridLayout and set a fixed size (could be calculated at runtime of course) to it. The buttons panel should be contained in a panel of BoxLayout.
Check out the BoxLayout Tutorial
Very Very basic example:
public static void main(String[] args) throws Exception
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel buttonPanel = new JPanel();
JPanel containerPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(2,2));
buttonPanel.add(new JButton("1"));
buttonPanel.add(new JButton("2"));
buttonPanel.add(new JButton("3"));
buttonPanel.add(new JButton("4"));
buttonPanel.setPreferredSize(new Dimension(300, 400));
containerPanel.add(buttonPanel);
frame.getContentPane().add(containerPanel);
frame.pack();
frame.setVisible(true);
}
Upvotes: 5
Reputation: 88727
FlowLayout would be the way to go but you might have some configuration problems. What layout manager does the parent component use?
Upvotes: 2
Reputation: 30838
I had a similar issue with a single column of buttons, and found that MiGLayout
(third-party, available here) was simple and effective for this. It helped both with making a grid and with setting button sizes, although it took me a day or two to get used to its syntax.
But the key is really setting button sizes; GridLayout
certainly seems like the way to go for a layout that is, well, a grid. I haven't tested, but I suspect that the built-in setXSize()
methods would work just as well. The GridBagLayout
tutorial has examples of some things you can do with sizing/positioning.
Upvotes: 2