user6287736 user6287736 - 7 months ago 7
Java Question

How to let the user stop a java application

I have an application which mainly uses a bot to press keys when a condition is met. I am used to working with applets so I am wondering about how the user stops the application. I did it by using the task manager but that is not very user friendly, is it?
So how can I make I UI for a standalone java application? Or is there an other way to give the user the opportunity to stop the application?

Answer

First of all I need 50 reputation to comment, thats why I write an answer...

Secondly Do you have a JFrame?

If not Create a new JFrame, JPanel and JButton with:

JFrame frame = new JFrame("title");
JPanel  panel = new JPanel();
JButton button = new JButton("Close");

//You need this for the screen to show.
frame.setSize(width,height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);


//add the panel to the frame and the button to the panel 
frame.add(panel);
panel.add(button);
button.addActionListener(this);//the class needs to implements ActionListener

frame.setVisible(true);

//this is the actionperformed method which will run if the button is clicked.
public void actionPerformed(ActionEvent e) {
      if(e.getSource==button){//If you have more than one button.
          System.exit(0);
      }
}