Java TextField Date auto fill - java

Alright I got something like this:
public void menu() {
final Form menu = new Form("Menu");
menu.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
Button confirm = new Button("Confirm");
Container creditCardContainer = new Container(new GridLayout(1, 3));
final TextField num1 = new TextField(3);
final TextField num2 = new TextField(3);
final TextField num3 = new TextField(3);
num1.setConstraint(TextArea.NUMERIC);
num2.setConstraint(TextArea.NUMERIC);
num3.setConstraint(TextArea.NUMERIC);
creditCardContainer.addComponent(num1);
creditCardContainer.addComponent(num2);
creditCardContainer.addComponent(num3);
Validator v = new Validator();
v.addConstraint(num1, new LengthConstraint(2));
v.addConstraint(num2, new LengthConstraint(2));
v.addConstraint(num3, new LengthConstraint(4));
automoveToNext(num1, num2);
automoveToNext(num2, num3);
menu.add(creditCardContainer);
menu.add(confirm);
v.addSubmitButtons(confirm);
menu.show();
confirm.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
String getdate = num1.getText() + "/" + num2.getText() + "/" + num3.getText();
System.out.println(getdate);
new StateMachine("/theme");
}
});
}
}
private void automoveToNext(final TextField current, final TextField next) {
current.addDataChangedListener(new DataChangedListener() {
public void dataChanged(int type, int index) {
if(current.getText().length() == 3) {
Display.getInstance().stopEditing(current);
String val = current.getText();
current.setText(val.substring(0, 2));
next.setText(val.substring(2));
Display.getInstance().editString(next, 3, current.getConstraint(), next.getText());
}
}
});
}
Notice that addDataChangeListener is deprecated so I had to change it to addDataChangedListener instead.
I think there is something wrong in my code, because when I run it in the Codename One Simulator, it still allow me to type letters, even with the code below:
num1.setConstraint(TextArea.NUMERIC);
num2.setConstraint(TextArea.NUMERIC);
num3.setConstraint(TextArea.NUMERIC);
Also when I finish typing the date, my confirm button doesn't get highlighted as it should be. Please someone help me to fix it.
Obs: My date is intended to be dd/MM/yyyy

We don't support direct field masking as native text field input doesn't handle that very well. You have 2 options I can think of:
Use Date Picker which launches a great device native UI to pick the date. Notice it's not great in the simulator but on Android/iOS it would look good.
Use 3 text fields and automatically move to the next as you type like we did for this credit card input sample: http://www.codenameone.com/blog/validation-regex-masking.html

Using
try {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = format.parse("");
}catch (ParseException e) {
System.out.println("Wrong format.");
}
to check if the date is valid format.

Related

Try still works even if there is an error

I have 2 radio buttons and pressed it in the order a->b->a I expect the output to be like a(doesn't print anything)->b(prints "N removes M")->a(prints M removes N), but what I get is a(doesn't print anything)->b(prints "N removes M")->a(prints M removes M). Why is that so? =( (btw I'm new here and a beginner in Java programming)
public GUI() {
militarytonorm = new JRadioButton("Military Time to Standard Time", false);
normtomilitary = new JRadioButton("Standard Time to Military Time", false);
add(militarytonorm);
add(normtomilitary);
group = new ButtonGroup();
group.add(militarytonorm);
group.add(normtomilitary);
checkButton ButtonChecker = new checkButton();
militarytonorm.addActionListener(ButtonChecker);
normtomilitary.addActionListener(ButtonChecker);
}
private class checkButton implements ActionListener {
public void actionPerformed(ActionEvent MTNButton) {
if (MTNButton.getSource() == militarytonorm) {
if (x == 1) {
try {
getContentPane().remove(Mtext);
getContentPane().remove(Minputhr);
getContentPane().remove(Minputmin);
getContentPane().remove(Minputsec);
getContentPane().remove(doneButton);
System.out.print("M removes M");
} catch (Exception error) {
getContentPane().remove(Ntext);
getContentPane().remove(Ninputhr);
getContentPane().remove(Ninputmin);
getContentPane().remove(Ninputsec);
getContentPane().remove(AMPM);
getContentPane().remove(NTMButton);
System.out.print("M removes N");
}
}
Mtext = new JLabel("input military hours, minutes and seconds");
add(Mtext);
Minputhr = new JFormattedTextField("00");
Minputhr.setColumns(2);
add(Minputhr);
Minputmin = new JFormattedTextField("00");
Minputmin.setColumns(2);
add(Minputmin);
Minputsec = new JFormattedTextField("00");
Minputsec.setColumns(2);
add(Minputsec);
doneButton = new JButton("Done");
add(doneButton);
MTNthehandler handler = new MTNthehandler();
doneButton.addActionListener(handler);
x = 1;
} else if (MTNButton.getSource() == normtomilitary) {
if (x == 1) {
try {
getContentPane().remove(Ntext);
getContentPane().remove(Ninputhr);
getContentPane().remove(Ninputmin);
getContentPane().remove(Ninputsec);
getContentPane().remove(AMPM);
getContentPane().remove(NTMButton);
System.out.print("N removes N");
} catch (Exception error) {
getContentPane().remove(Mtext);
getContentPane().remove(Minputhr);
getContentPane().remove(Minputmin);
getContentPane().remove(Minputsec);
getContentPane().remove(doneButton);
System.out.print("N removes M");
}
}
Ntext = new JLabel("input standard hours, minutes and seconds");
add(Ntext);
Ninputhr = new JFormattedTextField("00");
Ninputhr.setColumns(2);
add(Ninputhr);
Ninputmin = new JFormattedTextField("00");
Ninputmin.setColumns(2);
add(Ninputmin);
Ninputsec = new JFormattedTextField("00");
Ninputsec.setColumns(2);
add(Ninputsec);
AMPM = new JList(AMorPM);
AMPM.setVisibleRowCount(2);
AMPM.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
add(new JScrollPane(AMPM));
selectList AMPMSelect = new selectList();
AMPM.addListSelectionListener(AMPMSelect);
NTMButton = new JButton("Done");
add(NTMButton);
NTMthehandler NTMhandler = new NTMthehandler();
NTMButton.addActionListener(NTMhandler);
x = 1;
}
}
}
A note to start with: this is very complicated code - it would be much simpler if you based your GUI on a tabbed pane (https://docs.oracle.com/javase/tutorial/uiswing/components/tabbedpane.html) with one tab for "Military Time to Standard Time" and a second tab for "Standard Time to Military Time".
To explain the behaviour you are seeing:
The first time you press the "militarytonorm" radio button, x is 0 so the code won't try to remove anything and nothing is printed. Then you create a JLabel, store a reference in Mtext and add it to the root pane (plus several more, but for the problem these are not relevant.)
If you now press the "normtomilitary" radio button, x is 1 so you try to remove Ntext from the content pane. Since Ntext is not initialized yet this will throw a NullPointerException which is caught with catch (Exception error) and the code removes the Mtext label and prints "N removes M".
Up until now everything as you expected.
BUT:
If you now press the "militarytonorm" radio button, x is 1 and the code tries to remove the Mtext label. Since Mtext is a valid reference to a JLabel instance the code will not throw an exception! All those getContentPane().remove(Mxxxx) will do nothing (since all of the components have already been removed in step 2 above) and then "M removes M" is printed.

Passing variable values from UI to action listener

I am trying to learn Java so I apologize if this is a rookie question. I have researched enough before asking this question here. I appreciate your time and guidance here.
I have written a simple application where I am asking user to enter information like "Serverprocessorspeed", "RAM" etc
I need the information entered by the user in the fields "Serverprocessorspeed", "RAM" to be passed to Action Listener. These values are in turn sent to a database server.
Cloudbroker() {
f1 = new JFrame("Cloud Broker");
serverprocessorspeed = new JLabel("serverprocessorspeed :");
RAM = new JLabel("RAM :");
serverstorage = new JLabel("serverstorage :");
latency = new JLabel("latency :");
Region = new JLabel("Region");
txtserverprocessorspeed = new JTextField(60);
txtRAM = new JTextField(60);
txtserverstorage = new JTextField(60);
txtlatency = new JTextField(60);
txtRegion = new JTextField(60);
btnClose = new JButton("Close");
btnSave = new JButton("Save");
btnDelete = new JButton("Delete");
btnUpdate = new JButton("Update");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("The information you entered has been saved");
Connection conn1 = null;
try {
String dbURL1 =
"jdbc:sqlserver://localhost\\SQLEXPRESS:1433;"
+ "databaseName=dbcloudbroker;user=XXX;password=XXXX";
System.out.println("this is connection inside the SAVE button");
conn1 = DriverManager.getConnection(dbURL1);
Statement stmt1 = conn1.createStatement();
// I need these values to be the ones the user
// enters in the feilds serverprocessorspeed and RAM.
stmt1.executeUpdate(
"INSERT INTO cloudbrokertable " + "VALUES(XXXX, XXXXX)");
} catch (SQLException e1) {
e1.printStackTrace();
} finally {
try {
if (conn1 != null && !conn1.isClosed()) {
conn1.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
}
Based upon the suggestion I received, I edited my code accordingly
String speed = txtserverprocessorspeed.getText();
String ram = txtRAM.getText();
String storage = txtserverstorage.getText();
String latency = txtlatency.getText();
String region = txtRegion.getText();
System.out.println(speed);
stmt1.executeUpdate("INSERT INTO cloudbrokertable VALUES ('"+speed +"','"+ram+"','"+storage+"','"+latency+"','"+region+"')");
Now get the following error - com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near ')'.
The value is correctly passed into the variable speed and I can print it out.
I need the information entered by the used in the fields "Serverprocessorspeed", "RAM" to be passed to Action Listener. These values are in turn sent to a database server.
No, you don't, this isn't how this works (sorry). But, based on you code snippet, I would suggest you already have access to the information you need, for example...
btnSave.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String ram = txtRAM.getText();
String speed = txtserverprocessorspeed.getText();
String storage = txtserverstorage.getText();
String latency = txtlatency.getText();
String region = txtRegion.getText();
//...
It's the problem with your SQL statement. You need to check if it does work.
Simply open your DB to test it with a sample statement like:
INSERT INTO cloudbrokertable VALUES ('100','DDR2','500','1000','US')
If this doesn't work it means you need to fix your statement.
I hope this help.

How can I add values from textfield when i press the button with not having all of the values

im working on a java program using GUI, and i ran into a problem whenever i try to add the values from the text fields and one is missing it doesn't work and i get an error but if all of them are available i get the right answer, how can i add without having all the values?
JButton btnCheckOut = new JButton("CHECK OUT");
btnCheckOut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double apples, strawberries, watermelon, tomatoe, carrot, beef, lamb, payment;
apples = Double.parseDouble(textField.getText());
strawberries = Double.parseDouble(textField_1.getText());
watermelon = Double.parseDouble(textField_2.getText());
tomatoe = Double.parseDouble(textField_3.getText());
carrot = Double.parseDouble(textField_4.getText());
beef = Double.parseDouble(textField_5.getText());
lamb = Double.parseDouble(textField_6.getText());
payment = (apples*8)+(strawberries*10)+(watermelon*14)+
(tomatoe*5)+(carrot*6)+(beef*25)+(lamb*20);
DecimalFormat df = new DecimalFormat("###.##");
textField_7.setText(String.valueOf(df.format(payment)));
}
});
Create e.g. getDoubleValue, which you apply to all your items when read. Simple as:
apples = getDoubleValue( textField.getText() );
...
...
then
public double getDoubleValue( String txt ) {
double d = 0d;
try {
if( txt != null && !txt.isEmpty() ) {
d = Double.parseDouble( txt );
}
} catch(Exception ex) {}
return d;
}
(This will also take care for "dirty input", if the textfield does not contain a number it will set it to zero during parse).
When you make your textFields, initialize the text there to 0. Like
JTextField textField_1 = new JTextField("0");
Or, you could add
if(textField.getText() == ""){
textField.setText("0");
}
For each text field before trying to parse to double.
Create an IF statement that sets the variables to zero if its respective TextField is empty, before you do the math operation.
if(textfield.getText().isEmpty())
{
apples = 0;
}

How can I know if the user is inserting a valid Date or not in Java's Swing?

I am creating a project in which I am supposed to take date of birth of any person. So for that I have taken 3 combo boxes: date, month and year. But how I will know that the Date which is going to be inserted is valid because the number of day is different-different months and years is different.
And is there any ready made GUI component for taking dates from users?
I am designing using Swing package.
My sample code is
import java.awt.*;
import javax.swing.*;
public class Pro1 extends JFrame
{
JComboBox dd, mm, yy;
JLabel doblbl;
Container con;
public Pro1()
{
con = getContentPane();
doblbl = new JLabel("Date of Birth :-");
doblbl.setHorizontalAlignment(SwingConstants.CENTER);
doblbl.setFont(new Font("Arial",Font.BOLD,17));
doblbl.setForeground(Color.blue);
doblbl.setOpaque(true);
doblbl.setBackground(new Color(230,180,230));
dd = new JComboBox();
mm = new JComboBox();
yy = new JComboBox();
for(int i = 1; i<=31; i++)
dd.addItem("" + i);
for(int i = 1; i<=12; i++)
mm.addItem("" + i);
for(int i = 1960; i<=2014; i++)
yy.addItem("" + i);
con.setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
int i = 120;
doblbl.setBounds(30,i+=40,270,30);
int j = 120;
dd.setBounds(350,j+=40,50,30);
mm.setBounds(420,j,50,30);
yy.setBounds(480,j,70,30);
con.add(doblbl);
con.add(dd);
con.add(mm);
con.add(yy);
setSize(1500,800);
setVisible(true);
con.setBackground(new Color(125,80,140));
}
public static void main(String s[])
{
Pro1 p1 = new Pro1();
}
}
You can use SimpleDateFormat to parse or format the date as dd/MM/yyyy.
Sample code:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String dateString = "30/02/2014"; // form date string in above format
String formattedDate = sdf.format(sdf.parse(dateString));
if (formattedDate.equals(dateString)) {
System.out.println("valid date");
} else {
System.out.println("Invalid date"); // It's an invalid date
}
Consider offering the user a JSpinner with a SpinnerDateModel, then it is easier for the user to enter, or scroll through and select, a valid date.
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class PromptForDate {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {}
SpinnerDateModel dateModel = new SpinnerDateModel(
new Date(), null, null, Calendar.DAY_OF_MONTH );
JSpinner dateSpinner = new JSpinner(dateModel);
dateSpinner.setEditor(
new JSpinner.DateEditor(dateSpinner, "dd/MM/yyyy"));
JOptionPane.showMessageDialog(
null, dateSpinner, "D.O.B.?",
JOptionPane.QUESTION_MESSAGE);
System.out.println(dateModel.getValue());
}
};
SwingUtilities.invokeLater(r);
}
}
And is there any ready made GUI component for taking dates from users?
Yes, there are several options in standard API and third-party libraries, as exposed in this answer: JSpinner + SpinnerDateModel or JCalendar or JXDatePicker. These components will also solve this other problem:
But how i will know that the date which is going to be inserted is
valid because the number of dates in different-different months and
years is different.
Off-topic
About this:
con.setLayout(null);
...
dd.setBounds(350,j+=40,50,30);
mm.setBounds(420,j,50,30);
yy.setBounds(480,j,70,30);
...
con.add(dd);
con.add(mm);
con.add(yy);
While using Null layout is perfectly possible, Swing is designed to be used along with layout managers and thus null layout is discouraged. See this topic Why is it frowned upon to use a null layout in SWING?.

Counter Invoked in Two ActionListeners

I have a counter x that I want to invoke in two separate ActionListeners. When I try to make x into final, I can't increment using x++;. I tried to make x within the nest, but then I can't use the same value in the other ActionListener. Code is as follows:
buttonIn.addActionListener(new ActionListener() {
String reportDate = "";
int x = 0;
public void actionPerformed(ActionEvent e)
{
DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm aa");
Date time = new GregorianCalendar().getTime();
reportDate = df.format(time);
String confirm = name.getText() + " has checked in at " + reportDate;
timeLabel.setText(confirm);
timeLabel.setVisible(true);
String action = "Time In";
reportData[x][0] = name.getText();
reportData[x][1] = "Time In";
reportData[x][2] = reportDate;
x++;
System.out.println(x);
}
});
buttonOut.addActionListener(new ActionListener() {
String reportDate = "";
public void actionPerformed(ActionEvent e)
{
DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm aa");
Date time = new GregorianCalendar().getTime();
reportDate = df.format(time);
String confirm = name.getText() + " has checked out at " + reportDate;
timeLabel.setText(confirm);
timeLabel.setVisible(true);
reportData[x][0] = name.getText();
reportData[x][1] = "Time Out";
reportData[x][2] = reportDate;
x++;
}
});
One simple option is to use AtomicInteger instead - then the variable can be final, but you can still increment the wrapped value. So:
final AtomicInteger counter = new AtomicInteger(0);
buttonIn.addActionListener(new ActionListener() {
// Within here, you can use counter.get and counter.incrementAndGet
});
buttonOut.addActionListener(new ActionListener() {
// Within here, you can use counter.get and counter.incrementAndGet
});
I'd also strongly consider extracting that code into a separate class though - almost all the code is the same, so you should be able to remove the duplication by parameterizing the differences. So you'd end up with something like:
AtomicInteger counter = new AtomicInteger(0);
buttonIn.addActionListener(new ReportListener(
counter, reportData, "%s has checked in at %s", "Time In"));
buttonOut.addActionListener(new ReportListener(
counter, reportData, "%s has checked out at %s", "Time Out"));
(Where ReportListener is the new class implementing ActionListener.)
Additionally:
I strongly suspect you want to use HH rather than hh in your SimpleDateFormat
Consider which time zone and locale you want to use in your SimpleDateFormat, and specify them explicitly for clarity
To get the current time, just call new Date() rather than creating a calendar and extracting the date from it
There's no obvious reason for having reportDate as an instance variable
For testability, I'd encourage you to use some sort of Clock interface, with an implementation provided by dependency injection, so you can fake time appropriately
Consider using Joda Time for all date/time work; it's much cleaner than the built-in date/time API

Categories