'Adding a button that reset all the text fields Netbeans Java
I'm trying to make a simple calculator and i want a reset button when pressed it clears all the text fields. I've already added an addActionListener and and ive already added the button panel just need to know the method on how do I do this. here is my code -
else if(choice.equals("c")) {
xValue = inputXTextField.getText();
yValue = inputYTextField.getText();
if(convertPreOperand(xValue) && convertPostOperand(yValue)) {
total = preOperand c postOperand;
outputTextField.setText(Double.toString(total));
}
}
Solution 1:[1]
You can use inputField.setText(""); to set the text of any field to nothing.
Solution 2:[2]
Your Code sniplet is quite short and I can't figure out, what it is there for, except giving the names of the Textfields?
Anyway, in genereal your program could look like this:
public class calculator implements ActionListener{
JTextField inputXTextField;
JTextField inputYTextField;
JButton bClear=new JButton("clear all");
JPanel panel;
private void init(){
bClear.addActionListener(this);
panel.add(bClear);
panel.add....
}
void actionPerformed(ActionEvent e){
Object obj=e.getSource();
if (obj=bClear){
inputXTextField=new JTextField(...);
or
inputXTextField.setText(""); //just to empty the field
.
.
}
}
Solution 3:[3]
JTextField textField1, textField2; //Or as many as you want;
JButton clear;
private void init(){
textField1 = new JTextField(); //Do this for all text fields.
clear=new JButton("C");
clear.addActionListener(this);
//Add controls to the panel/frame
}
void actionPerformed(ActionEvent e){
Object obj=e.getSource();
if (e.getSource==clear){
textField1.setText("");
textField2.setText("");
//... For all the textFields you have
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DHerls |
| Solution 2 | meister_reineke |
| Solution 3 | Vallabh Patade |
