Reputation: 49
Hi i'm trying to use 2 arrays, to create a JMenuBar with JMenus and JMenuItems. I'm fairly new to using GUI, I made a class to achieve this, but it just isn't working.
import java.util.*;
import javax.swing.*;
public class MenuBar {
String[] titulos = {"Raices","Sistemas","Interpolacion","Dif. e Int.","Ecuaciones"};
String[][] subTitulos = {{"Biseccion","Falsa Posicion","Secante","Newton-Rhapson","Aprox. Sucesivas","Newton 2ndo. Orden"},
{"Gauss","Gauss-Jordan","Montante","Cramer","Jacobi","Gauss-Seidel"},
{"Diferencias Finitas","Newton","LaGrange","Min. Cuadrados"},
{"Por Limites","Diferencias Finitas","Trapecio","Trapecio","Simpson","Simpson"},
{"Euler","Euler-Gauss"}};
public JMenuBar menuBar = new JMenuBar();
public JMenu[] menus;
public List<List<JMenuItem>> menuItems;
public MenuBar(){
menus = new JMenu[titulos.length];
menuItems = new ArrayList<List<JMenuItem>>();
for (int i=0;i<titulos.length;i++){
menus[i]= new JMenu(titulos[i]);
menuItems.add(new ArrayList<JMenuItem>());
for(int j=0;j<subTitulos[i].length;j++){
menuItems.get(i).add(new JMenuItem(subTitulos[i][j]));
menus[i].add(menuItems.get(i).get(j));
}
menuBar.add(menus[i]);
}
}
}
The code works up to the point where I create the JMenu's, that works flawlessly. But as soon as i create a JMenuItem inside the second loop, even if I dont store it or attach it, it just breaks, and it doesn't show the menuBar in the frame.
It's quite bizarre because it actually works, very rarely which is even more confusing.
this is my main class:
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Menu");
frame.setVisible(true);
frame.setSize(900, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MenuBar menuBar = new MenuBar();
frame.setJMenuBar(menuBar.menuBar);
}
}
Upvotes: 1
Views: 506
Reputation: 24879
GUI-related code must run in the GUI event thread. You probably want to do this:
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Menu");
frame.setVisible(true);
frame.setSize(900, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MenuBar menuBar = new MenuBar();
frame.setJMenuBar(menuBar.menuBar);
});
It's also a good idea to do setVisible
last.
SwingUtilities.invokeLater(() -> {
MenuBar menuBar = new MenuBar();
JFrame frame = new JFrame("Menu");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(menuBar.menuBar);
frame.setSize(900, 800);
frame.setVisible(true);
});
Upvotes: 1