I want to change the label when I click the button, and then after 3 seconds exit the program. But if I click the button, label does not change. It just exits after 3 seconds. This is my logic
Change the label.
Sleep for 3 seconds
Then exit the program.
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Stopping the program.");
state.setText("Bye...");
state.setBackground(SystemColor.textHighlight);
doStop();
}
});
state = new JLabel("Not listening");
state.setForeground(new Color(255, 255, 255));
state.setBackground(new Color(204, 0, 51));
state.setHorizontalAlignment(SwingConstants.CENTER);
state.setBounds(10, 222, 488, 24);
state.setOpaque(true);
frame.getContentPane().add(state);
public void doStop() {
try{
Thread.sleep(3000);
} catch(InterruptedException e){
}
System.exit(0); }
Use javax.swing.Timer like:
final Timer time= new Timer(3000,new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
remove you doStop method, include this your code. Your button's actionListener would be like this
System.out.println("Stopping the program.");
state.setText("Bye...");
state.setBackground(SystemColor.textHighlight);
time.start();
Doc:
Fires one or more ActionEvents at specified intervals. An example use
is an animation object that uses a Timer as the trigger for drawing
its frames.
Learn MORE
Use javax.swing.TImer insted in your doStop(). Like this
public void doStop() {
Timer t=new Timer(3000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
t.start();
}
I guess the problem is the thread.sleep, try to use a timer instead.
There is an exemple :
public void doStop() {
long savedTime=System.currentTimeMillis(), actualTime=System.currentTimeMillis();
while((savedTime+3000 > actualTime) ){
actualTime=System.currentTimeMillis()
}
System.exit(0);}
Related
In my swings windows application after click the run button some operation is executed. If i am try to close window when operation is still in progress, close operation is not working. After complete the execution of process then only close window operation is working. Otherwise it will not responds the close operations.
I have already tried below mentioned codes. But that one is not stopped working
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
or
System.exit(1);
or
setDefaultCloseOperation(EXIT_ON_CLOSE);
or
setDefaultCloseOperation(3);
or
dispose();
}
});
JButton jb = new JButton("Run");
add(jb);
jb.setBounds(10, 30, 100, 30);
setSize(150,150);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
jb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
// some operations . For Example here i'm add 1E5 data,s in my collection object. again i will replace data's places of each element.
for(int i=0;i<1E5;i++)
{
ll.add(i);
}
for(int i=0;i<1E5;i++)
{
ll.add(1,i);
}
for(int i=0;i<1E5;i++)
{
ll.add(0,i);
}
System.out.println(ll);
}
});
If I am clicking close button, my window terminate the currently executed process and Close the window.
class MyThread extends Thread {
public void run() {
// some operations . For Example here i'm add 1E5 data,s in my collection object
..
..
}
}
Then in your actionPerformed method on your JButton actionlistener you just start the thread :
public void actionPerformed(ActionEvent e) {
new MyThread().start();
}
I have a JButton that will not allow me to perform the same action on any subsequent click on it after the first in the same Swing GUI instance.
JButton Run = new JButton("Run");
Run.setLocation(290, 70);
Run.setSize(120, 30);
buttonPanel.add(Run);
Run.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (Run.isEnabled()) {
errorLabel.setText("");
Result result = JUnitCore.runClasses(Run.class);
errorMessageDisplay(result);
}
}
});
totalGUI.setOpaque(true);
return totalGUI;
}
So far I thought about and tried removing the JPanel and painting all of the buttons back on, and disabling/renabling buttons.
The errorMessageDisplay method is as follows:
public void errorMessageDisplay(Result resultPass) {
if (resultPass.getFailureCount() > 0) {
errorLabel.setForeground(Color.red);
errorLabel.setVisible(true);
errorLabel.setText(" Failed");
}
else {
errorLabel.setForeground(Color.green);
errorLabel.setText(" Passed");
errorLabel.setVisible(true);
}
}
At first glance, the JUnitCore.runClasses(Run.class); call is suspicous. Also, it would be good to know what does the errorMessageDisplay() do. I believe, the problem is with one of these methods.
You can verify this with the following experimental code. Just be careful not to push it into production.
JButton run = new JButton("Run");
run.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (Run.isEnabled()) {
errorLabel.setText("");
System.out.println("Run action peformed.");
}
}
Update Since the errorMessageDisplay() looks okay, it's probably a Threading problem with JUniCore. Thus I'd try the following code:
final ExecutorService executor = Executors.newFixedThreadPool(5); // this runs stuff in background
JButton run = new JButton("Run");
// ..
run.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (Run.isEnabled()) {
executor.execute(new Runnable() { // This is how we run stuff in background. You can use lambdas instead of Runnables.
public void run() {
final Result result = JUnitCore.runClasses(Run.class); // Run.class is different from the current JButton run.
SwingUtilities.invokeLater(new Runnable() { // Now we go back to the GUI thread
public void run() {
errorMessageDisplay(result);
}
});
}
});
}
});
I've tried installing some keylisteners in my view class to terminate this method. But it seems like the method wont stop. I'm unsure how to actually stop it from executing? The button seems to be pressed the whole time the method is executed.
public void method1() {
try {
robot = new Robot();
Compare.captureScreen(800, 550, 200, 50);
if (Compare.processImage("image.png") == true) {
robot.mouseMove(890, 576);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
} else if (Compare.processImage("image.png") != true) {
if (Compare.file.exists()) {
Compare.file.delete();
}
robot.delay(2000);
method1();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I have tried something like this:
JButton btnNewButton = new JButton("method1");
btnNewButton.setFocusable(true);
btnNewButton.requestFocus();
btnNewButton.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ESCAPE){
System.exit(0);
}
}
});
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
theModel.method1();
}
});
btnNewButton.setBounds(163, 113, 101, 23);
mainPanel.add(btnNewButton);
You're calling long-running code on the Swing event dispatch thread (EDT), completely tying up the thread and making Swing unresponsive. The solution here is to have your long-running code run off the EDT and in a background thread.
I'm not sure how to change the timer in my program.
I want to control the timer as the program runs.
This is my code:
Timer timer = new Timer(Difficulty, new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if(p.GameOver==0)
{
if(p.s==1)
{
System.out.println("S");
p.moveSquare(p.SnakeHeadX,p.SnakeHeadY+p.SnakeHeadH);
p.eatBlueSquare(p.SnakeHeadX,p.SnakeHeadY);
p.Border(p.SnakeHeadX,p.SnakeHeadY);
p.Colision(p.SnakeHeadX,p.SnakeHeadY);
}
if(p.d==1)
{
System.out.println("D");
p.moveSquare(p.SnakeHeadX+p.SnakeHeadW,p.SnakeHeadY);
p.eatBlueSquare(p.SnakeHeadX,p.SnakeHeadY);
p.Border(p.SnakeHeadX,p.SnakeHeadY);
p.Colision(p.SnakeHeadX,p.SnakeHeadY);
}
if(p.a==1)
{
System.out.println("A");
p.moveSquare(p.SnakeHeadX - p.SnakeHeadW,p.SnakeHeadY);
p.eatBlueSquare(p.SnakeHeadX,p.SnakeHeadY);
p.Border(p.SnakeHeadX,p.SnakeHeadY);
p.Colision(p.SnakeHeadX,p.SnakeHeadY);
}
if(p.w==1)
{
System.out.println("W");
p.moveSquare(p.SnakeHeadX,p.SnakeHeadY-p.SnakeHeadH);
p.eatBlueSquare(p.SnakeHeadX,p.SnakeHeadY);
p.Border(p.SnakeHeadX,p.SnakeHeadY);
p.Colision(p.SnakeHeadX,p.SnakeHeadY);
}
}
}
});
timer.start();
If I change difficulty as the program runs there is no effect.
Just use timer.setDelay(Difficulty) every time you update the difficulty.
For more info about timer see this: http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html
you would have to cancel the current timer and then reinstantiate the timer with the correct value (where you would change the difficulty)
I have a JFormattedTextField component with an Integer value that is updated 3 times in a second when it doesn't have focus.
For updating the value I use Swing Timer.
I want to make it possible for user to edit its value(to update some value in the model) but I know that the value of a JFormattedTextField isn't updated every time it loses the focus. so it's not wise to change the model attributes in the lostFocus event and on the other hand when it loses the focus its value can be changed by the updater module which makes the situation more difficult.
It is clear that I can't use the propertyListener neither, because the value is updated 3 times in a second!
Now I wonder how I will be able to update the variable on place profiting JFormattedTextField capabilities and let updater update my JFormattedTextField when it doesn't have focus! Is it possible or I must use an inputDialog instead? How?
For example in the following code when I change the field value to 200 in the GUI and then click on the JFrame to make it lose focus the value printed in the console isn't 200. It's a great random value that was previously in the field.
public class SwingTimerFormattedTextFieldTester {
public static void main(String... args){
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(0, 0, 300, 200);
final JFormattedTextField field = new JFormattedTextField(new Long(100));
field.setColumns(20);
frame.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
frame.requestFocus();
e.consume();
}
});
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(field);
frame.setVisible(true);
Timer timer = new Timer(330, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(!field.hasFocus()){
field.setValue(ThreadLocalRandom.current().nextLong());
}
}
});
timer.start();
field.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
field.setBackground(Color.CYAN);
}
#Override
public void focusLost(FocusEvent e) {
field.setBackground(Color.WHITE);
System.out.println(String.valueOf((Long)field.getValue()));
}
});
frame.requestFocus();
}
}
What if you commit the edit to the JFormattedTextField on focus lost?
#Override
public void focusLost(FocusEvent e) {
try {
if (field.isEditValid()) {
field.commitEdit();
}
} catch (ParseException e1) {
e1.printStackTrace();
}
field.setBackground(Color.WHITE);
System.out.println(String.valueOf((Long) field.getValue()));
}