Ok so I am trying to build a little program and I want to be able to click on the skate or dice button and have the program open a new JFrame that has been built in another class. Currently it opens its own JFrame that was built in this method. I have the other classes built i have put the skate class below the main menu method. If someone could help me get this work I would greatly appreciate it.

Another thing I tried is the getContentPane and that creates and exception in the thread

Main method

public class MainMenu extends JFrame {

    public MainMenu(){

        JPanel panel = new JPanel();

        ImageIcon i1 = new ImageIcon("H:/dice/skategamepic.jpg");

        JButton skate = new JButton(i1);
        skate.setPreferredSize(new Dimension(230,65));
        skate.setBorderPainted(false);
        panel.add(skate);

        skate.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            { 
                JFrame skate1 = new JFrame();
                skate1.setForeground(Color.lightGray);
                skate1.setSize(320, 480);
                skate1.setTitle("Welcome to Skate");
                skate1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                skate1.setVisible(true);
                skate1.getContentPane().add(new skate());

            }
        });



        JButton dice = new JButton("Dice");
        dice.setLocation(90,250);
        dice.setPreferredSize(new Dimension(120,50));
        panel.add(dice);
        dice.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            { 
                JFrame dice = new JFrame();
                dice.setForeground(Color.lightGray);
                dice.setSize(320, 480);
                dice.setTitle("Welcome to dice");
                dice.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                dice.setVisible(true);

            }
        });

    add(panel, BorderLayout.CENTER);



    }
    public static void main(String[] args) {
        MainMenu m = new MainMenu();

        m.setForeground(Color.lightGray);
        m.setSize(320, 480);
        m.setTitle("Welcome to Skate");
        m.setLocationRelativeTo(null);
        m.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        m.setVisible(true);

    }

}

skate class

public class skate extends JFrame {
    public skate(){



    }

    public static void main(String[] args) {

        skate s = new skate();

        s.setForeground(Color.lightGray);
        s.setSize(320, 480);
        s.setTitle("Welcome to Skate");
        s.setLocationRelativeTo(null);
        s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        s.setVisible(true);

    }

}

If you move the code lines 12-17 into Skate's constructor then you can simply call new Skate(); in your button's ActionListener

Edited 3 Years Ago by JamesCherrill

This article has been dead for over six months. Start a new discussion instead.