-4

How do I make a button, that would exit java application? This has to be a button in-game. I should be able to manage his location. You see - I am brand new to java, and only explored it by watching tutorial series on how to make a RPG style game. So all that stuff with "How to change the buttons location, style, size etc." would be highly appreciated.

Kris
  • 21
  • 9

1 Answers1

1

Create your button & attach a listener to it that would call

System.exit(0);

on click. It shall shut down the JVM & your app.

EDIT:

JButton yourButton = new JButton("Exit");

yourButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        JButton clickedBtn = (JButton) e.getSource();

        if(clickedBtn == yourButton)
            System.exit(0);
        }
    }
});

// Or using Java8

yourButton.addActionListener(e -> {
    if(yourButton == (JButton) e.getSource())
        System.exit(0);
    }
});
Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
  • More info please. What commands do I need, what is the best way to insert this in code etc. – Kris Jan 08 '16 at 17:36
  • Thanks. Do I need a separate class for that? How do I change where does the button go? And can I give it textures? If yes, then how? – Kris Jan 08 '16 at 18:24
  • you have nothing to change here. Just apply this on the button of your choice. (It would be placed in a `JPanel` or a `JFrame`) – Mohammed Aouf Zouag Jan 08 '16 at 18:25
  • Uhm.. how do I do that? Sorry for being so dumb at Java... – Kris Jan 08 '16 at 18:28
  • Check this link : http://www.java2s.com/Code/JavaAPI/javax.swing/JButtonaddActionListenerActionListeneract.htm – Mohammed Aouf Zouag Jan 08 '16 at 18:30
  • Ok.. That didn't explain how can I change the position, texture and etc. of the button. Also - I need it in-game, which means no other tabs... So that wasn't really helpfull, sorry. But thanks for what You gave :) – Kris Jan 08 '16 at 19:02