0

I'm very new to java I have been doing basic stuff and for my final project we wanted to create a gui rpg. Our problem right now is we can't figure out how to open another program by clicking the gui button. My friends told me you guys use eclipse so I don't have to show imports. Keep in mind I'm in highschool so don't judge too harsh :D Here is our code:

public class Narnia {

    private static final String BACKHGROUND_IMAGE_URL = "http://randomwallpapers.net/fantasy-castle-1920x1080-wallpaper328374.jpg";

    protected void initUI() throws MalformedURLException {
        JFrame frame = new JFrame(Narnia.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final ImageIcon backgroundImage = new ImageIcon(new URL(BACKHGROUND_IMAGE_URL));

        JLabel mainPanel = new JLabel(backgroundImage) {
            @Override
            public Dimension getPreferredSize() {
                Dimension size = super.getPreferredSize();
                Dimension lmPrefSize = getLayout().preferredLayoutSize(this);
                size.width = Math.max(size.width, lmPrefSize.width);
                size.height = Math.max(size.height, lmPrefSize.height);
                return size;
            }
        };

        mainPanel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.weightx = 1.0;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        for (int i = 0; i < 1; i++) {
            mainPanel.add(new JButton("Play" + ("")), gbc);
        }
        for (int i = 0; i < 1; i++) {
            mainPanel.add(new JButton("Credits " + ("")), gbc);
        }
        for (int i = 0; i < 1; i++) {
            mainPanel.add(new JButton("Exit " + ("")), gbc);
        }

        // Let's put a filler bottom component that will push the rest to the top
        gbc.weighty = 1.0;
        mainPanel.add(Box.createGlue(), gbc);
        frame.add(mainPanel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    new Narnia().initUI();
                    } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }
}

Here is the class we want to open:

public class chooseaclass {

    private static final String BACKHGROUND_IMAGE_URL = "http://randomwallpapers.net/fantasy-castle-1920x1080-wallpaper328374.jpg";

    protected void initUI() throws MalformedURLException {
        JFrame frame = new JFrame(chooseaclass.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final ImageIcon backgroundImage = new ImageIcon(new URL(BACKHGROUND_IMAGE_URL));

        JLabel mainPanel = new JLabel(backgroundImage) {
            @Override
            public Dimension getPreferredSize() {
                Dimension size = super.getPreferredSize();
                Dimension lmPrefSize = getLayout().preferredLayoutSize(this);
                size.width = Math.max(size.width, lmPrefSize.width);
                size.height = Math.max(size.height, lmPrefSize.height);
                return size;
            }
        };

        mainPanel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(40, 40, 40, 40);
        gbc.weightx = 1.0;
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        for (int i = 0; i < 1; i++) {
            mainPanel.add(new JButton("Archer" + ("")), gbc);
        }
        for (int i = 0; i < 1; i++) {
            mainPanel.add(new JButton("Mage " + ("")), gbc);
        }
        for (int i = 0; i < 1; i++) {
            mainPanel.add(new JButton("Knight " + ("")), gbc);
        }

        // Let's put a filler bottom component that will push the rest to the top
        gbc.weighty = 1.0;
        mainPanel.add(Box.createGlue(), gbc);
        frame.add(mainPanel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    new chooseaclass().initUI();
                    } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }
}
Aks
  • 395
  • 3
  • 11
Josh
  • 9
  • 3
  • dupe? http://stackoverflow.com/questions/13991007/execute-external-program-in-java – Marc B Oct 21 '16 at 15:41
  • From what I can tell so far your buttons don't actually do anything, do you know about [action listeners](https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html)? – Ash Oct 21 '16 at 15:43
  • @marc B what do you mean? – Josh Oct 21 '16 at 15:44
  • take out the main method in chooseaclass, add an action listener to the button you want to activate the chooseaclass gui, and then in that action listener you will create the chooseaclass object and call initUI – RAZ_Muh_Taz Oct 21 '16 at 15:45
  • 1
    @Josh: this is what Ash ment: http://docs.oracle.com/javase/tutorial/uiswing/components/button.html – Timothy Truckle Oct 21 '16 at 15:45
  • @marc b I don't know how to add action listerners to my for statements – Josh Oct 21 '16 at 15:46
  • @TimothyTruckle yeah, its been a while since I did GUI stuff – Ash Oct 21 '16 at 15:47
  • @RAZ_Muh_Taz My friend says he knows how to call initUI but doesn't understand the "chooseaclass object" – Josh Oct 21 '16 at 15:48
  • *"My friend says.."* If it's your friend coding this, it's your fried that needs to be posting here. As to the basic problem description, it seems to be a messed up design as the other ..components of this app should not be separate apps. based around a frame each with a main method, but instead separate components based on a panel. Then each panel can be displayed as a card in a card layout. – Andrew Thompson Oct 22 '16 at 01:43

1 Answers1

1

You need to add a listener to whatever button you want. In this case, we'll use an ActionListener.

Let's just use this existing line that you already have: mainPanel.add(new JButton("Play" + ("")), gbc);

First of all, to make it simpler, let's put that JButton in a variable: JButton playButton = new JButton("Play" + (""));

To add a listener, we need to use the method addActionListener().

Now add an ActionListener as an anonymous class so that we can implement a method that the system can call behind the scenes:

JButton playButton = new JButton("Play" + (""));
    playButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            new chooseaclass.initUI() //insantiate a new chooseaclass instance

        }

    });
    mainPanel.add(playButton, gbc);

Within the actionPerformed() method, I instantiated a chooseaclass. You can do whatever you want from there.

I wrote this code off the cuff without an editor so it may contain syntax errors.

Eames
  • 321
  • 2
  • 19
  • furthermore, `addActionListener()` will get added automatically if you're using the WindowBuilder plugin, drop the button on the viewer, and then double click the button you just dropped. It will jump you to the spot in the code where the action listener was created as well – jseashell Oct 21 '16 at 19:49