I am currently creating GUI using Netbeans in Java. How to make a JTextField
auto fill to contain the current system date when I load the JFrame
that contains that text field using a JButton
from another frame?
Asked
Active
Viewed 496 times
-2

Andrew Thompson
- 168,117
- 40
- 217
- 433

P.L.Siriwardana
- 7
- 1
- 7
-
no but i want to create this. and i dont know how to do it – P.L.Siriwardana Jun 09 '18 at 02:15
-
ah ok i got it @IMustBeSomeone – P.L.Siriwardana Jun 09 '18 at 03:20
-
See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) – Andrew Thompson Jun 09 '18 at 03:29
1 Answers
2
- Given the
JTextField
can be constructed (instantiated) when the button is pressed, fill it with the current date / time when constructed. - See any number of components that are better suited to displaying (and allowing the user to choose) a date. E.G.
new JSpinner(new SpinnerDateModel())
; - incidentallynew SpinnerDateModel()
defaults to the current date!
Here is an example of using the spinner / spinner date model.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class DateSpinner {
private JComponent ui = null;
DateSpinner() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(100,100,100,100));
JButton dateSelector = new JButton("Select a date (after now)");
ActionListener dateSelectorListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SpinnerDateModel spinnerDateModel = new SpinnerDateModel();
JSpinner spinner = new JSpinner(spinnerDateModel);
JOptionPane.showMessageDialog(
ui, spinner, "Choose Date", JOptionPane.QUESTION_MESSAGE);
System.out.println("Date Chosen: " + spinnerDateModel.getDate());
}
};
dateSelector.addActionListener(dateSelectorListener);
ui.add(dateSelector);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
DateSpinner o = new DateSpinner();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

Andrew Thompson
- 168,117
- 40
- 217
- 433