I cant get my try catch to work in java - java

So here is my GUI as you can see.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Frame1 {
private JFrame frame;
private JTextField textFieldnum1;
private JTextField textFieldnum2;
private JTextField textFieldAns;
private Termostat thermo;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame1 window = new Frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Frame1() {
initialize();
}
private void initialize() {
thermo = new Termostat();
frame = new JFrame();
frame.setBounds(100, 100, 696, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textFieldnum1 = new JTextField();
textFieldnum1.setBounds(176, 11, 147, 46);
frame.getContentPane().add(textFieldnum1);
textFieldnum1.setColumns(10);
textFieldnum2 = new JTextField();
textFieldnum2.setBounds(176, 154, 147, 46);
frame.getContentPane().add(textFieldnum2);
textFieldnum2.setColumns(10);
JButton btnNewButton = new JButton("Convert to celcius");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double myf = thermo.convertToCelcius(Double.parseDouble(textFieldnum1.getText()));
textFieldAns.setText(String.valueOf(myf));
}
});
btnNewButton.setBounds(0, 0, 171, 68);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("Convert to fahrenheit");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double myf = thermo.convertToFahrenheit(Double.parseDouble(textFieldnum2.getText()));
textFieldAns.setText(String.valueOf(myf));
}
});
btnNewButton_1.setBounds(0, 143, 171, 68);
frame.getContentPane().add(btnNewButton_1);
textFieldAns = new JTextField();
textFieldAns.setBounds(354, 90, 147, 46);
frame.getContentPane().add(textFieldAns);
textFieldAns.setColumns(10);
JLabel lblNewLabel = new JLabel("Converted");
lblNewLabel.setBounds(285, 94, 112, 38);
frame.getContentPane().add(lblNewLabel);
}
}
And here comes my problem. When i made my class that i wanna run the input in to calculate celcius to fahrenheit, i dont want it to crash when i type anything else than numbers. but i cant get it to work so i need you guys help to get the try catch to work.
Im very thankful for all help i get.
import javax.swing.JOptionPane;
public class Termostat {
public double convertToCelcius(double input) {
double far = 0;
try {
far = (input - 32) * 5 / 9;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Wrong input");
return far;
}
return far;
}
public double convertToFahrenheit(double input) {
double cel = 1;
try {
cel = (input * 9 / 5) + 32;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Wrong input");
return cel;
}
return cel;
}
}

This is the line where you get probably an Exception:
double myf = thermo.convertToFahrenheit(Double.parseDouble(textFieldnum2.getText()));
So guard it with a NumberFormatException (parseDouble).

You can use the NumberUtil.isNumber(str) to check if the input is a number. Here is more information

you must use try catch when you want to parse text field texts to Double using this method Double.parseDouble(text)
write them them like this and remove your try catches inside your convertToFahrenheit and convertToCelcius methods
JButton btnNewButton_1 = new JButton("Convert to fahrenheit");
btnNewButton_1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
try { // start trying to parse input string to double
double myf = thermo.convertToFahrenheit(Double.parseDouble(textFieldnum2.getText()));
textFieldAns.setText(String.valueOf(myf));
} catch (NumberFormatException ex) { // catch the exception that you mentioned
JOptionPane.showMessageDialog(null, "Wrong input");
textFieldAns.setText("");
}
}
});

Related

Variables in GUI application not updating

I am currently making a very simple Java GUI application, but have run into the problem that my variables are unable to update. The application is a simple basketball scorekeeper and the score integers do not update nor does the text of the labels showing them. There are no errors so I am unsure as of why nothing is updating. The code:
ScoreWindow.java
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.SpringLayout;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.FlowLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class ScoreWindow implements ScoreListener {
private JFrame frmScorewindow;
public volatile JLabel homeScoreLabel;
public JLabel awayScoreLabel;
public volatile int homeScore, awayScore;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ScoreWindow window = new ScoreWindow();
window.frmScorewindow.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ScoreWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
// Init Scores
homeScore = 0;
awayScore = 0;
frmScorewindow = new JFrame();
frmScorewindow.setResizable(false);
frmScorewindow.setTitle("Score Keeper");
frmScorewindow.setBounds(100, 100, 551, 348);
frmScorewindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmScorewindow.getContentPane().setLayout(null);
JButton homeScore2 = new JButton("+2");
homeScore2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ScoreListener listener = new ScoreWindow();
listener.homeScore(2);
}
});
homeScore2.setBounds(110, 129, 117, 29);
frmScorewindow.getContentPane().add(homeScore2);
JButton homeScore3 = new JButton("+3");
homeScore3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ScoreListener listener = new ScoreWindow();
listener.homeScore(3);
}
});
homeScore3.setBounds(110, 156, 117, 29);
frmScorewindow.getContentPane().add(homeScore3);
JButton awayScore2 = new JButton("+2");
awayScore2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ScoreListener listener = new ScoreWindow();
listener.awayScore(2);
}
});
awayScore2.setBounds(332, 129, 117, 29);
frmScorewindow.getContentPane().add(awayScore2);
JButton awayScore3 = new JButton("+3");
awayScore3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ScoreListener listener = new ScoreWindow();
listener.awayScore(3);
}
});
awayScore3.setBounds(332, 156, 117, 29);
frmScorewindow.getContentPane().add(awayScore3);
JButton resetButton = new JButton("Reset");
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ScoreListener listener = new ScoreWindow();
listener.reset();
}
});
resetButton.setBounds(225, 220, 117, 29);
frmScorewindow.getContentPane().add(resetButton);
homeScoreLabel = new JLabel("000");
homeScoreLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 24));
homeScoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
homeScoreLabel.setBounds(138, 88, 61, 29);
frmScorewindow.getContentPane().add(homeScoreLabel);
awayScoreLabel = new JLabel("000");
awayScoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
awayScoreLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 24));
awayScoreLabel.setBounds(361, 88, 61, 29);
frmScorewindow.getContentPane().add(awayScoreLabel);
JLabel lblHome = new JLabel("Home");
lblHome.setHorizontalAlignment(SwingConstants.CENTER);
lblHome.setBounds(138, 60, 61, 16);
frmScorewindow.getContentPane().add(lblHome);
JLabel lblAway = new JLabel("Away");
lblAway.setHorizontalAlignment(SwingConstants.CENTER);
lblAway.setBounds(361, 60, 61, 16);
frmScorewindow.getContentPane().add(lblAway);
JLabel title = new JLabel("Score Keeper App");
title.setHorizontalAlignment(SwingConstants.CENTER);
title.setBounds(180, 33, 200, 16);
frmScorewindow.getContentPane().add(title);
}
#Override
public void reset() {
print("reset();");
homeScore = 0;
awayScore = 0;
awayScoreLabel.setText("" + awayScore);
homeScoreLabel.setText("" + homeScore);
}
#Override
public void awayScore(int n) {
print("awayScore();");
awayScore+=n;
awayScoreLabel.setText("" + awayScore);
}
#Override
public void homeScore(int n) {
print("homeScore();");
print(homeScoreLabel.getText());
homeScore = homeScore + n;
homeScoreLabel.setText("" + homeScore);
homeScoreLabel.repaint();
homeScoreLabel.revalidate();
}
static void print(Object o) {
System.out.println(o);
}
}
ScoreListener.java
public interface ScoreListener {
public void reset();
public void awayScore(int n);
public void homeScore(int n);
}
Thank you!!
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ScoreWindow window = new ScoreWindow();
window.frmScorewindow.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
You create your window with the above code.
JButton homeScore2 = new JButton("+2");
homeScore2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ScoreListener listener = new ScoreWindow();
listener.homeScore(2);
}
});
But then you create a second instance of the window.
Don't do this. You only need to create once instance of your class. All other code to reference this instance.
Your ActionListner class is defined in the ScoreWindow class you you can just reference the "homeScore()" method directly.

Java no UI update after Thread

So, I have got this problem in my Java Swing project where I am making a bot that automatically runs through a whileloop and outputs a text that the user can define in a textfield.
Here you can see my code for adding a textline into a jlabel into my frame:
btnAddTalking = new JButton("Add");
btnAddTalking.setBounds(144, 211, 146, 23);
btnAddTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!txtTalk.getText().equals("")) {
JLabel newLabel = new JLabel(txtTalk.getText());
newLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
frame.remove(newLabel);
frame.repaint();
}
});
newLabel.setHorizontalAlignment(SwingConstants.CENTER);
newLabel.setBounds(159, yLabel, 101, 20);
frame.getContentPane().add(newLabel);
yLabel = yLabel + 20;
frame.getContentPane().setLayout(null);
frame.repaint();
Talk.addTalk(txtTalk.getText());
}
}
});
frame.getContentPane().add(btnAddTalking);
frame.getContentPane().add(lblNewLabel);
frame.getContentPane().add(lblDelayInMs);
After that I start my bot by pressing the following button:
btnStartTalking = new JButton("Start AutoTalk");
btnStartTalking.setBounds(144, 143, 146, 23);
btnStartTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int robotDelay = Integer.parseInt(timeTalk.getText());
Talk.action = "start";
robotTalk = txtTalk.getText();
if (rdbtnRed.isSelected() == true) {
robotTalk = "red:" + txtTalk.getText();
} else if (rdbtnFlash.isSelected() == true) {
robotTalk = "flash1:" + txtTalk.getText();
} else if (rdbtnGlow.isSelected() == true) {
robotTalk = "glow1:" + txtTalk.getText();
}
autoTalkStart = new Runnable() {
public void run() {
try {
btnStartTalking.setEnabled(false);
btnStopTalking.setEnabled(true);
btnAddTalking.setEnabled(false);
Talk test = new Talk(robotDelay);
} catch (AWTException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
new Thread(autoTalkStart).start();
}
});
Via that button I start a thread which runs through a code that outputs the string. But after I've runned that Thread, my frame doesn't show newly-added jlabels anymore that you've added by clicking the btnAddTalking-button after you've run the Thread by clicking on the btnStartTalking-button! So, my question is: does anyone now how that's even possible (why my UI doesn't update anymore after i've run the thread)?
Greetz,
Jarnov
Here you can see my whole code for the two classes (class 1):
import java.awt.EventQueue;
import java.awt.event.InputEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import com.sun.glass.events.KeyEvent;
import com.sun.glass.ui.Robot;
import java.awt.AWTException;
import java.awt.BorderLayout;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.GroupLayout.Alignment;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.JRadioButton;
public class AutoTalker {
private static JFrame frame;
private JTextField txtTalk;
private JTextField timeTalk;
public String robotTalk;
private JButton btnStopTalking;
private JButton btnAddTalking;
private JButton btnStartTalking;
private int yLabel = 266;
private Runnable autoTalkStart;
/**
* Launch the application.
*/
public static void NewFrame() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AutoTalker window = new AutoTalker();
window.frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* #return
*/
public AutoTalker() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 415);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("AutoTalker");
frame.getContentPane().setLayout(null);
JRadioButton rdbtnGlow = new JRadioButton("Glow");
rdbtnGlow.setBounds(6, 113, 64, 23);
rdbtnGlow.setActionCommand("glow");
frame.getContentPane().add(rdbtnGlow);
JRadioButton rdbtnFlash = new JRadioButton("Flash");
rdbtnFlash.setBounds(182, 113, 69, 23);
rdbtnGlow.setActionCommand("flash");
frame.getContentPane().add(rdbtnFlash);
JRadioButton rdbtnRed = new JRadioButton("Red");
rdbtnRed.setBounds(364, 113, 64, 23);
rdbtnGlow.setActionCommand("red");
frame.getContentPane().add(rdbtnRed);
final ButtonGroup rdbtnPressed = new ButtonGroup();
rdbtnPressed.add(rdbtnRed);
rdbtnPressed.add(rdbtnFlash);
rdbtnPressed.add(rdbtnGlow);
txtTalk = new JTextField();
txtTalk.setBounds(130, 28, 173, 20);
txtTalk.setColumns(10);
btnStopTalking = new JButton("Stop AutoTalk");
btnStopTalking.setBounds(144, 177, 146, 23);
btnStopTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Talk.action = "stop";
btnStartTalking.setEnabled(true);
btnStopTalking.setEnabled(false);
btnAddTalking.setEnabled(true);
frame.repaint();
}
});
btnStartTalking = new JButton("Start AutoTalk");
btnStartTalking.setBounds(144, 143, 146, 23);
btnStartTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int robotDelay = Integer.parseInt(timeTalk.getText());
Talk.action = "start";
robotTalk = txtTalk.getText();
if (rdbtnRed.isSelected() == true) {
robotTalk = "red:" + txtTalk.getText();
} else if (rdbtnFlash.isSelected() == true) {
robotTalk = "flash1:" + txtTalk.getText();
} else if (rdbtnGlow.isSelected() == true) {
robotTalk = "glow1:" + txtTalk.getText();
}
autoTalkStart = new Runnable() {
public void run() {
try {
btnStartTalking.setEnabled(false);
btnStopTalking.setEnabled(true);
btnAddTalking.setEnabled(false);
Talk test = new Talk(robotDelay);
} catch (AWTException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
new Thread(autoTalkStart).start();
frame.repaint();
}
});
timeTalk = new JTextField();
timeTalk.setBounds(174, 71, 86, 20);
timeTalk.setColumns(10);
JLabel lblNewLabel = new JLabel("Text:");
lblNewLabel.setBounds(24, 28, 46, 20);
JLabel lblDelayInMs = new JLabel("Delay in ms:");
lblDelayInMs.setBounds(24, 71, 101, 20);
frame.getContentPane().add(txtTalk);
frame.getContentPane().add(btnStartTalking);
frame.getContentPane().add(btnStopTalking);
frame.getContentPane().add(timeTalk);
btnAddTalking = new JButton("Add");
btnAddTalking.setBounds(144, 211, 146, 23);
btnAddTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!txtTalk.getText().equals("")) {
JLabel newLabel = new JLabel(txtTalk.getText());
newLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
frame.remove(newLabel);
frame.repaint();
}
});
newLabel.setHorizontalAlignment(SwingConstants.CENTER);
newLabel.setBounds(159, yLabel, 101, 20);
frame.getContentPane().add(newLabel);
yLabel = yLabel + 20;
frame.getContentPane().setLayout(null);
frame.repaint();
Talk.addTalk(txtTalk.getText());
}
}
});
frame.getContentPane().add(btnAddTalking);
frame.getContentPane().add(lblNewLabel);
frame.getContentPane().add(lblDelayInMs);
btnStopTalking.setEnabled(false);
}
}
class 2:
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.ArrayList;
public class Talk extends AutoTalker {
Robot robot = new Robot();
public static String action;
public static ArrayList<String> Talks = new ArrayList<String>();
public Talk(int wait) throws AWTException, InterruptedException {
robot.delay(5000);
while(action == "start") {
for(int i = 0; i < Talks.size();i++) {
String text = Talks.get(i);
type(text);
robot.delay(wait);
}
}
}
public static void addTalk(String text) {
Talks.add(text);
}
private void type(String s)
{
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
switch(c) {
case '!':
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_1);
robot.keyRelease(KeyEvent.VK_SHIFT);
robot.keyRelease(KeyEvent.VK_1);
break;
case ':':
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SHIFT);
break;
default:
robot.keyPress(Character.toUpperCase(c));
break;
}
robot.delay(10);
}
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.delay(10);
}
}
Use instead
invalidate();
validate();

Swing Components invisible

When I run my code there is only the empty frame. To see the JButton and the JTextFields I have to search and click on them before they are visible. I searched everywhere on the Internet but I found nothing. I also set the visibility to true and added the JComponents. Here is my Code:
Frame Fenster = new Frame();
And this...
package me.JavaProgramm;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class Frame extends JFrame {
private JButton bChange;
private JTextField tvonEur;
private JTextField tzuOCur; //andere Währung (other Currency)
private JTextField tzuEur;
private JTextField tvonOCur;
private JComboBox cbCur; //Wärhung wählen
private String curName;
private double faktorUSD;
private double faktorGBP;
private static String[] comboCur = {"USD", "GBP"};
public Frame() {
setLayout(null);
setVisible(true);
setSize(400, 400);
setTitle("Währungsrechner");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setAlwaysOnTop(true);
setResizable(false);
Font schrift = new Font("Serif", Font.PLAIN + Font.ITALIC, 30);
tvonEur = new JTextField("Euro");
tvonEur.setSize(80, 25);
tvonEur.setLocation(20, 50);
tvonEur.requestFocusInWindow();
tvonEur.selectAll();
tzuEur = new JTextField("Euro");
tzuEur.setSize(80, 25);
tzuEur.setLocation(20, 150);
tzuEur.requestFocusInWindow();
tzuEur.selectAll();
bChange = new JButton("Euro zu US-Dollar");
bChange.setSize(120, 25);
bChange.setLocation(110, 50);
tzuOCur = new JTextField("US-Dollar");
tzuOCur.setSize(80, 25);
tzuOCur.setLocation(240, 50);
tzuOCur.requestFocusInWindow();
tzuOCur.selectAll();
tvonOCur = new JTextField("US-Dollar");
tvonOCur.setSize(80, 25);
tvonOCur.setLocation(240, 50);
tvonOCur.requestFocusInWindow();
tvonOCur.selectAll();
cbCur = new JComboBox(comboCur);
cbCur.setSize(100, 20);
cbCur.setLocation(100, 100);
tvonEur.setVisible(true);
tzuEur.setVisible(true);
tzuOCur.setVisible(true);
tvonOCur.setVisible(true);
bChange.setVisible(true);
cbCur.setVisible(true);
add(tvonEur);
add(bChange);
add(tzuOCur);
add(cbCur);
Currency currency = new Currency();
String strUSD = currency.convertUSD();
try {
NumberFormat formatUSD = NumberFormat.getInstance(Locale.GERMANY);
Number numberUSD = formatUSD.parse(strUSD);
faktorUSD = numberUSD.doubleValue();
System.out.println(faktorUSD);
} catch (ParseException e) {
System.out.println(e);
}
String strGBP = currency.convertGBP();
try {
NumberFormat formatGBP = NumberFormat.getInstance(Locale.GERMANY);
Number numberGBP = formatGBP.parse(strGBP);
faktorGBP = numberGBP.doubleValue();
System.out.println(faktorGBP);
} catch (ParseException e) {
System.out.println(e);
}
cbCur.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cbCur = (JComboBox) e.getSource();
curName = (String) cbCur.getSelectedItem();
if (curName == "USD") {
tzuOCur.setText("US-Dollar");
} else if (curName == "GBP") {
tzuOCur.setText("British-Pound");
}
}
});
bChange.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (curName == "USD") {
try {
Double doubleEUR = Double.parseDouble(tvonEur.getText());
Double doubleUSD = doubleEUR * faktorUSD;
tzuOCur.setText(Double.toString(roundScale3(doubleUSD)));
} catch (NumberFormatException nfe) {
System.out.println("Gebe einen richten Wert ein!");
}
} else if (curName == "GBP") {
try {
Double doubleEUR = Double.parseDouble(tvonEur.getText());
Double doubleGBP = doubleEUR * faktorGBP;
tzuOCur.setText(Double.toString(roundScale3(doubleGBP)));
} catch (NumberFormatException nfe) {
System.out.println("Gebe einen richten Wert ein!");
}
}
}
});
}
public static double roundScale3(double d) {
return Math.rint(d * 1000) / 1000.;
}
}
Try moving setVisible(true) after you add the children to the parent container.
Generally with Swing it's considered good practice to put code that updates visible components in the event dispatching thread, like this:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Frame.this.setVisible(true);
}
});

Issues with invokeLater

I'm having issues updating a JLabel value using invokeLater.
I have a separate method outside of the main function that runs invokeLater, but when I click the search button to update the value, it's not updating in the same instance of the gui.
I have to relaunch the gui in eclipse to get the value to change.
I'm not sure what I'm doing wrong so any help is greatly appreciated.
I'm running this method threadStart(); in the actionListener of the button.
Here's the method
private void threadStart() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
testLabel.setText(CN);
}
Here's the full class as a reference.
import java.awt.EventQueue;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.GridLayout;
import javax.naming.ldap.LdapName;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.awt.Color;
import java.awt.Font;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JTextArea;
import javax.swing.JTable;
public class MISControlPanel {
JFrame frame;
static JTextField textField;
private JTextField textField_1;
final JTextArea textArea = new JTextArea();
JLabel selectedComputerFromAD = new JLabel("testing");
String sCurrentLine = null;
String CN = null;
JLabel testLabel = new JLabel("test");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MISControlPanel window = new MISControlPanel();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*
* #throws IOException
*
* #wbp.parser.entryPoint
*/
public MISControlPanel() throws IOException {
initialize();
}
/**
* Initialize the contents of the frame.
*
* #throws IOException
*/
private void initialize() throws IOException {
frame = new JFrame();
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.getContentPane().setForeground(Color.RED);
frame.setBounds(100, 100, 658, 618);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setTitle("MIS Advanced Computerers");
frame.setResizable(false);
FileWriter fw = new FileWriter("C:\\Users\\anoc5f\\Desktop\\Output.txt");
File tempFile = new File("myTempFile.txt");
JButton searchComputerButton = new JButton("Search");
searchComputerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
threadStart();
String line;
BufferedWriter bw = null;
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(tempFile));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String s = null;
Process p = null;
/*
* try { // p = Runtime.getRuntime().exec(
* "cmd /c start c:\\computerQuery.bat computerName"); } catch
* (IOException e1) { // TODO Auto-generated catch block
* e1.printStackTrace(); }
*/
try {
p = Runtime.getRuntime().exec("c:\\computerQuery.bat");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
StringBuffer sbuffer = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(p
.getInputStream()));
try {
while ((line = in.readLine()) != null) {
System.out.println(line);
// textArea.append(line);
String dn = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
LdapName ldapName = new LdapName(dn);
String commonName = (String) ldapName.getRdn(
ldapName.size() - 1).getValue();
}
ComputerQuery.sendParam();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvalidNameException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally
{
try {
fw.close();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ComputerQuery.sendParam();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
testLabel.setText(CN);
}
});
}
});
try (BufferedReader br = new BufferedReader(new FileReader(
"resultofbatch.txt"))) {
final Pattern PATTERN = Pattern.compile("CN=([^,]+).*");
try {
while ((sCurrentLine = br.readLine()) != null) {
String[] tokens = PATTERN.split(","); // This will return
// you a array,
// containing the
// string array
// splitted by what
// you write inside
// it.
// should be in your case the split, since they are
// seperated by ","
// System.out.println(sCurrentLine);
CN = sCurrentLine.split("CN=", -1)[1].split(",", -1)[0];
System.out.println(CN);
testLabel.setText(CN);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
// SwingUtilities.invokeLater(updateCN());
searchComputerButton.setBounds(419, 19, 89, 20);
frame.getContentPane().add(searchComputerButton);
textField = new JTextField();
textField.setBounds(285, 19, 124, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblComputerName = new JLabel("Computer Name:");
lblComputerName.setForeground(Color.BLACK);
lblComputerName.setFont(new Font("Tahoma", Font.BOLD, 14));
lblComputerName.setBounds(159, 13, 124, 29);
frame.getContentPane().add(lblComputerName);
JLabel lblSelectedComputer = new JLabel("Selected Computer:");
lblSelectedComputer.setFont(new Font("Tahoma", Font.BOLD, 14));
lblSelectedComputer.setBounds(205, 78, 143, 30);
frame.getContentPane().add(lblSelectedComputer);
java.net.InetAddress localMachine = null;
try {
localMachine = java.net.InetAddress.getLocalHost();
} catch (UnknownHostException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
textArea.setBackground(Color.GRAY);
textArea.setForeground(Color.WHITE);
textArea.setFont(textArea.getFont().deriveFont(Font.BOLD));
textArea.setBounds(10, 387, 632, 191);
textArea.setEditable(false); // might cause design view not to come up
frame.getContentPane().add(textArea);
JButton btnNewButton = new JButton("SSO REPAIR");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton.setBounds(36, 183, 132, 23);
frame.getContentPane().add(btnNewButton);
JLabel lblNewLabel = new JLabel("Batch File Fixes");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 12));
lblNewLabel.setBounds(53, 158, 115, 14);
frame.getContentPane().add(lblNewLabel);
JLabel lblIpAddress = new JLabel("IP Address:");
lblIpAddress.setFont(new Font("Tahoma", Font.BOLD, 14));
lblIpAddress.setBounds(261, 104, 102, 22);
frame.getContentPane().add(lblIpAddress);
JLabel label = null;
try {
label = new JLabel(Inet4Address.getLocalHost().getHostAddress()); // Get
// User
// ID
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
label.setFont(new Font("Tahoma", Font.BOLD, 14));
label.setForeground(Color.RED);
label.setBounds(349, 105, 99, 21);
frame.getContentPane().add(label);
JLabel lblPcCommunication = new JLabel("PC Communication");
lblPcCommunication.setFont(new Font("Tahoma", Font.BOLD, 12));
lblPcCommunication.setBounds(279, 158, 115, 14);
frame.getContentPane().add(lblPcCommunication);
JButton btnPingComputer = new JButton("PING");
btnPingComputer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnPingComputer.setBounds(306, 183, 64, 23);
frame.getContentPane().add(btnPingComputer);
JButton remoteAssistanceButton = new JButton(
"Remote Assistance by PC Name");
remoteAssistanceButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
remoteAssistanceButton.setBounds(215, 251, 246, 23);
frame.getContentPane().add(remoteAssistanceButton);
JButton btnPingIndefinetely = new JButton("PING INDEFINETELY");
btnPingIndefinetely.setBounds(260, 217, 156, 23);
frame.getContentPane().add(btnPingIndefinetely);
JButton btnRdcByIp = new JButton("RDC by IP Address");
btnRdcByIp.setBounds(261, 353, 156, 23);
frame.getContentPane().add(btnRdcByIp);
JButton btnRdcByName = new JButton("RDC by PC Name");
btnRdcByName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnRdcByName.setBounds(248, 319, 180, 23);
frame.getContentPane().add(btnRdcByName);
JLabel lblLoggedInOpid = new JLabel("Logged in OPID:");
lblLoggedInOpid.setFont(new Font("Tahoma", Font.BOLD, 14));
lblLoggedInOpid.setBounds(228, 127, 135, 20);
frame.getContentPane().add(lblLoggedInOpid);
JLabel lblNewLabel_1 = new JLabel(System.getProperty("user.name")
.toUpperCase());
lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 14));
lblNewLabel_1.setForeground(Color.RED);
lblNewLabel_1.setBounds(348, 130, 86, 14);
frame.getContentPane().add(lblNewLabel_1);
JButton btnHiddenShare = new JButton("HIDDEN SHARE");
btnHiddenShare.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnHiddenShare.setBounds(484, 183, 132, 23);
frame.getContentPane().add(btnHiddenShare);
JLabel lblAdditionalTools = new JLabel("Tools");
lblAdditionalTools.setFont(new Font("Tahoma", Font.BOLD, 12));
lblAdditionalTools.setBounds(526, 157, 126, 20);
frame.getContentPane().add(lblAdditionalTools);
JButton btnNewButton_1 = new JButton("Remote Assistance by IP Address");
btnNewButton_1.setBounds(215, 285, 246, 23);
frame.getContentPane().add(btnNewButton_1);
JButton gpUpdate = new JButton("GP UPDATE");
gpUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
gpUpdate.setBounds(36, 217, 132, 23);
frame.getContentPane().add(gpUpdate);
JButton btnForced = new JButton("NURMED REG FIX");
btnForced.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnForced.setBounds(36, 251, 132, 23);
frame.getContentPane().add(btnForced);
JButton btnCleaConsoler = new JButton("CLEAR");
btnCleaConsoler.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textArea.setText("");
}
});
btnCleaConsoler.setBounds(563, 353, 79, 23);
frame.getContentPane().add(btnCleaConsoler);
JLabel lblOpid = new JLabel("Find Computer by OPID:");
lblOpid.setFont(new Font("Tahoma", Font.BOLD, 14));
lblOpid.setBounds(104, 53, 180, 14);
frame.getContentPane().add(lblOpid);
textField_1 = new JTextField();
textField_1.setBounds(285, 50, 124, 20);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
JButton btnNewButton_2 = new JButton("Search");
btnNewButton_2.setBounds(419, 50, 89, 23);
frame.getContentPane().add(btnNewButton_2);
testLabel.setForeground(Color.RED);
testLabel.setFont(new Font("Tahoma", Font.BOLD, 14));
testLabel.setBounds(358, 78, 150, 24);
frame.getContentPane().add(testLabel);
}
private void threadStart() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
testLabel.setText(CN);
}
});
}
}
My recommendations are again that you should:
Have your batch file output to the standard output, the console, if you will.
Trap that output by capturing the InputStream and the ErrorStream from your Process. These can be trapped together by redirecting the error stream.
You should do all of this in a background thread such as with a SwingWorker.
I'd make the SwingWorker specifically of type, SwingWorker<Integer, String> so that it can "publish" the Strings read in from its InputStream, and then it can eventually return the process's integer exit code to make sure that the process ran OK.
For instance, say I had a bat file in the user working directory called test.bat that simply printed out the directory of the path passed into it:
test.bat
dir %1
You could call this from a GUI and display the results using the techniques described above.
Note that my code below borrows heavily from MadProgrammer's wonderful answer that can be found here: Printing a Java InputStream from a Process. Please check his answer including his description and up-vote it if it helps you to better understand what's going on.
Also be sure to read Concurrency in Swing for all the details on how to do background threading and in particular SwingWorker use in Swing GUI's.
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import javax.swing.*;
#SuppressWarnings("serial")
public class TestBatGui extends JPanel {
public static final String BATCH_FILE_PATH = "test.bat";
private JTextArea resultArea = new JTextArea(30, 80);
public TestBatGui() {
resultArea.setFocusable(false); // not allow user edits
resultArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
JScrollPane scrollPane = new JScrollPane(resultArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
int keyCode = KeyEvent.VK_H;
String path = System.getProperty("user.home");
buttonPanel.add(new JButton(new ShowDirAction("Home Dir", keyCode, path)));
keyCode = KeyEvent.VK_W;
path = System.getProperty("user.dir");
buttonPanel.add(new JButton(new ShowDirAction("Working Dir", keyCode,
path)));
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.PAGE_END);
}
// Action/ActionListener to be used by my buttons
private class ShowDirAction extends AbstractAction {
private String path;
public ShowDirAction(String name, int keyCode, String path) {
super(name);
putValue(MNEMONIC_KEY, keyCode);
this.path = path;
}
#Override
public void actionPerformed(ActionEvent e) {
// our SwingWorker
BatchFileWorker batchFileWorker = new BatchFileWorker(
resultArea, BATCH_FILE_PATH, path);
// add a listener to respond when the worker is done
batchFileWorker.addPropertyChangeListener(new BatchFileWorkerListener());
batchFileWorker.execute(); // execute the worker
}
}
// class to listen for when the worker has completed its work
// and then this class extracts the SwingWorker's results via .get()
// and does house cleaning if need be.
private class BatchFileWorkerListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
BatchFileWorker worker = (BatchFileWorker) evt.getSource();
try {
// extract the result returned from the worker's doInBackground() method
// and most importantly, trap any exceptions thrown
int exitValue = worker.get();
String displayText = "";
if (exitValue != 0) {
displayText = String.format("Error when running batch, Exit Value: %d", exitValue);
} else {
displayText = "Batch file ran without error";
}
((Consumer<String>) worker).accept(displayText);
((Consumer<String>) worker).accept("\n");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
}
// Our SwingWorker. It's also a Consumer so that outside classes, namely the InputConsumer
// can pass the strings that it reads back into the worker via the accept(...) method
private class BatchFileWorker extends SwingWorker<Integer, String> implements Consumer<String> {
private JTextArea resultArea;
private String batchFilePath;
private String dirPath;
public BatchFileWorker(JTextArea resultArea, String batchFilePath,
String dirPath) {
this.resultArea = resultArea;
this.batchFilePath = batchFilePath;
this.dirPath = dirPath;
}
#Override
protected Integer doInBackground() throws Exception {
// command list to load into the process builder
List<String> commandList = new ArrayList<>();
int exitCode = 0;
publish("Getting dir for " + dirPath);
commandList.add("cmd");
commandList.add("/c");
commandList.add(batchFilePath);
commandList.add(dirPath);
// create the process builder
ProcessBuilder pBuilder = new ProcessBuilder(commandList);
// add the error stream to the input stream so now we have only one stream to handle
pBuilder.redirectErrorStream();
Process p = pBuilder.start(); // create our process
InputStream is = p.getInputStream(); // get its InputStream and use it
InputStreamReader isr = new InputStreamReader(is); // to create a
BufferedReader br = new BufferedReader(isr); // BufferedReader
InputConsumer consumer = new InputConsumer(br, this); // pass into our consumer object
Thread thread = new Thread(consumer); // start this in a background thread
thread.start();
exitCode = p.waitFor(); // wait in this thread for the error code
thread.join(); // join two threads
br.close(); // close the BufferedReader
return exitCode;
}
#Override // this allows our InputConsumer to pass Strings read back into the SwingWorker
public void accept(String text) {
publish(text);
}
#Override // published text will be sent here on the EDT, to be placed into the JTextArea
protected void process(List<String> chunks) {
for (String chunk : chunks) {
resultArea.append(chunk + "\n");
}
}
}
// to read in from the BufferedReader, passing text back into its consumer
private class InputConsumer implements Runnable {
private BufferedReader br;
private Consumer<String> consumer;
public InputConsumer(BufferedReader br, Consumer<String> consumer) {
this.br = br;
this.consumer = consumer;
}
#Override
public void run() {
String line = null;
try {
while ((line = br.readLine()) != null) {
consumer.accept(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void createAndShowGui() {
TestBatGui mainPanel = new TestBatGui();
JFrame frame = new JFrame("TestBatGui");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Auto clicker UI goes black when started

i have made a simple auto clicker, but when i run it the screen goes black so i cant stop it etc. i dont have a clue what i have done wrong. I thought maybe i had to set focus, but i am not sure.
Code:
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.UIManager;
import javax.swing.JRadioButton;
public class AutoClicker1 extends JFrame {
private JPanel contentPane;
private JTextField textField;
public static int rate;
public static boolean go = false;
public static int time;
public static int multiplyer;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AutoClicker1 frame = new AutoClicker1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public AutoClicker1() {
setTitle("Auto Clicker");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 361, 154);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNoOfClicks = new JLabel("Interval between clicks");
lblNoOfClicks.setBounds(10, 25, 149, 14);
contentPane.add(lblNoOfClicks);
textField = new JTextField();
textField.setBounds(10, 55, 139, 20);
contentPane.add(textField);
textField.setColumns(10);
JButton btnStopf = new JButton("Stop(F11)");
btnStopf.setBounds(203, 45, 89, 23);
contentPane.add(btnStopf);
JButton button = new JButton("Stop(F11)");
button.setBounds(203, 81, 89, 23);
contentPane.add(button);
final JRadioButton rdbtnSeconds = new JRadioButton("Seconds");
rdbtnSeconds.setBounds(6, 81, 65, 23);
contentPane.add(rdbtnSeconds);
final JRadioButton rdbtnMilliseconds = new JRadioButton("Milliseconds");
rdbtnMilliseconds.setBounds(71, 81, 109, 23);
contentPane.add(rdbtnMilliseconds);
btnStopf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
go = false;
}
});
JButton btnStart = new JButton("Start(F10)");
btnStart.setBounds(203, 11, 89, 23);
contentPane.add(btnStart);
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
go = true;
if (rdbtnMilliseconds.isSelected()) {
autoClick();
} else {
if (rdbtnSeconds.isSelected()) {
multiplyer = 1000;
autoClick();
}
}
}
});
}
private void autoClick() {
requestFocus();
rate = Integer.parseInt(textField.getText());
time = (rate * multiplyer);
System.out.print(time);
try {
Robot robot = new Robot();
while (true) {
try {
Thread.sleep(rate);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
} catch (InterruptedException ex) {}
}
} catch (AWTException e) {}
}
private void keyListner(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_F10) {
System.out.print("pressed F10");
go = true;
}
if (key == KeyEvent.VK_F11) {
go = false;
}
}
private void setTheme() {
try {
UIManager
.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void checkRate() {
if (rate < 500) {
rate = 0;
}
}
}
You are blocking the Event Dispatch Thread in autoClick() with the while(true), instead of that you can use a Swing Timer.
I suggest not using keyListener for listen only 2 keys, you can use keybindings for that purpose. Also you shouldn't call directly setBounds rely in a proper LayoutManager to position in screen.
You break out of the program loop in your Main method when you enter the wile loop in your AutoClick method.
You could instead run your program in a "game loop".
In the main method what I would do is create a method called run()
public void run()
{
int FPS = 60;
float startTime = System.currentTimeInMillis();
while(started)
{
float currentTime = System.currentTimeInMillis();
float passedTime = currentTime - startTime;
startTime = System.currentTimeInMillis();
if(passedTime > (float) 1000/FPS)
{
update();
}
}
}
and then in the update method put the logic of the program. I know it is a totally different approach to how you are currently doing it but in my opinion it allows for more flexibility.
For example in your action listener you could have it invoke a "startClick()" method
where it sets a boolean value to true and initializes what you intialzie currently in the autoclick method. Then your update() method would look like this:
public void update()
{
if(boolean) //boolean value that startClick sets to true
{
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
}
}
This way the program isn't stuck in an infinite while-loop and you can control how often it updateswith the FPS variable.

Categories