its a maybe a dumb question but i am curious to understand this thing….
The below code works but the one below that doesn’t work.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Menu extends JFrame
{
public Menu()
{
JMenuBar menubar = new JMenuBar();
ImageIcon icon = new ImageIcon("exit.png");
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
JMenuItem fileClose = new JMenuItem("Close",icon);
fileClose.setMnemonic(KeyEvent.VK_C);
fileClose.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event)
{System.exit(0);}
});
file.add(fileClose);
menubar.add(file);
setJMenuBar(menubar);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300,200);
setLocationRelativeTo(null);
}
public static void main (String args[])
{
new Menu();
}
}
The below one doesn’t work
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Menu extends JFrame
{
public Menu()
{
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300,200);
setLocationRelativeTo(null);
JMenuBar menubar = new JMenuBar();
ImageIcon icon = new ImageIcon("exit.png");
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
JMenuItem fileClose = new JMenuItem("Close",icon);
fileClose.setMnemonic(KeyEvent.VK_C);
fileClose.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event)
{System.exit(0);}
});
file.add(fileClose);
menubar.add(file);
setJMenuBar(menubar);
}
public static void main (String args[])
{
new Menu();
}
}
I thought Java supports free style coding !!! (that’s what it says in my Book)
PS: Please Someone Edit the Tile to suit the question correctly, I am not sure what to put in Title.
The issue in your 2nd code sample is that you are calling
setVisiblebefore you actually add stuff to the GUI. Your saying “Here’s some stuff, now show” while in the second one your saying “Show, now here’s some stuff“Fix: Move setVisible to the end of the constructor