Hot questions for Using JTextField in actionevent

Question:

I have a javax.swing.JTextField named SearchBox with an actionPerformed Event.

public void SearchBoxActionPerformed(java.awt.event.ActionEvent evt){
     //TODO
}

What I want to do is to call the above method from another method in a different class by passing the JTextField object as an argument.

import javax.swing.JTextField;

public class Program {

    public static synchronized void QuickSearchResults(JTextField textBox) {
        /*
         * I want to call ActionPerformed method of textBox if it has any.
         */
    }
}

Please note that calling the method name directly is not an option. If I pass 3 different JTextField objects, the relevant ActionPerformed methods should be called.

Is there a way to achieve this? I already tried using,

textBox.getActions();
textBox.getActionListeners();

but it didn't go well, and now I'm back in square one.

Thanks in advice!


Answer:

JTextField#postActionEvent will trigger the fields ActionListeners, which is what I assume you're trying to do

public class Program {

    public static synchronized void QuickSearchResults(JTextField textBox) {
        textBox.postActionEvent();
    }
}

Question:

I am trying to calculate sub-total in a separate textField from an event which involves user selecting number of rooms and number of days (based on check in and check out dates).

This textField (sub-total) will effectively multiply (no of days * no of rooms * room price) and will be updated when the user changes duration or number of rooms.

Please note my GUI is based on drag and drop.

private void checkDoubleActionPerformed(java.awt.event.ActionEvent evt) {                                            
 // User clicks "Check Availability" button after selecting number of Double Rooms required and duration of stay

   String value2 = spinner2.getValue().toString(); //Getting number of room using spinner2

    //.set a default current date to Check in. Can be changed by customer
    cid_chooser2.getJCalendar().setMinSelectableDate(new Date());
    cid_chooser2.setMinSelectableDate(new Date());

    Date d1 = null; //initial value of check in date
    Date d2 = null; // initial value of check out date

    try {
        d1 = cid_chooser2.getDate();
        d2 = cod_chooser2.getDate();

        long duration = d2.getTime() - d1.getTime(); //calculationg duration in days
        long days = TimeUnit.MILLISECONDS.toDays(duration);

        if (days > 0) {

            JOptionPane pane = new JOptionPane("You selected " + value2 + " Double Rooms for: " + days,JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION);
            JDialog dialog = pane.createDialog(null, "Customer Notification");
            dialog.setSize(new Dimension(400, 200));
            dialog.show();
        }
        else {JOptionPane.showMessageDialog(null, "Check out Date needs to be after Check in Date ");
        }
    }
    catch (NullPointerException ex1) {

        if (d1 == null && d2 == null) {

            JOptionPane.showMessageDialog(null, "Please enter missing check in AND check out dates.");
        }

        else if (d2 == null) {
            JOptionPane.showMessageDialog(null, "Please enter missing check out date."
                + "\nyour check out date should be at least a day after your check in date");
        }
        else if (d1 == null) {

            JOptionPane.showMessageDialog(null, "Please enter missing check in date."
                + "\nyour check in date should be at least today");
        }
    }                                          

}                         

   ////////////// separate JTextField to calculate sub-total////////////

  private void subTotal2ActionPerformed(java.awt.event.ActionEvent evt) {                                          
// sub-Total based on number of Double Rooms selected * duration (days) * unit price

}  

Answer:

I hope this sample program will show you how to do this. Here I'm using JDateChooser class which can be downloaded from: https://toedter.com/jcalendar/

If you are using some other date component, I'm sure that class would also have a similar API like addPropertyChangeListener() which you can use.

import com.toedter.calendar.JDateChooser;

import javax.swing.*;
import javax.swing.event.*;
import java.awt.GridLayout;
import java.awt.event.*;
import java.beans.*;
import java.util.Date;

public class CalculateSubTotal {

  private static JDateChooser checkin = new JDateChooser();
  private static JDateChooser checkout = new JDateChooser();
  private static JSpinner rooms = new JSpinner(new SpinnerNumberModel(1, 0, 10, 1));
  private static JTextField subTotal = new JTextField(20);
  private static JButton button = new JButton("Check availability");

  public static void main(String[] args) {

    checkin.getDateEditor().addPropertyChangeListener("date", new PropertyChangeListener() {
      @Override
      public void propertyChange(PropertyChangeEvent evt) {
        calculateSubTotal(checkin.getDate(), checkout.getDate(), (Integer) rooms.getValue(), 50);
      }
    });

    checkout.getDateEditor().addPropertyChangeListener("date", new PropertyChangeListener() {
      @Override
      public void propertyChange(PropertyChangeEvent evt) {
        calculateSubTotal(checkin.getDate(), checkout.getDate(), (Integer) rooms.getValue(), 50);
      }
    });

    rooms.addChangeListener(new ChangeListener() {
      @Override
      public void stateChanged(ChangeEvent e) {
        calculateSubTotal(checkin.getDate(), checkout.getDate(), (Integer) rooms.getValue(), 50);
      }
    });

    button.addActionListener(new ActionListener()
    {
      @Override
      public void actionPerformed(ActionEvent e) {
        calculateSubTotal(checkin.getDate(), checkout.getDate(), (Integer) rooms.getValue(), 50);
      }
    });

    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().setLayout(new GridLayout(6, 2));
    f.getContentPane().add(new JLabel("Price"));
    f.getContentPane().add(new JLabel("50"));
    f.getContentPane().add(new JLabel("Check in"));
    f.getContentPane().add(checkin);
    f.getContentPane().add(new JLabel("Check out"));
    f.getContentPane().add(checkout);
    f.getContentPane().add(new JLabel("Number of rooms"));
    f.getContentPane().add(rooms);
    f.getContentPane().add(new JLabel("Sub total"));
    f.getContentPane().add(subTotal);
    f.getContentPane().add(button);
    f.setBounds(300, 200, 400, 300);
    f.setVisible(true);
  }

  private static void calculateSubTotal(Date checkin, Date checkout, int rooms, int price) {
    if (checkin == null || checkout == null) {
      return;
    }
    int sub = getDays(checkin, checkout) * rooms * price;
    subTotal.setText(String.valueOf(sub));
  }

  private static int getDays(Date checkin, Date checkout) {
    return (int) ((checkout.getTime() - checkin.getTime()) / (1000 * 60 * 60 * 24));
  }
}

Question:

Question is: How do i add code to ensure that a table number (tableNumberJTextField) and waiter name (waiterNameJTextField) have been entered? If one or all fields are empty Use a JOptionPane to inform user that both fields must contain Information

At the moment i have:

private void calculateBillJButtonActionPerformed( 
      ActionEvent event )

{

    if(event.getSource() == tableNumberJTextField)   
     {

     }
     else
     {
         JOptionPane.showInputDialog("Information missing");
     }

   } // end method calculateBillJButtonActionPerformed

Would i need another IF...Else and a JOptionPane in there for WaiterName as well as tableNumberJTextField seen in the code above OR am i completely doing this wrong????

FULL QUESTION THAT I HAVE TO DO IS: calculateBillJButtonActionPerformed method (which immediately follows dessertJComboBoxItemStateChanged) and add code to ensure that a table number (tableNumberJTextField) and waiter name (waiterNameJTextField) have been entered. If one of these fields is empty, display a JOptionPane informing the user that both fields must contain information. Otherwise, call the calculateSubtotal method, which you implement in the next step, to calculate the subtotal of the bill. The calculateSubtotal method takes no arguments and returns a double containing the subtotal, which you should display in subtotalJTextField. Calculate and display the tax and the total of the bill in JTextFields taxJTextField and totalJTextField, respectively. The tax rate is specified in a constant TAX_RATE.


Answer:

Presumably, the actionPerformed you're showing is for a button. If so, just check for text in the fields:

   String tableNumber = tableNumberJTextField.getText().trim();
   String waiterName = waiterNameJTextField.getText().trim();

   if (tableNumber.length() == 0 || waiterName.length() == 0)
    {
       // show an error
    }
    else
    {
       // do a calculation
    }

Question:

I need to display text within a field I created in this program that is identified in the actionEvent, which is the RadioButton selection. I'm having a hard time getting the selection to display in the field. Please help?

  import javax.swing.*;
  import java.awt.*;
  import java.awt.event.*;

  public class JBasketball {

    public static void main(String args[]) {

      JFrame frame = new JFrame("JBasketball");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      JTextField field = new JTextField(16);

      JPanel panel = new JPanel(new FlowLayout());

      ButtonGroup group = new ButtonGroup();
        JRadioButton sixers = new JRadioButton("Philadelphia 76ers");
        JRadioButton raptors = new JRadioButton("Toronto Raptors");
        JRadioButton lakers = new JRadioButton("Los Angeles Lakers");
        JRadioButton sonics = new JRadioButton("Seattle Supersonics");
        JRadioButton bullets = new JRadioButton("Baltimore Bullets");

      ActionListener action = new ActionListener() {

        public void actionPerformed(ActionEvent actionEvent) {
          JRadioButton aButton = (JRadioButton) actionEvent.getSource();

           String team = aButton.getText();
  //This is where I need the field to display the team name
           field.setText(team);
        }
      };

      panel.add(sixers);
      group.add(sixers);
      panel.add(raptors);
      group.add(raptors);
      panel.add(lakers);
      group.add(lakers);
      panel.add(sonics);
      group.add(sonics);
      panel.add(bullets);
      group.add(bullets);
      panel.add(field);


      sixers.addActionListener(action);
      raptors.addActionListener(action);
      lakers.addActionListener(action);
      sonics.addActionListener(action);
      bullets.addActionListener(action);
      field.addActionListener(action);

      frame.add(panel);
      frame.setSize(500, 130);
      frame.setVisible(true);
      frame.setLocationRelativeTo(null);
    }
  }

Answer:

It works fine, once you get it to compile. You just need to declare the text field final

final JTextField field = new JTextField

The reason is that you are trying to access a local variable inside an anonymous class, and it needs to be declare final.


Other things you should note:

  • Run your Swing apps on the Event Dispatch Thread. See more at Initial Threads

  • I wouldn't do all the work in the main as you are. Create a constructor for the class and do the work there, or some init method. And with instantiate the constructor in the main or call the init method, which ever bests suits you.

Question:

I'm having a trouble storing a value by using an ActionListener with a JButton. I'm fairly new to Java and not 100% confident in class and subclass way of programming.

import java.ActionEvent;
import javaActionListener;
import javax.swing JButton;
import javax.swing JPanel;
import javax.swing.JTextField;

public class Trial extends JPanel implements Action Listener {

    private static final long serialVersionUID = 1L;

    public Trial() {
        setFrame();
    }

    public void setFrame(){

        JFrame frame = new JFrame("Trial");
        JPanel panel = new JPanel();
        JTextField field = new JTextField(10);
        JButton button = new JButton("Enter");
        button.addActionListener(this);

        panel.add(field);
        panel.add(button);

        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new Trial();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String s = field.getText();
        System.out.prinln("Button is pressed");
    }
}

field is undefined inside actionPerformed, why is this so? I played around with the ActionEvent, and it seems I can't pass in any variable outside of the actionPerformed function. So how do I go about doing this? Do I need to move setFrame() to its own class?


Answer:

The reason for your issue is down to the scope of the variable field.

In java the scope of a variable is set by the code block it is defined in. Your JTextField field, is declared within the setFrame method, this means the variable is only visible within the setFrame method.

If you want to make the field variable visible within the entire class so that you can access it in your actionPerformed method you can make it an instance variable.

public class Trial extends JPanel implements Action Listener {

    private static final long serialVersionUID = 1L;
    private JTextField field;    //Move your declaration to class level, making it an instance variable.

    public Trial() {
        setFrame();
    }

    public void setFrame(){

        JFrame frame = new JFrame("Trial");
        JPanel panel = new JPanel();
        field = new JTextField(10);    //Remove the declaration of the variable and just initialize it here.
        JButton button = new JButton("Enter");
        button.addActionListener(this);

        panel.add(field);
        panel.add(button);

        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new Trial();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String s = field.getText();   //Now you can access field within any method in the class.
        System.out.prinln("Button is pressed");
    }
}

Hopefully the above code explains it enough, any questions please comment and I'll elaborate.