How to have a class which contains all the UI elements for a JFrame?

50 Views Asked by At

so i've got two classes one which handels creating the JFrame and the other that would load the menu bar on the JFrame the code is like this:

import java.awt.Toolkit;
import javax.swing.JFrame;
import java.awt.Dimension;

import javax.swing.ImageIcon;
public class Main extends JFrame{
       static JFrame F = new Main();
static UI ui = new UI();
public Main()
{
    ImageIcon img = new ImageIcon("icon.png");
    setTitle("JFrame title");
    setJMenuBar(ui);
    setUndecorated(true);       
    //maximize window
    setExtendedState(getExtendedState() | MAXIMIZED_BOTH);
    setVisible(true);
    setIconImage(img.getImage());
}   
public static void main(String[] args)
{
}

} and then the UI code:

import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
public class UI extends JMenuBar{

JMenu menu  = new JMenu("File");
JMenuItem i1,i2;

public UI() {
i1 = new JMenuItem("Save");
i2 = new JMenuItem("Load");
menu.add(i1);
menu.add(i2);
add(menu);
}

public static void main (String[] args) {

    }
}

When i compiled no errors showed up i ran the code and i had only the JFrame, and no errors have i done any

1

There are 1 best solutions below

0
Amir M On BEST ANSWER

UI is still not initialized when called in setJMenuBar.

public class Main extends JFrame {
    static JFrame F = new Main();

    public Main() {
        UI ui = new UI();
        ImageIcon img = new ImageIcon("icon.png");
        setTitle("JFrame title");
        setJMenuBar(ui);
        setUndecorated(true);
        //maximize window
        setExtendedState(getExtendedState() | MAXIMIZED_BOTH);
        setVisible(true);
        setIconImage(img.getImage());
    }

    public static void main(String[] args) {
    }
}