Using swing how do I dim an unfocused text field? - java

A user is allowed to choose only one option from a few. Each option is represented by a text field (user is required to put some text there) so I though it should be nice to dim a field which is unfocused to let user understand he may choose one option.
Can anyone please advise me with an example / link to one for something similar?

So, the basic idea would be to simple use setEnabled to change the enabled state of the field which you don't want modified. The difficult part is knowing when to to disable/enable the fields
Fortunately, the JTextField's Document can generate events when it's updated. See Listening for Changes on a Document for more details
So, with this in hand, we can do something like this...
public class ManagedDocumentHandler implements DocumentListener {
private JTextField toBe;
private JTextField orNotToBe;
public ManagedDocumentHandler(JTextField toBe, JTextField orNotToBe) {
this.toBe = toBe;
this.orNotToBe = orNotToBe;
}
#Override
public void insertUpdate(DocumentEvent e) {
updateState();
}
#Override
public void removeUpdate(DocumentEvent e) {
updateState();
}
#Override
public void changedUpdate(DocumentEvent e) {
updateState();
}
protected void updateState() {
toBe.setEnabled(true);
orNotToBe.setEnabled(toBe.getText().trim().length() == 0);
}
}
Knowing that we have two fields, one will be enabled when the contents is changed, the other will (likely) be disabled when the other is changed (except if the field is empty, then they are both enabled)
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class MakeItSo {
public static void main(String[] args) {
new MakeItSo();
}
public MakeItSo() {
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() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
gbc.insets = new Insets(4, 4, 4, 4);
add(new JLabel("Choose this:"), gbc);
gbc.gridx++;
add(new JLabel("Or this:"), gbc);
JTextField thisOne = new JTextField(10);
JTextField orThisOne = new JTextField(10);
thisOne.getDocument().addDocumentListener(new ManagedDocumentHandler(thisOne, orThisOne));
orThisOne.getDocument().addDocumentListener(new ManagedDocumentHandler(orThisOne, thisOne));
gbc.gridx = 0;
gbc.gridy++;
add(thisOne, gbc);
gbc.gridx++;
add(orThisOne, gbc);
}
public class ManagedDocumentHandler implements DocumentListener {
private JTextField toBe;
private JTextField orNotToBe;
public ManagedDocumentHandler(JTextField toBe, JTextField orNotToBe) {
this.toBe = toBe;
this.orNotToBe = orNotToBe;
}
#Override
public void insertUpdate(DocumentEvent e) {
updateState();
}
#Override
public void removeUpdate(DocumentEvent e) {
updateState();
}
#Override
public void changedUpdate(DocumentEvent e) {
updateState();
}
protected void updateState() {
toBe.setEnabled(true);
orNotToBe.setEnabled(toBe.getText().trim().length() == 0);
}
}
}
}

Related

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();
}
});

Drag and Drop from JButton to JComponent in Java

I searched on the internet for examples how to Drag and Drop JButtons to an Object but I could not make it work.
What my program does, is that when I click on a button, the object updated a field (with a selectedobject.setField()). I want to be able to do this not by clicking, but by dragging the JButton.
How can I do this ?
I found this, and I tried to put in my code:
btn.setTransferHandler(new ImageHandler());
btn.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
JComponent c = (JComponent)e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
}
});
I took the ImageHandler class from here.
Drag'n'drop is a fun bag of crunchy, munchy carrots...not helped by the fact that there is a "core" API and the newer "transfer" API, so it's really easy to get confused
The following example uses the "transfer" API and basically transfers a String value from a button to a JLabel.
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
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() {
setLayout(new GridLayout(1, 2));
add(createLeftPanel());
add(createRightPanel());
}
protected JPanel createLeftPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
for (int index = 0; index < 10; index++) {
JButton btn = new JButton(Integer.toString(index + 1));
panel.add(btn, gbc);
btn.setTransferHandler(new ValueExportTransferHandler(Integer.toString(index + 1)));
btn.addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
JButton button = (JButton) e.getSource();
TransferHandler handle = button.getTransferHandler();
handle.exportAsDrag(button, e, TransferHandler.COPY);
}
});
}
return panel;
}
protected JPanel createRightPanel() {
JPanel panel = new JPanel(new GridBagLayout());
JLabel label = new JLabel("Drop in");
label.setBorder(new CompoundBorder(new LineBorder(Color.DARK_GRAY), new EmptyBorder(20, 20, 20, 20)));
label.setTransferHandler(new ValueImportTransferHandler());
panel.add(label);
return panel;
}
}
public static class ValueExportTransferHandler extends TransferHandler {
public static final DataFlavor SUPPORTED_DATE_FLAVOR = DataFlavor.stringFlavor;
private String value;
public ValueExportTransferHandler(String value) {
this.value = value;
}
public String getValue() {
return value;
}
#Override
public int getSourceActions(JComponent c) {
return DnDConstants.ACTION_COPY_OR_MOVE;
}
#Override
protected Transferable createTransferable(JComponent c) {
Transferable t = new StringSelection(getValue());
return t;
}
#Override
protected void exportDone(JComponent source, Transferable data, int action) {
super.exportDone(source, data, action);
// Decide what to do after the drop has been accepted
}
}
public static class ValueImportTransferHandler extends TransferHandler {
public static final DataFlavor SUPPORTED_DATE_FLAVOR = DataFlavor.stringFlavor;
public ValueImportTransferHandler() {
}
#Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(SUPPORTED_DATE_FLAVOR);
}
#Override
public boolean importData(TransferHandler.TransferSupport support) {
boolean accept = false;
if (canImport(support)) {
try {
Transferable t = support.getTransferable();
Object value = t.getTransferData(SUPPORTED_DATE_FLAVOR);
if (value instanceof String) {
Component component = support.getComponent();
if (component instanceof JLabel) {
((JLabel) component).setText(value.toString());
accept = true;
}
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
return accept;
}
}
}
I've gone out my way to separate the TransferHandlers allowing for a "drag" and "drop" version. You don't "have" to do this and you "could" use a single TransferHandler to perform both operations, that's up to you.
You will have to modify the ValueExportTransferHandler to accept different values and modify the SUPPORTED_DATE_FLAVOR accordingingly, but those are the basics
You could also have a look at Drag and Drop custom object from JList into JLabel as another example...

Is it possible to use a JSlider controlling multiple JTextfield?

I tried to use a JSlider to set text in three JTextFields.
My condition is the slider should work for textfield_1, only when a textfield_1 get its focus, similarly for the other two textfields.
When I tried to use the same slider with other textfield, only the first text field values getting changed.
Expecting valuable suggestions Thanks in Advance.
JSlider slider;
JTextField tf;
tf.addFocusListener(new FoucusListener(){
public void foucusGained(FocusEvent fe){
slider.addChangeListener(new ChangeListener()){
public void stateChanged(ChangeEvent ce){
JSlider slider =(JSlider)ce.getSource();
if(slider.getValueisAdjusting())
tf.setText(String.valueOf(slider.getValue()))
}
});
});
The basic idea is you need to know what field was last selected. The problem is, when you select the slider, it will fire a focus gained event...
The simplest idea would be to use a FocusListener registered only to the text fields and maintain a reference to the last field selected.
When the slider changes, you would simply interact with the last selected field (if it's not null)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SliderControl {
public static void main(String[] args) {
new SliderControl();
}
public SliderControl() {
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 JSlider slider;
private JTextField[] fields;
private JTextField selectedField;
public TestPane() {
setLayout(new GridBagLayout());
fields = new JTextField[3];
FocusHandler focusHandler = new FocusHandler();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
for (int index = 0; index < 3; index++) {
fields[index] = new JTextField(3);
fields[index].addFocusListener(focusHandler);
add(fields[index], gbc);
gbc.gridy++;
}
gbc.fill = GridBagConstraints.HORIZONTAL;
slider = new JSlider();
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if (selectedField != null) {
selectedField.setText(String.valueOf(slider.getValue()));
}
}
});
add(slider, gbc);
}
protected class FocusHandler extends FocusAdapter {
#Override
public void focusGained(FocusEvent e) {
if (e.getComponent() instanceof JTextField) {
selectedField = (JTextField) e.getComponent();
}
}
}
}
}

How to change size of JTextArea

I have three radio buttons that I want to use to change the size of a JTextArea when I click the buttons.
if(rd_7inch.isSelected())
{
jScrollPane2.setSize(200,200);
txt_sysnp.setSize(5,20);
}if(rd_9inch.isSelected())
{
jScrollPane2.setSize(200,200);
txt_sysnp.setSize(5,25);
}if(rd_10inch.isSelected())
{
jScrollPane2.setSize(200,200);
txt_sysnp.setSize(5,30);
}
The important point is that whenever you update the UI you have to call revalidate() on that panel or container so that your changes get apply.
You can also do this by setSize() method.
public void showDialog(){
btnUp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dimSPane.setSize(new Dimension(400,50));
pane.revalidate();
}
});
btnUp.setSize(new Dimension(100,24));
btnDn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dimSPane.setSize(new Dimension(200,25));
pane.revalidate();
}
});
btnDn.setSize(new Dimension(100,24));
dimSPane.setSize(new Dimension(200,25));
Dimension dimtfield = new Dimension();
dimtfield.setSize(new Dimension(200,25));
spane.setMinimumSize(dimSPane);
spane.setMaximumSize(dimSPane);
spane.setPreferredSize(dimSPane);
tfield.setMinimumSize(dimtfield);
tfield.setMaximumSize(dimtfield);
tfield.setPreferredSize(dimtfield);
pane.add(spane);
pane.add(tfield);
pane.add(btnUp);
pane.add(btnDn);
JDialog dlg =new JDialog();dlg.add(pane);
dlg.pack();
dlg.show();
}
It is likely that you components are under the control of a layout manager.
The only means by which you can suggest changes to the size would be to use setColumns and setRows and use a layout manager that respects the preferred size of its components
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TextAreaSize {
public static void main(String[] args) {
new TextAreaSize();
}
public TextAreaSize() {
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 JTextArea ta;
public TestPane() {
setLayout(new GridBagLayout());
JRadioButton btnSmall = new JRadioButton(new SizeAction("Small", 2, 10));
JRadioButton btnMed = new JRadioButton(new SizeAction("Medium", 4, 15));
JRadioButton btnLarge = new JRadioButton(new SizeAction("Large", 12, 24));
ButtonGroup bg = new ButtonGroup();
bg.add(btnSmall);
bg.add(btnMed);
bg.add(btnLarge);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.NORTHWEST;
add(btnSmall, gbc);
gbc.gridy++;
add(btnMed, gbc);
gbc.gridy++;
add(btnLarge, gbc);
gbc.gridx++;
gbc.gridy = 0;
gbc.gridheight = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.CENTER;
ta = new JTextArea();
add(new JScrollPane(ta), gbc);
btnSmall.doClick();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public class SizeAction extends AbstractAction {
private int rows;
private int columns;
public SizeAction(String name, int rows, int columns) {
putValue(NAME, name);
this.rows = rows;
this.columns = columns;
}
#Override
public void actionPerformed(ActionEvent e) {
ta.setRows(rows);
ta.setColumns(columns);
revalidate();
}
}
}
}

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