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.
Related
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.
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.
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;
}
I have a JList in my GUI, which uses an ArrayList as data:
ArrayList Cruise = new ArrayList();
Cruise.add("Scottish to Greek Waters");
Cruise.add("Greek to Scottish Waters");
JScrollPane scrollPane = new JScrollPane();
CruiseList = new JList(Cruise.toArray());
CruiseList.setPreferredSize(new Dimension(200, 200));
scrollPane.setViewportView(CruiseList);
CruiseList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
CruiseList.setSelectedIndex(0);
CruiseList.setVisibleRowCount(6);
listPanel.add(scrollPane);
Frame1.setVisible(true);
I have a button - List all Cruises, which once clicked on should display this as output:
"Scottish to Greek Waters"
"Greek to Scottish Waters"
However, upon clicking the button, it only displays the selected list option as output.
This is what I have so far:
listallCruises.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String AllCruises = CruiseList.getSelectedValue().toString();
System.out.print("All Cruises:\n" + AllCruises + CruiseList.getModel() + "\n");
}
});
How do I print out all element in the list upon clicking the button?
You are outputting just the selected value because that's the method you are calling, getSelectedValue().
To display ALL the values, you have to get the model and iterate through the values, like so:
int size = CruiseList.getModel().getSize();
StringBuilder allCruises = new StringBuilder("All cruises:");
for(int i = 0; i < size; i++) {
allCruises.append("\n").append(CruiseList.getModel().getElementAt(i));
}
System.out.print(allCruises);
I'm a newbie so please be patient
What I want
I have a JPanel on which I have a JButton, a JLabel and a JTextArea. Upon pressing JButton, an image has to be printed inside the JLabel (and some text in JTextArea). This certain image (and text) is determined by if-else statements. Conditions of if-else are based on an integer variable R.
Basically its a survey like question-answer thing I'm trying to make. I use the R to record answers from user. When a user clicks a choice, the value of R gets updated.
Its working fine for the text, but not the image.
For text, I use a String variable yourphone. If the value of R in the end is eg 120, then yourphone gets updated to a string eg. Xperia Z.
I want a similar variable I can use for image, so that the picture of Xperia Z is displayed when the user clicks JButton.
Total value of R is used in if-else statements.
Structure
I initiate variables like this
int R=0;
String yourphone;
ImageIcon imageresult;
My JPanel which is meant to display result
final JPanel result = new JPanel();
result.setBackground(Color.BLACK);
getContentPane().add(result, "name_17130054294139");
result.setLayout(null);
final JTextArea txtrphoneresult = new JTextArea();
txtrphoneresult.setBackground(Color.BLACK);
txtrphoneresult.setForeground(Color.YELLOW);
txtrphoneresult.setFont(new Font("Tahoma", Font.PLAIN, 14));
txtrphoneresult.setBounds(448, 515, 469, 121);
result.add(txtrphoneresult);
JLabel resultlabel = new JLabel(imageresult);
resultlabel.setBounds(292, 122, 782, 346);
result.add(resultlabel);
JButton btnShowResult = new JButton("Show Result");
btnShowResult.setFont(new Font("Tahoma", Font.PLAIN, 10));
btnShowResult.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(R==1726)
{
yourphone = "Samsung Galaxy S4\r\nHTC One\r\nSony Xperia Z";
ImageIcon imageresult = new ImageIcon("galaxy_one_XperiaZ.jpg");
}
else if(R==5002)
{
yourphone = "Sony Xperia Z1\r\nSamsung Galaxy Note 3";
ImageIcon imageresult = new ImageIcon("Note3_sonyZ1.jpg");
}
else
{
yourphone = "No Results";
}
txtrphoneresult.setText(yourphone);
}
});
btnShowResult.setBounds(618, 48, 130, 32);
result.add(btnShowResult);
Problem
The image is not displayed at all.
If there is any other possible way to achieve this, please guide.
At first you create your imageresult inside if-else and it's not visible for all method. And you doesn't add your image to JLabel.
Make resultlabel as clas member or final variable.
Change your code in next way:
public void actionPerformed(ActionEvent e) {
ImageIcon imageresult = null;
if(R==1726)
{
yourphone = "Samsung Galaxy S4\r\nHTC One\r\nSony Xperia Z";
imageresult = new ImageIcon("galaxy_one_XperiaZ.jpg");
}
else if(R==5002)
{
yourphone = "Sony Xperia Z1\r\nSamsung Galaxy Note 3";
imageresult = new ImageIcon("Note3_sonyZ1.jpg");
}
else
{
yourphone = "No Results";
}
resultlabel.setIcon(imageresult)
txtrphoneresult.setText(yourphone);
}
Declare ImageIcon imageresult before the if statement and call
resultlabel.setIcon(imageresult)
after txtrphoneresult.setText(yourphone);
BTW: Don't use null layout/setBounds(). Read about layouts and choose proper one.
where do you set icon for your label.
you mising this line
resultlabel.setIcon(imageresult);
Make resultLabel final and change action performed:
public void actionPerformed(ActionEvent e)
{
ImageIcon imageresult = null;
if(R == 1726)
{
yourphone = "Samsung Galaxy S4\r\nHTC One\r\nSony Xperia Z";
imageresult = new ImageIcon("galaxy_one_XperiaZ.jpg");
}
else if(R == 5002)
{
yourphone = "Sony Xperia Z1\r\nSamsung Galaxy Note 3";
imageresult = new ImageIcon("Note3_sonyZ1.jpg");
}
else
{
yourphone = "No Results";
}
txtrphoneresult.setText(yourphone);
resultlabel.setIcon(imageresult);
}
The image is not displayed because you are not "giving" it to you JLabel. You can do it by using the setIcon() method.
You also have a problem with variable declaration. Unlike PHP and some other programming languages, in Java a variable only exists within the brackets (and sub-brackets) {} it has been declared in (despite there are some exceptions). For example :
public void myMethod() {
float b = 5f;
if (true) {
int a = 6;
if (true) {
// a exists, you can do whatever you like with it
// b exists, you can do whatever you like with it
}
// a exists you can do whatever you like with it
// b exists, you can do whatever you like with it
} // a is "destroyed"
// a doesn't exists
// b still exists
} // b is "destroyed"
// Neither a or b exists
You are in the exact same case with the declaration of your variable imageresult.