This solution doesn't use a JToolBar
, but a GridLayout
with multiple buttons. The program accepts n number of buttons and lays them in the container. The number of columns (or buttons) per row is constant and the number of rows grow based upon the number of buttons.
For example, if a row accommodates 8 columns or buttons - 12 buttons are placed in two rows. Here is some code to show what is possible. Note the program accepts an integer number (number of buttons) as command-line argument.
import javax.swing.*;
import java.awt.*;
public class ToolbarGrid {
private static final int MAX_BUTTONS_PER_ROW = 4;
public static void main(String [] args) throws Exception {
if (args.length == 0) {
System.out.println("Enter number of buttons as arg> java -cp . ToolbarGrid 9");
return;
}
int noOfButtons = Integer.parseInt(args[0]);
JFrame frame = new JFrame();
frame.setTitle("Testing Toolbar in a Grid");
GridLayout gLayout = new GridLayout(0, MAX_BUTTONS_PER_ROW); // 0 rows = any number of rows
JPanel panel = new JPanel();
panel.setLayout(gLayout);
panel = panelWithButtons(noOfButtons, panel);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
private static JPanel panelWithButtons(int noOfButtons, JPanel panel) {
for (int i = 0; i < noOfButtons; i++) {
panel.add(new JButton("Button_" + i+1));
}
return panel;
}
}
EDIT: In a similar manner, one can use multiple toolbars. Each toolbar limiting n number of buttons. Also, the number of buttons per toolbar can also be determined by the total width of buttons.