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));
}
}
You can use inputField.setText(""); to set the text of any field to nothing.
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
.
.
}
}
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
}
}
Related
Apparently my Google-fu skills are bit lacklustre and I can't figure out how to get JTextField when pressing a JButton.
Please note that I've removed some parts of the code for ease of reading.
If you see some variable that's not defined assume that it was part of that code.
As it stands, the code works fine.
public final class Main {
// Some removed code was here
private void prepareGUI() {
// Top right stuff
JPanel topRightPanel = new JPanel();
topRightPanel.setLayout(new FlowLayout());
JLabel topRightLabel = new JLabel("Address");
JTextField topRightTextField = new JTextField("", 15);
topRightTextField.setName("add_address");
JButton topRightButton = new JButton("Add");
topRightButton.setName("add_btn");
topRightPanel.add(topRightLabel);
topRightPanel.add(topRightTextField);
topRightPanel.add(topRightButton);
mainFrame.add(topRightPanel);
// The button in question. Very suggestive name, I know.
topRightButton.addActionListener(new GenericButtonListener());
genericButtonListener.setKernel(kernel);
// some other non relevant stuff here
mainFrame.setVisible(true);
}
}
public class GenericButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
String btnName = btn.getName();
if(btnName.toLowerCase().contains("add_btn")) {
addBtn(btn);
}
}
public void addBtn(JButton button){
SshFileIO sshFileIO = kernel.getFileIO();
// Get field text here
}
}
My current dilemma is how to get said textfield value inside GenericButtonListener.
I realize that I can use getText to get the text field value, however I don't have access to that variable inside the actionPerformed function.
I suppose this is more of a scoping problem rather than anything else.
I just need some pointing in the right direction, no hand holding required.
It's painfully obvious that I'm very new to Java.
Please try to get a reference of topRightTextField with the constructor of GenericButtonListener. Store as property of the class and use it inside actionPerformed.
Change this one:
topRightButton.addActionListener(new GenericButtonListener());
To this:
topRightButton.addActionListener(new GenericButtonListener(topRightTextField));
And inside class GenericButtonListener add field:
private JTextField topRightTextField;// set it in the constructor
And then use it inside of your method actionPerformed.
Have a nice coding and good luck!
I create some JButtons with a method, but I don't give them a variable i can call them with. i was wondering if it is possible to change the text somehow, after the button is created from another method. I am aware of that i can get the action command when the button is pressed but i want to change the button text, without it being pressed. I can give the buttons names like but would prefer not to. since I am only going to call half of them, and then I don't think its a good idea. or is it?
JButton button1 = buttons(0,0,0);
public JButton buttons(int coord, int coord1, int number) {
JButton box = new JButton("");
box.setFont(new Font("Tahoma", Font.PLAIN, 60));
box.setBounds(coord, coord1, 100, 100);
contentPane.add(box);
box.addActionListener(this);
box.setActionCommand(Integer.toString(number));
return box;
}
public static void main(String[] args) {
buttons(0,0,0);
buttons(98,0,1);
buttons(196,0,2);
buttons(0,98,3);
addText();
}
public void addText() {
//help me guys
button.setText("Please fix me");
}
You can get pressed button from actionEvent
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
}
Why not just have them in a public arraylist?
ArrayList<JButton> buttons = new ArrayList<JButton>();
public JButton buttons(int coord, int coord1, int number) {
JButton box = new JButton("");
box.setFont(new Font("Tahoma", Font.PLAIN, 60));
box.setBounds(coord, coord1, 100, 100);
contentPane.add(box);
box.addActionListener(this);
box.setActionCommand(Integer.toString(number));
buttons.add(box);//Add it here
return box;
}
This way you can loop through them later and change something if you want to,
for(JButton b : buttons){
if(/*Whatever*/){
b.setText("New name");
}
}
I can give the buttons names like but would prefer not to. since I am only going to call half of them, and then I don't think its a good idea. or is it?
You are creating problems for yourself. Even if you may only need the call a few/none of them, there is significant advantage for not keeping a reference for them.
If you have too many JButtons and you do not want to have a separate variable name for each of them, you can have an array/collection of JButtons.
JButton[] btns = new JButton[size];
//or
ArrayList<JButton> btns= new ArrayList<JButton>();
To change text for all buttons:
for(JButton b : btns)
btns.setText("whatever here");
To change text for a specific button:
btns[x].setText("whatever here"); //from array
btns.get(x).setText("whatever here"); //from list
Alternatively, if you do not keep a reference. You can get the list of buttons from the content pane:
Component[] components = myPanel.getComponents();
for(Component c : components)
if(c instanceof JButton)
((JButton)c).setText("whatever here");
I have a main frame : JFrame>contentFrame>ScrollPane>BigPanel>panel_1T
private JPanel contentPane;
private JPanel BigPanel;
private JPanel panel_1T;
In panel_1T, I have put a FOOD button WITH its actionListener:
JButton button_19 = new JButton("FOOD");
button_19.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
newFoodUI nf = new newFoodUI();//Open other class
nf.setVisible(true);
nf.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
});
panel_1T.setLayout(new GridLayout(0, 2, 0, 0));
panel_1T.add(button_19);
When user click FOOD button, new JFrame in newFoodUI class will be shown.:
JFrame>contentPane>panel>tabbedPane>panel_3>panel_5
In panel_5, I put a JTextField:
public static JTextField textField_3;
textField_3 = new JTextField();
panel_5.add(textField_3, "9, 4, fill, default");
textField_3.setColumns(10);
User will write some text into textField_3. Then user click SAVE button in panel_3, it will perform this:
JButton button_4 = new JButton("SAVE");
button_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setContentPane(contentPane);
panel_3.revalidate();
panel_3.repaint();
panel_3.updateUI();
panel_5.revalidate();
panel_5.repaint();
panel_5.updateUI();
contentPane.revalidate();
contentPane.repaint();
JOptionPane.showMessageDialog(null, "Saved !");
}
});
button_4.setBounds(873, 396, 75, 33);
contentPane.add(button_4);
}
The result is, when I click SAVE button and close the Frame in newFoodUI, I will reopen back by click the FOOD button to check whether the text I wrote has been saved or not. But its not saving the text I wrote.
You have to save the value from the textfeld textField_3.getText() and set this value manually to textfeld when showing textField_3.setText(value). So you have to keep your value in your project or store persistent somewhere.
There are a couple of things to fix here and I will not give you complete code but I will point out some errors. First let's consider your button_19 listener
public void actionPerformed(ActionEvent ae) {
newFoodUI nf = new newFoodUI();//Open other class
nf.setVisible(true);
nf.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
When this is performed, it creates a totally new object of newFoodUI and gives it no parameters. So how could this frame know about anything that happened before its creation if you give it nothing? Additionally, you explicitly say DISPOSE_ON_CLOSE, when you could use HIDE_ON_CLOSE if you wish to reuse it.
Then in your JButton button_4 = new JButton("SAVE"); listener you want to save the data in the text field, but your implementation does nothing to the text field. You should, for example, get the text from textField_3 and write it to a file or send back to the first JFrame.
Then there is the issue of using multiple JFrames in the first place.
I have two buttons and in the second one I want to use a variable made in the first button. So Netbeans is generating code of the button. ActionEvent generated by netbeans is
"private void buttonActionPerformed(java.awt.event.ActionEvent evt)"
and I cant change it. I tried to change button to public in button setting. I changed it to public but in code it is still private. I dont know what to do. Anyone know where the problem might be?
Thanks.
What you want to do is, there is a blank line above the private void buttonActionPerformed(ActionEvent evt) you create your variable in that line the example: int a; now the a will turn green. This is called a global variable
JFrame jtfMainFrame;
JButton jbnButton1, jbnButton2;
JTextField jtfInput;
JPanel jplPanel;
//Declaring the string variable setText
String setText;
public JButtonDemo2() {
jtfMainFrame = new JFrame("Which Button Demo");
jtfMainFrame.setSize(50, 50);
jbnButton1 = new JButton("Button 1");
jbnButton2 = new JButton("Button 2");
jtfInput = new JTextField(20);
jplPanel = new JPanel();
jbnButton1.setMnemonic(KeyEvent.VK_I); //Set ShortCut Keys
jbnButton2.setMnemonic(KeyEvent.VK_I);
jbnButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Setting the setText variable
setText = "Do whatever you want";
}
});
jbnButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Displaying the setText variable
jtfInput.setText(setText);
}
});
jplPanel.setLayout(new FlowLayout());
jplPanel.add(jtfInput);
jplPanel.add(jbnButton1);
jplPanel.add(jbnButton2);
jtfMainFrame.getContentPane().add(jplPanel, BorderLayout.CENTER);
jtfMainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtfMainFrame.pack();
jtfMainFrame.setVisible(true);
}
Simply declare it as a global means when the class definition starts at that time declare the variable which you want to use at the two buttons click and change the value of variable according to your use.
No need to change the ActionPerformed(). All you have to do is declare the variable as a global variable and then do whatever the task inside the button's ActionPerformed().
I have a various panels with various buttons. Some buttons should call a method initiating a search through an array list, other buttons should call methods that send information to different JTextArea boxes.
After adding an event listener for each button, how do I create specific actions depending on the button clicked in my actionPerformed method? Below is my code for various gui properties, as you can see there are 3 different JPanels, the buttons of each needing to perform different functions. I just need to know how to determine which button was clicked so I can link it to the appropriate method (already written in another class). Does this require an if statement? Can my other class access the buttons on the GUI if I make them public, or is there a more efficient way to do this.
JPanel foodOptions;
JButton[] button= new JButton[4]; //buttons to send selected object to info panel
static JComboBox[] box= new JComboBox[4];
JPanel search;
JLabel searchL ;
JTextField foodSearch;
JButton startSearch; //button to initialize search for typed food name
JTextArea searchInfo;
JPanel foodProfile;
JLabel foodLabel;
JTextArea foodInfo;
JButton addFood; //but to add food to consumed calories list
JPanel currentStatus;
JLabel foodsEaten;
JComboBox foodsToday;
JLabel calories;
JTextArea totalKCal;
JButton clearInfo; //button to clear food history
As per people's comments, you need to use listeners of some sort, here is a real basic example to get you started, however I would define your listeners elsewhere in most cases, rather than on the fly:
JButton startSearch = new JButton("startSearch");
JButton addFood = new JButton("addFood");
startSearch.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//DO SEARCH RELATED THINGS
}
});
addFood.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//DO FOOD ADD RELATED THINGS
}
});
Something like this:
JButton searchButton = new JButton("Start search");
searchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do some search here
}
});
JButton addFoodButton= new JButton("Add food");
addFoodButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// add your food
}
});
and so on. If you need to reuse an behaviour through multiple buttons, create a ActionListener instance instead of using anonymous classes and assign it multiple times to your buttons.
Well there any many ways to do that I guess. I suppose you can do the following:
public class Myclass implements ActionListener
{
private JButton b1,b2;
private MyClassWithMethods m = new MyClassWithMethods();
// now for example b1
b1 = new JButton("some action");
b1.setActionCommand("action1");
b1.addActionListener(this);
public void actionPerformed(ActionEvent e) {
if ("action1".equals(e.getActionCommand()))
{
m.callMethod1();
} else {
// handle other actions here
}
}
}
And you can do the same for more buttons and test which action triggered the event and then call the appropriate methods from you class.