How to update the time without closing the UI in java? - java

I want to create a system that has a time in/time out feature.
I tried this code as a trial before including the the feature to my system:
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Time extends JFrame implements ActionListener {
Date now = new Date();
private JLabel time;
private JButton getTime;
private SimpleDateFormat dateFormatter = new SimpleDateFormat("hh:mm:ss");
public Time()
{
setLayout(null);
setSize(500,300);
JLabel time = new JLabel("00:00:00");
time.setSize(100,100);
time.setLocation(40,40);
JButton getTime = new JButton("GET TIME");
getTime.addActionListener(this);
getTime.setSize(90,30);
getTime.setLocation(90,70);
Container pane = getContentPane();
pane.add(time);
pane.add(getTime);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand() == "GET TIME")
{
JOptionPane.showMessageDialog(null, "Time "+dateFormatter.format(now),
"Time.",JOptionPane.INFORMATION_MESSAGE);
}
}
public static void main(String[] args) {
new Time();
}
}
It gets the current time, but it still gives the same time when I click again the button. It only changes when I close the UI.

Canned answer:
Don't compare Strings using ==. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of
if (fu == "bar") {
// do something
}
do,
if ("bar".equals(fu)) {
// do something
}
or,
if ("bar".equalsIgnoreCase(fu)) {
// do something
}
Uncanned answer:
So in other words, change this:
if (e.getActionCommand() == "GET TIME")
to this:
if ("GET TIME".equals(e.getActionCommand())
or better still, use String constants.
Also, you'll want to avoid using null layout in your Swing GUI's as you'll find out that that is the hard way to lay things out. Much easier and more robust is to use layout managers.
Edit
You need to get the time from within your actionPerformed method. In other words, now should be created in the actionPerformed method before calling the JOptionPane.
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand() == "GET TIME")
{
now = new Date();
JOptionPane.showMessageDialog(null, "Time "+dateFormatter.format(now),

You're getting the same time because you've declared the Date variable as a global variable and initialized it globally as well. You should change the implementation of your actionPerformed as follows:
public void actionPerformed(ActionEvent e) {
Date now = new Date(); //Create a new instance of date
if ("GET TIME".equalsIgnoreCase(e.getActionCommand())) {
JOptionPane.showMessageDialog(null,
"Time " + dateFormatter.format(now), "Time.",
JOptionPane.INFORMATION_MESSAGE);
}
}

Related

How would I program an array of Strings to work as a set of passwords?

So I'm trying to get a java applet to accept a set of multiple passwords, so naturally I thought to put them in array. However, only one of the passwords in the array is working, the last one in the set. None of the ones before it will work and my applet denies the others. This is my code so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JPasswordC extends JApplet implements ActionListener
{
private final String[] password = {"Rosebud", "Redrum", "Jason", "Surrender", "Dorothy"};
private Container con = getContentPane();
private JLabel passwordLabel = new JLabel("Password: ");
private JTextField passwordField = new JTextField(16);
private JLabel grantedPrompt = new JLabel("<html><font color=\"green\">Access Granted</font></html>");
private JLabel deniedPrompt = new JLabel("<html><font color=\"red\">Access Denied</font></html>");
public void init()
{
con.setLayout(new FlowLayout());
con.add(passwordLabel);
con.add(passwordField);
con.add(grantedPrompt);
grantedPrompt.setVisible(false);
con.add(deniedPrompt);
deniedPrompt.setVisible(false);
passwordField.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String input = passwordField.getText();
for(String p : password)
{
if(input.equalsIgnoreCase(p))
{
grantedPrompt.setVisible(true);
deniedPrompt.setVisible(false);
}
else
{
grantedPrompt.setVisible(false);
deniedPrompt.setVisible(true);
}
}
}
}
How would I get this to work properly? Am I doing something wrong with the array? Is it something in the code altogether?
The code is checking each password even if a valid one is found meaning that even if a valid password is found it will still change based on the validity of the next password. So the last one in the array declares the status of grantedPrompt and deniedPrompt. Try adding a break after the input is equal to one of the passwords.
for(String p : password)
{
if(input.equalsIgnoreCase(p))
{
grantedPrompt.setVisible(true);
deniedPrompt.setVisible(false);
break; // break out or loop once found
}
else
{
grantedPrompt.setVisible(false);
deniedPrompt.setVisible(true);
}
}
You are looping through all the passwords,even though there is a match.So change the code to return the method when ever there is a match in the password.
public void actionPerformed(ActionEvent ae)
{
String input = passwordField.getText();
for(String p : password)
{
if(input.equalsIgnoreCase(p))
{
grantedPrompt.setVisible(true);
deniedPrompt.setVisible(false);
return;
}
}
grantedPrompt.setVisible(false);
deniedPrompt.setVisible(true);
}

Creating Custom Components - Extending to JFormattedField

I am currently working on an application and I have a certain requirement for my interface: A time input.
I need my controls to accept 12hrs to 24hrs input using JFormattedTextField and found this:
MaskFormatter mask = new MaskFormatter("##:##");
mask.setPlaceHolderCharacter('0');
Now I created a class that extends to a JFormattedTextField
public class JayTimeInput extends JFormattedTextField{....
now I peeked inside JFormattedTextField's source and found something like this:
public JFormattedTextField(Object mask){...
my question is: How do I create my JayTimeInput class that automatically has a mask formatter? I tried declaring it in my constructor but I am not sure about this:
public JayTimeInput(){
try{
MaskFormatter mask = new MaskFormatter("##:##");
mask.setPlaceHolderCharacter('0');
new JFormattedTextField(mask);
}catch(Exception e){e.printStackTrace()}
}
Ive seen examples on how to use MaskFormatter and the only way I found was by declaring it like this:
MaskFormatter mask = new MaskFormatter("##:##");
mask.setPlaceHolderCharacter('0');
JFormattedTextField jformat = new JFormattedTextField(mask);
Im not sure if my actionlistener was correctly done but I need this to work first.
anyone help me out? im still new in creating my own controls by extending existing swings.
UPDATE:
I was looking at the wrong way of customizing my JFormattedTextField. I Should've used FormatFactory. Answer code has been posted for anyone who needs it.
//if you found this usefull, please dont remove this
//and credit my work for this
//James C. Castillo
//zeinzu21#gmail.com
import java.awt.event.KeyEvent;
import javax.swing.JFormattedTextField;
import javax.swing.text.MaskFormatter;
public final class JayTimeInput extends JFormattedTextField{
public JayTimeInput(){
myFormat();
addKeyListener(new java.awt.event.KeyAdapter() {
#Override
public void keyTyped(java.awt.event.KeyEvent evt) {
verify(evt);
}
});
}
public void myFormat() {
try {
MaskFormatter format = new MaskFormatter("##:##");
format.setPlaceholderCharacter('0');
this.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(format));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
}
public String getTime(){
return this.getText();
}
public void setTime(String x){
this.setText(x);
}
public void resetTime(){
this.setText("00:00");
}
public void setFocus(boolean f){
this.setFocusable(f);
this.setVerifyInputWhenFocusTarget(f);
}
public void verify(KeyEvent evt){
try {
int carret = this.getCaretPosition();
char c = evt.getKeyChar();
if(carret==0){
int hour = Integer.parseInt(c+"");
if(hour>1){
evt.consume();
}
}
if(carret==1){
int hour = Integer.parseInt(c+"");
if(hour>2){
evt.consume();
}
}
if(carret==3){
int min = Integer.parseInt(c+"");
if(min>5){
evt.consume();
}
}
} catch (Exception e) {
//do nothing. nothing to catch since its keyevent
}
}
}

java changes in jtextfield [duplicate]

I want the message box to appear immediately after the user changes the value in the textfield. Currently, I need to hit the enter key to get the message box to pop out. Is there anything wrong with my code?
textField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (Integer.parseInt(textField.getText())<=0){
JOptionPane.showMessageDialog(null,
"Error: Please enter number bigger than 0", "Error Message",
JOptionPane.ERROR_MESSAGE);
}
}
}
Any help would be appreciated!
Add a listener to the underlying Document, which is automatically created for you.
// Listen for changes in the text
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
if (Integer.parseInt(textField.getText())<=0){
JOptionPane.showMessageDialog(null,
"Error: Please enter number bigger than 0", "Error Message",
JOptionPane.ERROR_MESSAGE);
}
}
});
The usual answer to this is "use a DocumentListener". However, I always find that interface cumbersome. Truthfully the interface is over-engineered. It has three methods, for insertion, removal, and replacement of text, when it only needs one method: replacement. (An insertion can be viewed as a replacement of no text with some text, and a removal can be viewed as a replacement of some text with no text.)
Usually all you want is to know is when the text in the box has changed, so a typical DocumentListener implementation has the three methods calling one method.
Therefore I made the following utility method, which lets you use a simpler ChangeListener rather than a DocumentListener. (It uses Java 8's lambda syntax, but you can adapt it for old Java if needed.)
/**
* Installs a listener to receive notification when the text of any
* {#code JTextComponent} is changed. Internally, it installs a
* {#link DocumentListener} on the text component's {#link Document},
* and a {#link PropertyChangeListener} on the text component to detect
* if the {#code Document} itself is replaced.
*
* #param text any text component, such as a {#link JTextField}
* or {#link JTextArea}
* #param changeListener a listener to receieve {#link ChangeEvent}s
* when the text is changed; the source object for the events
* will be the text component
* #throws NullPointerException if either parameter is null
*/
public static void addChangeListener(JTextComponent text, ChangeListener changeListener) {
Objects.requireNonNull(text);
Objects.requireNonNull(changeListener);
DocumentListener dl = new DocumentListener() {
private int lastChange = 0, lastNotifiedChange = 0;
#Override
public void insertUpdate(DocumentEvent e) {
changedUpdate(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
changedUpdate(e);
}
#Override
public void changedUpdate(DocumentEvent e) {
lastChange++;
SwingUtilities.invokeLater(() -> {
if (lastNotifiedChange != lastChange) {
lastNotifiedChange = lastChange;
changeListener.stateChanged(new ChangeEvent(text));
}
});
}
};
text.addPropertyChangeListener("document", (PropertyChangeEvent e) -> {
Document d1 = (Document)e.getOldValue();
Document d2 = (Document)e.getNewValue();
if (d1 != null) d1.removeDocumentListener(dl);
if (d2 != null) d2.addDocumentListener(dl);
dl.changedUpdate(null);
});
Document d = text.getDocument();
if (d != null) d.addDocumentListener(dl);
}
Unlike with adding a listener directly to the document, this handles the (uncommon) case that you install a new document object on a text component. Additionally, it works around the problem mentioned in Jean-Marc Astesana's answer, where the document sometimes fires more events than it needs to.
Anyway, this method lets you replace annoying code which looks like this:
someTextBox.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
doSomething();
}
#Override
public void removeUpdate(DocumentEvent e) {
doSomething();
}
#Override
public void changedUpdate(DocumentEvent e) {
doSomething();
}
});
With:
addChangeListener(someTextBox, e -> doSomething());
Code released to public domain. Have fun!
Just create an interface that extends DocumentListener and implements all DocumentListener methods:
#FunctionalInterface
public interface SimpleDocumentListener extends DocumentListener {
void update(DocumentEvent e);
#Override
default void insertUpdate(DocumentEvent e) {
update(e);
}
#Override
default void removeUpdate(DocumentEvent e) {
update(e);
}
#Override
default void changedUpdate(DocumentEvent e) {
update(e);
}
}
and then:
jTextField.getDocument().addDocumentListener(new SimpleDocumentListener() {
#Override
public void update(DocumentEvent e) {
// Your code here
}
});
or you can even use lambda expression:
jTextField.getDocument().addDocumentListener((SimpleDocumentListener) e -> {
// Your code here
});
Be aware that when the user modify the field, the DocumentListener can, sometime, receive two events. For instance if the user selects the whole field content, then press a key, you'll receive a removeUpdate (all the content is remove) and an insertUpdate.
In your case, I don't think it is a problem but, generally speaking, it is.
Unfortunately, it seems there's no way to track the content of the textField without subclassing JTextField.
Here is the code of a class that provide a "text" property :
package net.yapbam.gui.widget;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
/** A JTextField with a property that maps its text.
* <br>I've found no way to track efficiently the modifications of the text of a JTextField ... so I developed this widget.
* <br>DocumentListeners are intended to do it, unfortunately, when a text is replace in a field, the listener receive two events:<ol>
* <li>One when the replaced text is removed.</li>
* <li>One when the replacing text is inserted</li>
* </ul>
* The first event is ... simply absolutely misleading, it corresponds to a value that the text never had.
* <br>Anoter problem with DocumentListener is that you can't modify the text into it (it throws IllegalStateException).
* <br><br>Another way was to use KeyListeners ... but some key events are throw a long time (probably the key auto-repeat interval)
* after the key was released. And others events (for example a click on an OK button) may occurs before the listener is informed of the change.
* <br><br>This widget guarantees that no "ghost" property change is thrown !
* #author Jean-Marc Astesana
* <BR>License : GPL v3
*/
public class CoolJTextField extends JTextField {
private static final long serialVersionUID = 1L;
public static final String TEXT_PROPERTY = "text";
public CoolJTextField() {
this(0);
}
public CoolJTextField(int nbColumns) {
super("", nbColumns);
this.setDocument(new MyDocument());
}
#SuppressWarnings("serial")
private class MyDocument extends PlainDocument {
private boolean ignoreEvents = false;
#Override
public void replace(int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
String oldValue = CoolJTextField.this.getText();
this.ignoreEvents = true;
super.replace(offset, length, text, attrs);
this.ignoreEvents = false;
String newValue = CoolJTextField.this.getText();
if (!oldValue.equals(newValue)) CoolJTextField.this.firePropertyChange(TEXT_PROPERTY, oldValue, newValue);
}
#Override
public void remove(int offs, int len) throws BadLocationException {
String oldValue = CoolJTextField.this.getText();
super.remove(offs, len);
String newValue = CoolJTextField.this.getText();
if (!ignoreEvents && !oldValue.equals(newValue)) CoolJTextField.this.firePropertyChange(TEXT_PROPERTY, oldValue, newValue);
}
}
I know this relates to a really old problem, however, it caused me some problems too. As kleopatra responded in a comment above, I solved the problem with a JFormattedTextField. However, the solution requires a bit more work, but is neater.
The JFormattedTextField doesn't by default trigger a property change after every text changes in the field. The default constructor of JFormattedTextField does not create a formatter.
However, to do what the OP suggested, you need to use a formatter which will invoke the commitEdit() method after each valid edit of the field. The commitEdit() method is what triggers the property change from what I can see and without the formatter, this is triggered by default on a focus change or when the enter key is pressed.
See http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html#value for more details.
Create a default formatter (DefaultFormatter) object to be passed to the JFormattedTextField either via its constructor or a setter method. One method of the default formatter is setCommitsOnValidEdit(boolean commit), which sets the formatter to trigger the commitEdit() method every time the text is changed. This can then be picked up using a PropertyChangeListener and the propertyChange() method.
An elegant way is to add the listener to the caret position, because it changes every time something is typed/deleted, then just compare old value with current one.
String oldVal = ""; // empty string or default value
JTextField tf = new JTextField(oldVal);
tf.addCaretListener(e -> {
String currentVal = tf.getText();
if(!currentVal.equals(oldVal)) {
oldVal = currentVal;
System.out.println("Change"); // do something
}
});
(This event is also being triggered every time a user just clicks into a TextField).
textBoxName.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
onChange();
}
#Override
public void removeUpdate(DocumentEvent e) {
onChange();
}
#Override
public void changedUpdate(DocumentEvent e) {
onChange();
}
});
But I would not just parse anything the user (maybe on accident) touches on his keyboard into an Integer. You should catch any Exceptions thrown and make sure the JTextField is not empty.
If we use runnable method SwingUtilities.invokeLater() while using Document listener application is getting stuck sometimes and taking time to update the result(As per my experiment). Instead of that we can also use KeyReleased event for text field change listener as mentioned here.
usernameTextField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
JTextField textField = (JTextField) e.getSource();
String text = textField.getText();
textField.setText(text.toUpperCase());
}
});
it was the update version of Codemwnci. his code is quite fine and works great except the error message. To avoid error you must change the condition statement.
// Listen for changes in the text
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
if (textField.getText().length()>0){
JOptionPane.showMessageDialog(null,
"Error: Please enter number bigger than 0", "Error Massage",
JOptionPane.ERROR_MESSAGE);
}
}
});
You can use even "MouseExited" to control.
example:
private void jtSoMauMouseExited(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
try {
if (Integer.parseInt(jtSoMau.getText()) > 1) {
//auto update field
SoMau = Integer.parseInt(jtSoMau.getText());
int result = SoMau / 5;
jtSoBlockQuan.setText(String.valueOf(result));
}
} catch (Exception e) {
}
}
Use a KeyListener (which triggers on any key) rather than the ActionListener (which triggers on enter)
DocumentFilter ? It gives you the ability to manipulate.
[ http://www.java2s.com/Tutorial/Java/0240__Swing/FormatJTextFieldstexttouppercase.htm ]
Sorry. J am using Jython (Python in Java) - but easy to understand
# python style
# upper chars [ text.upper() ]
class myComboBoxEditorDocumentFilter( DocumentFilter ):
def __init__(self,jtext):
self._jtext = jtext
def insertString(self,FilterBypass_fb, offset, text, AttributeSet_attrs):
txt = self._jtext.getText()
print('DocumentFilter-insertString:',offset,text,'old:',txt)
FilterBypass_fb.insertString(offset, text.upper(), AttributeSet_attrs)
def replace(self,FilterBypass_fb, offset, length, text, AttributeSet_attrs):
txt = self._jtext.getText()
print('DocumentFilter-replace:',offset, length, text,'old:',txt)
FilterBypass_fb.replace(offset, length, text.upper(), AttributeSet_attrs)
def remove(self,FilterBypass_fb, offset, length):
txt = self._jtext.getText()
print('DocumentFilter-remove:',offset, length, 'old:',txt)
FilterBypass_fb.remove(offset, length)
// (java style ~example for ComboBox-jTextField)
cb = new ComboBox();
cb.setEditable( true );
cbEditor = cb.getEditor();
cbEditorComp = cbEditor.getEditorComponent();
cbEditorComp.getDocument().setDocumentFilter(new myComboBoxEditorDocumentFilter(cbEditorComp));
I am brand new to WindowBuilder, and, in fact, just getting back into Java after a few years, but I implemented "something", then thought I'd look it up and came across this thread.
I'm in the middle of testing this, so, based on being new to all this, I'm sure I must be missing something.
Here's what I did, where "runTxt" is a textbox and "runName" is a data member of the class:
public void focusGained(FocusEvent e) {
if (e.getSource() == runTxt) {
System.out.println("runTxt got focus");
runTxt.selectAll();
}
}
public void focusLost(FocusEvent e) {
if (e.getSource() == runTxt) {
System.out.println("runTxt lost focus");
if(!runTxt.getText().equals(runName))runName= runTxt.getText();
System.out.println("runText.getText()= " + runTxt.getText() + "; runName= " + runName);
}
}
Seems a lot simpler than what's here so far, and seems to be working, but, since I'm in the middle of writing this, I'd appreciate hearing of any overlooked gotchas. Is it an issue that the user could enter & leave the textbox w/o making a change? I think all you've done is an unnecessary assignment.
Here is a Kotlin port of #Boann's answer, which is a great solution that has been working well for me.
import java.beans.*
import javax.swing.*
import javax.swing.event.*
import javax.swing.text.*
/**
* Installs a listener to receive notification when the text of this
* [JTextComponent] is changed. Internally, it installs a [DocumentListener] on the
* text component's [Document], and a [PropertyChangeListener] on the text component
* to detect if the `Document` itself is replaced.
*
* #param changeListener a listener to receive [ChangeEvent]s when the text is changed;
* the source object for the events will be the text component
*/
fun JTextComponent.addChangeListener(changeListener: ChangeListener) {
val dl: DocumentListener = object : DocumentListener {
private var lastChange = 0
private var lastNotifiedChange = 0
override fun insertUpdate(e: DocumentEvent) = changedUpdate(e)
override fun removeUpdate(e: DocumentEvent) = changedUpdate(e)
override fun changedUpdate(e: DocumentEvent) {
lastChange++
SwingUtilities.invokeLater {
if (lastNotifiedChange != lastChange) {
lastNotifiedChange = lastChange
changeListener.stateChanged(ChangeEvent(this))
}
}
}
}
addPropertyChangeListener("document") { e: PropertyChangeEvent ->
(e.oldValue as? Document)?.removeDocumentListener(dl)
(e.newValue as? Document)?.addDocumentListener(dl)
dl.changedUpdate(null)
}
document?.addDocumentListener(dl)
}
You can use it on any text component as follows:
myTextField.addChangeListener { event -> myEventHandler(event) }
Like his code, also public domain.

JTextField variable returns null outside of actionlistener?

I'm making a program that adds and formats files. I actually have many classes, but for the purpose of this question let's say I have two, guidialog and guimain.
In guidialog I have a JTextField and an actionlistener for it. Here is the actionlistner:
public void actionPerformed(ActionEvent event) {
blockName=textFieldBlockName.getText();
System.out.println("Made new block: "+blockName);
canClose=true;
guimain blockAddWrite = new guimain();
blockAddWrite.addNewBlockFile();
}
});
public String blockName;
Now in guimain I have a formatter which writes a file based on the name given in the text field:
public void addNewBlockFile() {
blockdialog blockName = new blockdialog();
try {
newBlock = new Formatter("Block" + blockName.blockName + ".java");
System.out.println("Created File: Block" + blockName.blockName);
} catch (Exception e) {
System.out.println("ERROR: Could Not Output Block File");
}
}
I do edit and close the file, but it wasn't necessary. But when I try this, all of the stuff in guimain that refers to blockName outputs as "null". I can't figure it out.
That's because in guimain, you're not using the blockName field of the dialog where the user entered something: you're using the blockName field of another, newly constructed dialog:
public void addNewBlockFile() {
blockdialog blockName = new blockdialog();
^--- the dialog is not the one where the user entered something. It's a new one.
You should pass the blockName from the dialog to the guimain:
public void actionPerformed(ActionEvent event) {
blockName=textFieldBlockName.getText();
System.out.println("Made new block: "+blockName);
canClose=true;
guimain blockAddWrite = new guimain(blockName); // we construct a guimain instance with the entered text
blockAddWrite.addNewBlockFile();
}
});
Side notes:
you should not use public fields. Use getter methods.
classes should be start with an upper-case and be spelt in CamelCase: GuiMain.

Document Listener firing some times but not others

this one has been puzzling me for a few days now and I feel that I have barely been able to narrow it down.
I am using Java and have a wizard for the user to step through. One of the steps allows the user to select a start time & date and an end time & date to schedule some work. I thought I had the validation on the dates complete (so that the end date must be after the start date & start date must be after current date etc). However, my validation method only fired once focus was lost on either date TextField so if the user selected a new date and immediately clicked next, an invalid choice could continue -- bug!
The start and end date selectors are widgets which are made up of a JSpinner and a calendar dialog which pops up if button is clicked. I have attached a Document Listener to the text field of the JSpinner:
DocumentListener docListener = new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
dateChanged();
System.out.println("insertUpdate");
}
#Override
public void removeUpdate(DocumentEvent e) {
dateChanged();
System.out.println("removeUpdate");
}
#Override
public void changedUpdate(DocumentEvent e) {
dateChanged();
System.out.println("changedUpdate");
}
};
((JSpinner.DefaultEditor) jSpinner1.getEditor()).getTextField().getDocument().addDocumentListener(
docListener);
When I run this class using its own main method to test:
public static void main(String[] args) {
DateSelectorWidget test = new DateSelectorWidget();
JFrame f = new JFrame("T E S T ");
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(test, BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
The DocListener fires each time and everything is fine. However this class is part of a bigger program and when it is called in it - the DocListener simply does not fire at all. An instance of the class is simply added to a panel in the wizard and yet it does not function the way it does when tested independently.
Any ideas anyone?
Thanks
My guess is that you directly or indirectly change the editor on the JSpinner after your line to retrieve, cast, get component, get model and add listener.

Categories

Resources