I try to convert data but without clicking on a button,
When I enter the data in the 1st textfield nothing happens
JTextField textC = new JTextField() ;
JTextField textF = new JTextField() ;
labelC.setText("Celsius");
labelF.setText("Fahrenheit");
ActionListener textFieldCListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String value = textC.getText();
try {
float valC = new Float(value);
float valF = valC * 1.8f + 32;
textF.setText(Float.toString(valF));
} catch (Exception exp) {
textF.setText("");
textC.setText("");
}
}};
You should add ActionListener to your JTextField object.
textC.addActionListener(textFieldCListener);
See this: What addActionListener does?
Try:
textC.addActionListener(textFieldCListener);
Related
Basically, I click a JButton (unipedal) and it pops up with a JOptionPane with a few JTextFields. I want to take the String inputs of these JTextFields and:
Check to make sure the string values are in a HashMap I have of type (posTasks.taskType), which they should be
Then create a new UNIPEDALImpl object with those Strings as parameters
Use the Strings as keys to another HashMap of type (jLabelsHM) to hide the JLabel if the key of this HashMap returns true when used as a key in posTasks.completedTasks.
I am getting several errors and I can't figure out why.
unipedal.addActionListener(new java.awt.event.ActionListener() {
#SuppressWarnings("null")
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
String robotName = null;
String firstTask = null;
String secondTask = null;
String thirdTask = null;
String fourthTask = null;
String fifthTask = null;
JPanel inputBox = new JPanel();
inputBox.setLayout(new GridLayout(0, 2, 3, 4));
JTextField name = new JTextField(15);
JTextField task1 = new JTextField(15);
JTextField task2 = new JTextField(15);
JTextField task3 = new JTextField(15);
JTextField task4 = new JTextField(15);
JTextField task5 = new JTextField(15);
inputBox.add(new JLabel("Robot's Name:"));
inputBox.add(name);
inputBox.add(new JLabel("Task 1:"));
inputBox.add(task1);
inputBox.add(new JLabel("Task 2:"));
inputBox.add(task2);
inputBox.add(new JLabel("Task 3:"));
inputBox.add(task3);
inputBox.add(new JLabel("Task 4:"));
inputBox.add(task4);
inputBox.add(new JLabel("Task 5:"));
inputBox.add(task5);
int option = JOptionPane.showConfirmDialog(middle,inputBox,
"Please fill all the fields", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
robotName.equals(name.getText());
firstTask.equals(task1.getText());
secondTask.equals(task2.getText());
thirdTask.equals(task3.getText());
fourthTask.equals(task4.getText());
fifthTask.equals(task5.getText());
if (!posTasks.taskType.containsKey(firstTask)||!posTasks.taskType.containsKey(secondTask)||!posTasks.taskType.containsKey(thirdTask)||!posTasks.taskType.containsKey(fourthTask)||!posTasks.taskType.containsKey(fifthTask)) {
throw new IllegalArgumentException("One or more of the tasks you have requested are invalid. Please choose tasks from the list provided and check your spelling!");
}
try {
UNIPEDALImpl unipedal = new UNIPEDALImpl(firstTask, secondTask, thirdTask, fourthTask,
fifthTask);
LinkedList<String>tasksList = new LinkedList <String>();
tasksList.add(firstTask);
tasksList.add(secondTask);
tasksList.add(thirdTask);
tasksList.add(fourthTask);
tasksList.add(fifthTask);
for (String task : tasksList) {
if (posTasks.completedTasks.get(task) == true) {
throw new IllegalArgumentException(task + "has already been completed. Please choose a different task or use 'refresh' if you want the task to be completed again");
}
unipedal.time += unipedal.taskTimes.get(task);
posTasks.completedTasks.put(task, true);
unipedal.tasksList.remove(task);
unipedal.taskCounter++;
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
for (Entry<String, JLabel> entry : jLabelsHM.entrySet()) {
if(posTasks.completedTasks.get(entry.getKey()) == true) {
jLabelsHM.get(entry.getKey()).setVisible(false);
}
}
}
}
});
First of all we don't have UNIPEDALImpl class here, so with a black-box view, I can not tell you if there is an error within that part.
About the problems in your code. first it seems that you want to fill your variable with equals method which is wrong, you need to use = sign.
equals methos is for comparing two objects not assigning variables.
robotName = name.getText();
firstTask = task1.getText();
secondTask = task2.getText();
thirdTask = task3.getText();
fourthTask = task4.getText();
fifthTask = task5.getText();
then you move from there.
I want to return a string fileName from the enterFileName textfield when I press the saveFileNameBtn button. I tried getting the text in an inline action listener method but when I do that the variable is out of scope when I try to return it.
String getSaveFileName()
{
JFrame enterFileNameWin = new JFrame();
JPanel fileNameP = new JPanel();
enterFileNameWin.add(fileNameP);
JLabel fileNamePrompt = new JLabel("Enter a name for the file");
TextField enterFileName = new TextField(20);
JButton saveFileNameBtn = new JButton("Save");
fileNameP.add(fileNamePrompt);
fileNameP.add(enterFileName);
fileNameP.add(saveFileNameBtn);
enterFileNameWin.setVisible(true);
enterFileNameWin.setSize(300, 100);
String fileName = enterFileName.getText();
fileName = fileName + ".dat";
saveFileNameBtn.addActionListener((ActionListener) this);
return fileName;
}
This doesn't work because fileName is out of scope and cannot be returned.
String getSaveFileName()
{
JFrame enterFileNameWin = new JFrame();
JPanel fileNameP = new JPanel();
enterFileNameWin.add(fileNameP);
JLabel fileNamePrompt = new JLabel("Enter a name for the file");
TextField enterFileName = new TextField(20);
JButton saveFileNameBtn = new JButton("Save");
fileNameP.add(fileNamePrompt);
fileNameP.add(enterFileName);
fileNameP.add(saveFileNameBtn);
enterFileNameWin.setVisible(true);
enterFileNameWin.setSize(300, 100);
saveFileNameBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String fileName = enterFileName.getText();
fileName = fileName + ".dat";
}
});
return fileName;
}
saveFileNameBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String textFieldValue = enterFileName.getText();
// call another function or do some operations
}
})
You can define the fileName variable outside of the ActionListener class and then reference it using the syntax OuterclassName.this. Since I don't know what the name of your class is, replace Outerclass with that name.
String getSaveFileName() {
//your other code...
String fileName;
saveFileNameBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Outerclass.this.fileName = enterFileName.getText();
}
});
return fileName;
}
If you are using Java 8, you could even simplify the code further using Lambda expressions for the Anonymous ActionListener class.
String getSaveFileName() {
//your other code...
String fileName;
saveFileNameBtn.addActionListener( e->{ Outerclass.this.fileName = enterFileName.getText(); });
return fileName;
}
A similar example can be found in this post: (ignoring the final issue) Accessing Variable within JButton ActionListener
I got a JTextfield a GetText method, and an array to store the numbers logged on the Jtextfield.
JTextField tf1 = new JTextField();
frame.add(tf1);
String tfone = tf1.getText();
int one = Integer.parseInt(tfone);
int[][] array = new int[4][5];
array[0][0] = one;
array[0][1] = otherValues...
The problem here is, that code execute all, so no wait for a user input into the JtextField. How can i make the jtextfield wait, until an user log in something. To latter on execute the Integer.Parseint ?
I can no change JtextField by another method cuz I'm working with GUI (Graphic User Environment.)
You may try adding Button and then perform it's ActionListener and then enter the input and pressing the button will load the code of doing the stuff you want.
You can use a DocumentListener:
JTextField tf1 = new JTextField();
tf1.getDocument().addDocumentListener(DocumentListener()
{
#Override
public void changedUpdate(DocumentEvent e)
{
}
#Override
public void insertUpdate(DocumentEvent e)
{
// parse here
}
#Override
public void removeUpdate(DocumentEvent e)
{
// parse here
}
});
Instead of JTextField, you can use JOptionPane to get the user input. It will display a modal form and wait until the user validates.
String tfone = JOptionPane.showInputDialog("Please enter a number");
// Now test the user input
if (tfone != null) {
int one = Integer.parseInt(tfone);
}
Here is the documentation User input with JOptionPane
Here is the code:
JTextField tf1 = new JTextField();
frame.add(tf1);
JButton b = new JButton();
b.setText("Solve");
b.setBounds(30, 140, 110, 30);
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
String tfone = tf1.getText();
int one = Integer.parseInt(tfone);
int[][] array = new int[4][5];
array[0][0] = one;
array[0][1] = otherValues...
//Here you can complete the rest of functions
});
frame.add(b);
Once the user press the button the code will end its execution.
Ok my code has to pick route combo box (check) display in label(check) have a return and single ticket combobox(check) need it to display text(check) my problem is it only prints text related to one of my statments hope someone can tell me how to fix my if statments. The lable changes on a button .It reads code by lable.So far it only prints 15 and wont print 20 unless i had another label but this wouldnt make sense for the program
package learning;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList.*;
import java.util.Arrays.*;
import java.util.List.*;
#SuppressWarnings("unused")
public class test {
String[] items = {"Tipperary_to_cork","Cork_to_Dublin","Limerick_to_Tipperary","Dublin_to_Cork"};
JComboBox c = new JComboBox(items);
JButton b = new JButton("From");
JLabel l = new JLabel();
String[] items2 = {"window","aisle"};
JComboBox m = new JComboBox(items2);
JButton n = new JButton("Seat");
JLabel o = new JLabel();
String[] items3 = {"Single","return"};
JComboBox x = new JComboBox(items3);
JButton y= new JButton("Ticket");
JLabel z = new JLabel("choose Ticket");
String[] items4 = {"1","2","3","4","5","6","7","8","9","10"};
JComboBox<?> xx = new JComboBox(items4);
JButton yy = new JButton("seat");
JLabel zz = new JLabel("Choose a seat");
JLabel hh = new JLabel("cost");
JButton ccc = new JButton("comfirm");
JLabel hhh = new JLabel("");{
}
public test(){
frame();
}
public void frame(){
JFrame wolf = new JFrame();//frame
wolf.setVisible(true);
wolf.setSize(350,350);
wolf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
JPanel p = new JPanel();
p.add(hh);
p.add(c);//
p.add(b);//
p.add(l);//lable1
p.add(m);//
p.add(n);//
p.add(o);//lable 2
p.add(x);//
p.add(y);//
p.add(z);//lable 2
p.add(xx);//
p.add(yy);//
p.add(zz);//lable 2
p.add(ccc);
p.add(hhh);
wolf.add(p);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = c.getSelectedItem().toString();
l.setText(s);
}
});
n.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = m.getSelectedItem().toString();
o.setText(s);
}
});
y.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = x.getSelectedItem().toString();
z.setText(s);
}
});
yy.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = xx.getSelectedItem().toString();
zz.setText(s);
}
});
}
{
if(l.getText().equals("Tipperary_to_cork")&&(z.getText().equals("single"))){
ccc.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
hh.setText("15"); //***
}});
if(l.getText().equals("Tipperary_to_cork")&&(z.getText().equals("return"))){
ccc.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
hh.setText("20"); //****
}
});
}}}
public static void main(String[]args){
new test();
}
}
You want to check "if some condition" when you click the button. So, start with one simple if statement inside one of the actionPerformed methods. You shouldn't add an action listener inside an if statement, you should always perform an action, and determine the event inside that action.
For example
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = c.getSelectedItem().toString();
if (s.equals("Tipperary to cork")) {
// TODO: do something
}
}
});
Original answer
These line just happen to work because you have if(false==false)
if(l.equals("Tipperary to cork")==(z.equals("single"))) { ... }
if(l.equals("Tipperary to cork")==(z.equals("return"))) { ... }
The reason they evaluate to false is because you are comparing a JLabel.equals(String). You should use l.getText().equals("text here"), but...
The problem is that you have those if statements inside the constructor for your class, meaning that they are the first thing that is evaluated in your code. You should move the corrected if statements into the ActionListeners for the respective buttons.
Additional note: You seem to want "Tipperary to cork" AND "single". In that case, use && in place of ==. Alternatively, you could do this (psuedocode intentional)
if "Tipperary to cork" {
if "single" { ... }
else if "return" { ... }
}
In reality, though, you should compare c.getSelectedItem().toString() instead of the text of the label, but that's your decision.
I have two JTextField which take numbers from users, like this:
nbMuscle = new JTextField();
nbMuscle.setText("2");
and this:
nbFuyard = new JTextField();
nbFuyard.setText("1");
my JTextArea() takes make an addition of both JTextField's values, like this:
nbPersonnages = new JTextArea();
int nombMusc = Integer.valueOf(nbMuscle.getText());
int nombFuy = Integer.valueOf(nbFuyard.getText());
int nbTotal = nombMusc + nombFuy;
nbPersonnages.setText(String.valueOf(nbTotal));
It works like a charm but I have one problem, if the user edit one of the JTextFields, the JTextArea value don't change. I have found on internet some notions like jTextArea.appened(String str) but it doesn't work.
Any idea of what I could do?
You have to add a DocumentListener to the underlying Document of the TextFields to listen to changes made while the program runs.
The easiest way to do this is proboably an anonymous class.
Here is the Code:
nbMuscle = new JTextField();
nbMuscle.setText("2");
nbFuyard = new JTextField();
nbFuyard.setText("1");
nbPersonnages = new JTextArea();
DocumentListener dl = new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
textChanged();
}
#Override
public void insertUpdate(DocumentEvent e) {
textChanged();
}
#Override
public void changedUpdate(DocumentEvent e) {
// This method is not called when the text of the Document changed, but if attributes of the Document changed.
}
private void textChanged() {
int nombMusc = Integer.valueOf(nbMuscle.getText());
int nombFuy = Integer.valueOf(nbFuyard.getText());
int nbTotal = nombMusc + nombFuy;
nbPersonnages.setText(String.valueOf(nbTotal));
}
};
int nombMusc = Integer.valueOf(nbMuscle.getText());
int nombFuy = Integer.valueOf(nbFuyard.getText());
int nbTotal = nombMusc + nombFuy;
nbPersonnages.setText(String.valueOf(nbTotal));
nbMuscle.getDocument().addDocumentListener(dl);
nbFuyard.getDocument().addDocumentListener(dl);