Reputation: 2570
I'm have no trouble when creating menu bar and its item. But now, when I get a question how to make the menu items appeared as column & rows-like table shaped, I really don't know about that.
The goals is to create this kind of menu items using java. Check this link.
And right now, I just think that I should use a jpanel as menu item, and then applying a flowlayout and then adding many jlabel(s) as I could as menuitem inside the grid. But wouldn't it worst? What's the best deal to create the menu items such as the image preview on the above links?
I tried google, but found no related cases. CMIIW.
Upvotes: 2
Views: 3625
Reputation: 48045
The popup menu of a JMenu
instance is a standard container, so you can add to it whatever you want. It has a default layout, but you can change it.
Something like in your mockup is created by this code:
import javax.swing.*;
import java.awt.*;
public class Test {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Menu test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(600, 400));
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Test");
JPopupMenu popupMenu = menu.getPopupMenu();
popupMenu.setLayout(new GridLayout(5, 5));
for (int r = 0; r < 5; r++) {
for (int c = 0; c < 5; c++) {
popupMenu.add(new JMenuItem("(" + (r + 1) + ", " + (c + 1) + ")"));
}
}
menuBar.add(menu);
frame.setJMenuBar(menuBar);
frame.setVisible(true);
}
});
}
}
Upvotes: 6
Reputation: 1546
The simplest solution is just set the layout of JMenu's JPopupMenu and then add items like you normally would. There's no need to create a subclass.
Example:
import javax.swing.*;
import java.awt.*;
public class menu {
public static void main(String ... args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("A regular menu");
menu.add(new JMenuItem("Menu item"));
JMenu gridMenu = new JMenu("Menu with grid");
// This does the trick:
gridMenu.getPopupMenu().setLayout(new GridLayout(2, 2));
gridMenu.add("Top left");
gridMenu.add("Top right");
gridMenu.add("Bottom left");
gridMenu.add("Bottom right");
menu.add(gridMenu);
menuBar.add(menu);
JFrame frame = new JFrame("Menus");
frame.setJMenuBar(menuBar);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
Upvotes: 1
Reputation: 81960
I haven't seen a ready made component for anything like this. So I think you are on your own.
I see two possibilities:
JMenuItem is a JComponent, so you can add other components to it. You probably want to use some kind of grid based layout and add buttons or labels for the numbers.
Implement you own JMenuItem that displays your grid component instead of the normal JPopupMenu
In any case have a look at the source code of JMenu(Item) in order to understand how these components work.
Upvotes: 2