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.
Asked
Active
Viewed 263 times
-4
-
1You really need to provide some more context. What kind of game? Show some code. It really depends on how the entire program works. – Arc676 Jan 08 '16 at 14:04
-
Add a button with an action handler method calling `System.exit(0);` – Boris Pavlović Jan 08 '16 at 14:07
-
Please work on your search skills. – Hovercraft Full Of Eels Jan 08 '16 at 14:09
-
Arc676 well.. it has alot of code... It's a game afterall... – Kris Jan 08 '16 at 17:29
1 Answers
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
-
-
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