Search code examples
javaswingjframelook-and-feel

JFrame looks different depending on how its loaded


I have a JFrame:

public class Help extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Throwable e) {
            e.printStackTrace();
        }
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Help frame = new Help();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Help() {
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);
    }

}

If i run this in Eclipse i get the following: How i want it to look

Now if call this from the ActionListener of a JButton within another JFrame using:

btnHelp.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent arg0) {
                EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        try {
                            Help frame = new Help();
                            frame.setVisible(true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

        });

Then the JFrame loads looking like this: How i don't want it to look

This looks ugly to me. Why isn't the first style loading when i initialize the JFrame from within another JFrames JButton ActionListener? It seems to me like i'm running exactly the same code with both methods of loading it.


Solution

  • In your second example, the new JFrame will have the same look and feel as the other JFrames in the application.

    Your comments indicate that you are not setting the look and feel for that application.

    Use a line similar to the one in your first example to do this.