Change JButton Color in a Thread - java

I am trying to make a game like simon: http://www.freegames.ws/games/kidsgames/simon/simon.htm#
I am making a smaller scale with only 2 buttons. I want the color to switch between 2 buttons, button1 and button2. This is in a thread because I need buttons to be clicked while this is happening. When I open the program the button color stays as-is.
Thanks for help in advance!
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.*;
public class TestFrame extends JFrame{
public JButton button1;
public JButton button2;
boolean isTrue = true;
boolean switchColor = true;
TestFrame(){
super("Simon");
initialize();
this.setSize(200, 400);
this.setVisible(true);
}
private void initialize() {
this.setLayout(new BorderLayout());
button1 = new JButton();
button1.setBackground(Color.green);
button1.setSize(200,200);
button2 = new JButton();
button2.setSize(200, 200);
button2.setBackground(Color.blue);
this.add(button1, BorderLayout.NORTH);
this.add(button2, BorderLayout.SOUTH);
Thread t = new Thread(r1);
t.start();
}
Runnable r1 = new Runnable() {
public void run() {
while(isTrue){
if(switchColor = true){
button1.setBackground(Color.blue);
button2.setBackground(Color.green);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
refresh();
switchColor = false;
} else {
button1.setBackground(Color.green);
button2.setBackground(Color.blue);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
refresh();
switchColor = true;
}
}
}
};
public void refresh(){
this.invalidate();
this.validate();
this.repaint();
}
}

A number of issues stand out (shazin has addressed one), the other that scares me is you are violating the single thread requirements of Swing. All changes to the UI must be made from within the context of the Event Dispatching Thread.
Instead of using a Thread, you should be using a javax.swing.Timer. This will save you the need to have to resync your updates back to the EDT.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class FlashyButtons {
public static void main(String[] args) {
new FlashyButtons();
}
public FlashyButtons() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JButton btn1;
private JButton btn2;
private int count = 0;
public TestPane() {
setLayout(new GridBagLayout());
btn1 = new FlashButton();
btn2 = new FlashButton();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(btn1, gbc);
add(btn2, gbc);
btn1.setBackground(Color.GREEN);
btn2.setBackground(Color.BLUE);
Timer timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
count++;
if (count % 2 == 0) {
btn1.setBackground(Color.BLUE);
btn2.setBackground(Color.GREEN);
} else {
btn1.setBackground(Color.GREEN);
btn2.setBackground(Color.BLUE);
}
}
});
timer.start();
}
}
public class FlashButton extends JButton {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Take a look at Concurrency in Swing for more details

if(switchColor = true){
button1.setBackground(Color.blue);
button2.setBackground(Color.green);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
refresh();
switchColor = false;
} else {
button1.setBackground(Color.green);
button2.setBackground(Color.blue);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
refresh();
switchColor = true;
}
}
In the above code change the following to
if(switchColor = true){
to
if(switchColor == true){
or just
if(switchColor){
And it is best to have your Runnable anonymous class inside
SwingUtilities.invokeLater(new Runnable() {
public void run() {
}
});
than using a new Thread object to create and start the thread as it will be changing the Swing UI properties.

Related

No OpenGL context found in the current thread while using action listener JFrame

I have integrated Display inside JFrame using Canvas and Display.setParent(canvas) method. now i would like to update loader(data) in side Display using JButton aciton listener, Doing this i have faced following error
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: No OpenGL context found in the current thread.
at org.lwjgl.opengl.GLContext.getCapabilities(GLContext.java:124)
at org.lwjgl.opengl.GL30.glDeleteVertexArrays(GL30.java:1530)
at renderEngine.Loader.cleanUp(Loader.java:38)
at engineTester.MainGameLoop$2.actionPerformed(MainGameLoop.java:79)
I have found useful resource which am exactly facing right now here How to get OpenGL context into my current thread, opengl context not found I know i have to use Queue and Runnables but i never used them and dont know where to start. Can some one help me with some code or steps in doing ? or a resource where i can start and get it work.This is important for me. Thanks
Edit 1: adding program(Error thrown where i line commented inside button ActionListener)
package com.java8;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
public class LWJGLTester {
private volatile boolean isRunning = false;
private int frameWidth = 800;
private int frameHeight = 600;
private int displayWidth = 720;
private int displayHeight = 450;
private Thread glThread;
public static void main(String[] args) {
new LWJGLTester().runTester();
}
private void runTester() {
final JFrame frame = new JFrame("LWJGL in Swing");
frame.setSize(frameWidth, frameHeight);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent we) {
frame.setVisible(false);
frame.dispose(); //canvas's removeNotify() will be called
}
});
JPanel mainPanel = new JPanel(new BorderLayout());
JButton button = new JButton("BUTTON");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("From button");
loader.cleanUp(); // am trying to change the model data here which gives me the error
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(button);
mainPanel.add(buttonPanel, BorderLayout.NORTH);
Canvas canvas = new Canvas() {
#Override
public void addNotify() {
super.addNotify();
startGL();
}
#Override
public void removeNotify() {
stopGL();
super.removeNotify();
}
};
canvas.setPreferredSize(new Dimension(displayWidth, displayHeight));
canvas.setIgnoreRepaint(true);
try {
Display.setParent(canvas);
Display.setVSyncEnabled(true);
} catch (LWJGLException e) {
//handle exception
e.printStackTrace();
}
JPanel canvasPanel = new JPanel();
canvasPanel.add(canvas);
mainPanel.add(canvasPanel, BorderLayout.SOUTH);
frame.getContentPane().add(mainPanel);
//frame.pack();
frame.setVisible(true);
}
private void startGL() {
glThread = new Thread(new Runnable() {
#Override
public void run() {
isRunning = true;
try {
Display.setDisplayMode(new DisplayMode(displayWidth, displayHeight));
Display.create();
} catch (LWJGLException e) {
//handle exception
e.printStackTrace();
}
// init OpenGL here
while(isRunning) {
Display.sync(60);
Display.update();
}
Display.destroy();
}
}, "LWJGL Thread");
glThread.start();
}
private void stopGL() {
isRunning = false;
try {
glThread.join();
} catch (InterruptedException e) {
//handle exception
e.printStackTrace();
}
}
}

JTextField - Call event after not editing in n seconds [duplicate]

how to start a function after stop typing in a JTextField. Not for every key release. If two key release time difference is greater than 1 second then it will run this function. Otherwise wait for 1 second.
Use a Swing Timer and a DocumentListener, each time the Document is updated, reset the Timer
Have a look at How to use Swing Timers and Listening for Changes on a Document for more details
As a, simple, example...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
JTextField field = new JTextField(20);
JLabel label = new JLabel("Waiting");
DeferredDocumentListener listener = new DeferredDocumentListener(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Execute your required functionality here...
label.setText(label.getText() + ".");
}
}, true);
field.getDocument().addDocumentListener(listener);
field.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
listener.start();
}
#Override
public void focusLost(FocusEvent e) {
listener.stop();
}
});
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(field, gbc);
add(label, gbc);
}
}
public class DeferredDocumentListener implements DocumentListener {
private final Timer timer;
public DeferredDocumentListener(int timeOut, ActionListener listener, boolean repeats) {
timer = new Timer(timeOut, listener);
timer.setRepeats(repeats);
}
public void start() {
timer.start();
}
public void stop() {
timer.stop();
}
#Override
public void insertUpdate(DocumentEvent e) {
timer.restart();
}
#Override
public void removeUpdate(DocumentEvent e) {
timer.restart();
}
#Override
public void changedUpdate(DocumentEvent e) {
timer.restart();
}
}
}
If you don't mind using two libraries, this is very easy to solve with RxSwing and RxJava:
EventQueue.invokeLater(() -> {
try {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
JTextField textField = new JTextField(30);
frame.getContentPane().add(textField, BorderLayout.NORTH);
// HERE
SwingObservable.fromDocumentEvents(textField.getDocument())
.debounce(1, TimeUnit.SECONDS)
.map(documentEvent -> textField.getText())
.subscribe(System.out::println);
frame.setVisible(true);
frame.pack();
} catch (final Exception e) {
e.printStackTrace();
}
});

Why can't I retrieve my buttons when I run my program?

So, my program is a user adding buttons during runtime. When he/she clicks on the 'save' button the program is saved to a file. But when I run it again, the buttons are gone. I tried to serialize my buttons using XMLEncoder and XMLDecoder, but when I ran my program, it didn't save anything, it started all over again. How would I serialize this correctly so that when I start my program, the buttons are there? Any help would be appreciated.
Here is a snippet of my code:
public class saveButton
{
//JFrame and JPanels have been declared earlier
class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
str = JOptionPane.showInputDialog("What is the name of the new button?");
JButton b = new JButton(str);
frame.add(b);
try
{
XMLEncoder encdr = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("file.ser")));
encdr.writeObject(new JButton(str));
encdr.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
ActionListener addButtonClicked = new ClickListener();
b.addActionListener(addButtonClicked);
class ClickListenerTwo implements ActionListener
{
public void actionPerformed(ActionEvent f)
{
try
{
XMLDecoder d = new XMLDecoder(new BufferedInputStream(new FileInputStream("file.ser")));
Object result = d.readObject();
d.close();
}
catch (IOException decoder)
{
decoder.printStackTrace();
}
}
}
Once you decode the object, you need to cast the object appropriately and then add the component to the container.
This is pretty basic example which generates a random number of buttons on a panel each time you click the Random button. When you click Save, the panel is saved to disk and when you click Load, it loads the panel from disk and reapplies it the container
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private RandomButtonPane pane;
public TestPane() {
setLayout(new BorderLayout());
JPanel actions = new JPanel();
JButton random = new JButton("Random");
JButton save = new JButton("Save");
JButton load = new JButton("Load");
actions.add(random);
actions.add(save);
actions.add(load);
add(actions, BorderLayout.SOUTH);
random.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (pane != null) {
remove(pane);
}
pane = new RandomButtonPane();
pane.randomise();
add(pane);
Window window = SwingUtilities.windowForComponent(TestPane.this);
window.pack();
window.setLocationRelativeTo(null);
}
});
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (pane != null) {
try (OutputStream os = new FileOutputStream(new File("Save.dat"))) {
try (XMLEncoder encoder = new XMLEncoder(os)) {
encoder.writeObject(pane);
remove(pane);
pane = null;
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
});
load.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (pane != null) {
remove(pane);
pane = null;
}
try (InputStream is = new FileInputStream(new File("Save.dat"))) {
try (XMLDecoder decoder = new XMLDecoder(is)) {
Object value = decoder.readObject();
if (value instanceof RandomButtonPane) {
pane = (RandomButtonPane)value;
pane.revalidate();
add(pane);
}
}
} catch (IOException exp) {
exp.printStackTrace();
}
Window window = SwingUtilities.windowForComponent(TestPane.this);
window.pack();
window.setLocationRelativeTo(null);
}
});
}
}
public static class RandomButtonPane extends JPanel {
public RandomButtonPane() {
setLayout(new GridBagLayout());
}
public void randomise() {
int count = ((int) (Math.random() * 100)) + 1;
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
for (int index = 0; index < count; index++) {
if (index % 10 == 0) {
gbc.gridx = 0;
gbc.gridy++;
}
add(new JButton(Integer.toString(index)), gbc);
gbc.gridx++;
}
}
}
}

How can i send an event while the program is in a loop?

I work at a project and i need to understand very well how event-driven programming works. I've read a lot in the last few days and i understood how this is working but i cant figure some things out.
In a class called Application i got this:
public void Simulate() throws InterruptedException {
int i = 0;
while (1 == 1) {
System.out.println(i);
Thread.sleep(1000);
i++;
}
}
And i have this class:
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Visual {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Visual window = new Visual();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Visual() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 472, 381);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
JButton btnStart = new JButton("Start");
btnStart.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
Application app = new Application();
try {
app.Simulate();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
**JButton print = new JButton("Print");
print.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("random text");
}
});**
panel.add(print);
panel.add(btnStart);
}
}
What i want to do is when i run this program, i want to pres the putton Start to start the loop in the simulate method and then i want to press the button print, to print some random text while the counter is still running. The problem is that after i pres the start button, the print button becomes unavailable, and cant be pressed anymore. How can i solve this?
For buttons don't use addMouseListener, use addActionListener and override actionPerformed method, to be able to print your number while the loop is running, try to call your simulate method using new thread. Change your Visual class to the followng example:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Visual {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Visual window = new Visual();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Visual() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 472, 381);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Application app = new Application();
(new Thread(new Runnable() {
public void run() {
try {
app.Simulate();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
})).start();
}
});
JButton print = new JButton("Print");
print.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("random text");
}
});
panel.add(print);
panel.add(btnStart);
}
}

Java Swing processing status

I am trying to implement a swing frame. In this, I want to display a processing status in a textPanel using a different thread while performing the needed task. I tried the following code. Of course there is something wrong with the logic. Please provide me with the proper approach
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class SampleSwing {
private JFrame frame;
public static JTextField textField;
public static boolean processing=false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SampleSwing window = new SampleSwing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public SampleSwing() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(0, 31, 434, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
processing=true;
Processingstatus ps=new Processingstatus();
ps.start();
/*perform the actual task*/
processing=false;
}
});
btnNewButton.setBounds(174, 74, 89, 23);
frame.getContentPane().add(btnNewButton);
}
}
class Processingstatus extends Thread{
public void run() {
try {
while(SampleSwing.processing) {
SampleSwing.textField.setText("Processing");
Thread.sleep(1000);
SampleSwing.textField.setText("Processing..");
Thread.sleep(1000);
SampleSwing.textField.setText("Processing...");
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
First I thought, "you should be using a SwingWorker, as it has methods to handle progress and EDT updates..."
But when I looked closer, you don't actually really care about the process itself, you just want some where to show that a process is running...They are two separate entities, that are only related because one (the UI updates) will run so long as the other is running.
So, instead, I used a javax.swing.Timer. This allows me to schedule an event to occur every n milliseconds and have that triggered in the EDT, nice and clean...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.Timer;
public class SampleSwing {
private JFrame frame;
public static JTextField textField;
public static boolean processing = false;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SampleSwing window = new SampleSwing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public SampleSwing() {
initialize();
}
private Timer processTimer;
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
textField = new JTextField(25);
frame.add(textField, gbc);
processTimer = new Timer(500, new ActionListener() {
private StringBuilder dots = new StringBuilder(3);
#Override
public void actionPerformed(ActionEvent e) {
dots.append(".");
if (dots.length() > 3) {
dots.delete(0, dots.length());
}
textField.setText("Processing" + dots.toString());
}
});
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!processing) {
processing = true;
processTimer.start();
} else {
processTimer.stop();
processing = false;
textField.setText(null);
}
}
});
frame.add(btnNewButton, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
}
}
ps For the reason why your original code didn't work, see my comment in the above comments section ;)

Categories

Resources