Hot questions for Using JTextField in actionlistener

Top Java Programmings / JTextField / actionlistener

Question:

so this is the concept: Simply, there's a textbox with "Name" as the value, and I wanted that if I click anywhere IN the textbox, the value "Name" will disappear. This is what I've done in my code:

JTextField t1 = new JTextField("Name", 10);

t1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent cl){
                t1.setText(" ");
            }
        });

There's no syntax errors but when I run the program and clicked somewhere in the textbox, nothing happens and the value "Name" is still there

Any help would be greatly appreciated, thank you!


Answer:

You can try this:

t1.addFocusListener(new FocusListener() {

    @Override
    public void focusGained(FocusEvent e) {
        t1.setText(null); // Empty the text field when it receives focus
    }

});

Question:

Im having trouble using JButtons to increment/decrement an already set JTextField.

I know an actionlistener is necessary but I'm not sure how to set it up. I also have to set this up for multiple JButtons which further complicates this process.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class App1 extends JFrame implements ActionListener, MouseListener
{
    JPanel upper, lower, jp1, jp2, jp3;
    JButton jb1, jb2, jb3, jb4, jb5, jb6;
    JLabel jl1, jl2, jl3;
    JTextField jtf1, jtf2, jtf3;
    int count = 128;

    public static void main(String[] args) {
        App1 a1 = new App1();
    }

    public App1() {

        JFrame myFrame = new JFrame("Color Selector");
        myFrame.setLocationRelativeTo(null);
        myFrame.setSize(new Dimension(600,400));

        GridLayout layout = new GridLayout(2,1);
        myFrame.setLayout(layout);

        JPanel upper = new JPanel();
        upper.setBackground(Color.GRAY);

        JPanel lower = new JPanel(); add(lower);
        lower.setLayout(new BoxLayout(lower, BoxLayout.X_AXIS));
        lower.setBackground(Color.GRAY);
        JPanel jp1 = new JPanel(); lower.add(jp1);
        JPanel jp2 = new JPanel(); lower.add(jp2);
        JPanel jp3 = new JPanel(); lower.add(jp3);
        lower.addMouseListener(this);

        JLabel jl1 = new JLabel("Red"); jp1.add(jl1);
        JLabel jl2 = new JLabel("Green"); jp2.add(jl2);
        JLabel jl3 = new JLabel("Blue"); jp3.add(jl3);

        jp1.setBackground(Color.RED);
        jp2.setBackground(Color.GREEN);
        jp3.setBackground(Color.BLUE);

        JButton jb1 = new JButton("R-"); jp1.add(jb1);
        JTextField jtf1 = new JTextField(6);jp1.add(jtf1);
        jtf1.setText("128");
        JButton jb2 = new JButton("R+"); jp1.add(jb2);
        jb1.addActionListener(this);
        jb2.addActionListener(this);

        JButton jb3 = new JButton("G-"); jp2.add(jb3);
        JTextField jtf2 = new JTextField(6);jp2.add(jtf2);
        jtf2.setText("128");
        JButton jb4 = new JButton("G+"); jp2.add(jb4);
        jb3.addActionListener(this);
        jb4.addActionListener(this);

        JButton jb5 = new JButton("B-"); jp3.add(jb5);
        JTextField jtf3 = new JTextField(6);jp3.add(jtf3);
        jtf3.setText("128");
        JButton jb6 = new JButton("B+"); jp3.add(jb6);
        jb5.addActionListener(this);
        jb6.addActionListener(this);

        myFrame.add(upper);
        myFrame.add(lower);

        myFrame.setVisible(true);
    }

    private void start() {
        // TODO Auto-generated method stub
    }

    private static String setEditable(String string) {
        // TODO Auto-generated method stub
        return null;
    }

    private static String setText(String string) {
        // TODO Auto-generated method stub
        return null;
    }

    private static void add(JPanel lower) {
        // TODO Auto-generated method stub
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
    }

    private void rebuild() {
        // TODO Auto-generated method stub
    }
}   

I expect JButton to increment/decrement already set JTextField "128" by +1 or -1 with use of JButtons.


Answer:

In this case it would be simpler to have a seperate Action Listener for each button. For example: Instead of

jb1.addActionListener(this);
jb2.addActionListener(this);

Do

    jb1.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            jtf1.setText(String.valueOf(Integer.valueOf(jtf1.getText())-1));
        }
    });

    jb2.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            jtf1.setText(String.valueOf(Integer.valueOf(jtf1.getText())+1));
        }
    });

(So App1 does not need to implement ActionListener)

Note: using lambda expressions makes the above code look like:

jb1.addActionListener(e -> jtf1.setText(String.valueOf(Integer.valueOf(jtf1.getText())-1)));
jb2.addActionListener(e -> jtf1.setText(String.valueOf(Integer.valueOf(jtf1.getText())+1)));

Side note: You are declaring variables twice. For example you have a field JTextField jtf1 and later JTextField jtf1 = new JTextField(6);. The field remains null.

Question:

I have two JTextfields, I want the value/text of second Textfield to change based on any change in value/text made in first TextField

Here is what I am doing

    textField_15 = new JTextField("100");
    textField_15.setEditable(false);
    textField_15.setColumns(10);
    textField_15.setBounds(161, 253, 86, 20);
    panel_3.add(textField_15);

    textField_14 = new JTextField();
    textField_14.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            int az = Integer.parseInt(textField_14.getText());
            int aw = Integer.parseInt(textField_15.getText());
            int aq = aw - az;
            String ar = String.valueOf((aq));
            JOptionPane.showMessageDialog(null, az + " " +aw + " " + aq + " " + ar);
            textField_15.setText(ar);
        }
    });
    textField_14.setColumns(10);
    textField_14.setBounds(426, 186, 86, 20);
    panel_3.add(textField_14);

Answer:

I'm assuming that you don't understand that ActionListener will only be notified when the user presses the Enter key...

That would be the easiest solution, if, however, you want to monitor changes to a text component, you should use a DocumentListener

See How to Use Text Fields, How to Write an Action Listeners and Listening for Changes on a Document for more details

This, however, raises some issues. When do you assume the user has stopped typing?

There is a significant difference between 100 and 1 and 0 and 0, so what we need is someway to defer the event notification to some time in the future, where we can "assume" that the user has stopped typing (or at least long enough for us to grab a reasonable value)

public class DeferredDocumentChangedListener implements DocumentListener {

    private Timer timer;
    private List<ChangeListener> listeners;

    public DeferredDocumentChangedListener() {

        listeners = new ArrayList<>(25);
        timer = new Timer(250, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                fireStateChanged();
            }
        });
        timer.setRepeats(false);
    }

    public void addChangeListener(ChangeListener listener) {
        listeners.add(listener);
    }

    public void removeChangeListener(ChangeListener listener) {
        listeners.add(listener);
    }

    protected void fireStateChanged() {
        if (!listeners.isEmpty()) {
            ChangeEvent evt = new ChangeEvent(this);
            for (ChangeListener listener : listeners) {
                listener.stateChanged(evt);
            }
        }
    }

    @Override
    public void insertUpdate(DocumentEvent e) {
        timer.restart();
    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        timer.restart();
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        timer.restart();
    }

}

Okay, so, this is a little trick. This is a simple observable DocumentListener, which provides event notification at some point in the future that the document has changed. In your case, you don't really care about the change, just that it has.

This sets up a non-repeating Swing Timer with a short delay (250 milliseconds in the example) which if it's not reset for that period of time, will notify any registered ChangeListeners. If, however, the Document is modified within that time period, the Timer is reset.

You may want to play around with the "time out" value ;)

Which you could then use something like...

JTextField number = new JTextField(5);
JTextField sum = new JTextField("0", 5);

setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;

add(number, gbc);
add(sum, gbc);

DeferredDocumentChangedListener listener = new DeferredDocumentChangedListener();
listener.addChangeListener(new ChangeListener() {

    @Override
    public void stateChanged(ChangeEvent e) {
        int num1 = Integer.parseInt(number.getText());
        int num2 = Integer.parseInt(sum.getText());
        int result = num1 + num2;
        sum.setText(Integer.toString(result));
        number.selectAll();
    }
});

number.getDocument().addDocumentListener(listener);

This, obviously doesn't provide any validation, so it could throw an exception if the text is not a number, but I'll leave that for you to figure out

You may also want to have a look at How to Use Spinners and How to Use Formatted Text Fields which provide post validation process which can help validate the user input.

You could also use a DocumentFilter to further restrict what the user can enter, see Implementing a Document Filter and DocumentFilter Examples for more details

Question:

I have made a window using JFrame and on my JPanel I have added 3 components: 2 JTextFields ("field1" and "field2") and inbetween them a JButton ("switch"). My goal is to switch the value of field1 to field2 and vice versa when the JButton is clicked. I thought this ActionListener which I have added to my JButton would achieve my goal:

    public void actionPerformed(ActionEvent e) {  
        field2.setText(field1.getText());  

        field1.setText(field2.getText());  
    }  

However, it changes the value of field2 into the value of field1 but not the other way around.

Any help would be appreciated.


Answer:

You need a temporarily variable todo. If you do not use on, you set the text from field1 to field2 and then you get the wrong value.

public void actionPerformed(ActionEvent e) {  
        String tmp= field2.getText()  
        field2.setText(field1.getText());  

        field1.setText(tmp);  
    }  

Question:

this is the code of the Gui Design class and below is the Class that provides functionality to the program. Im trying to get user input from the textfields so i can remove the text using the clearAll method and also save user input using the saveit method.I tried using nameEntry.setText(""); in the clearAll method but it wont work can someone help me please!

//Import Statements
import javax.swing.*;
import java.awt.*;
import javax.swing.JOptionPane;
import java.awt.event.*;


//Class Name
public class Customer extends JFrame {
    Function fun = new Function();

    public static void main(String[]args){
        Customer.setLookAndFeel();
        Customer cust = new Customer();
    }


    public Customer(){
        super("Resident Details");
        setSize(500,500);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        FlowLayout two = new FlowLayout(FlowLayout.LEFT);
        setLayout(two);


        JPanel row1 = new JPanel();
        JLabel name = new JLabel("First Name",JLabel.LEFT);
        JTextField nameEntry = new JTextField("",20);
        row1.add(name);
        row1.add(nameEntry);
        add(row1);

        JPanel row2 = new JPanel();
        JLabel surname = new JLabel("Surname    ",JLabel.LEFT);
        JTextField surnameEntry = new JTextField("",20);
        row2.add(surname);
        row2.add(surnameEntry);
        add(row2);

        JPanel row3 = new JPanel();
        JLabel contact1 = new JLabel("Contact Details : Email                 ",JLabel.LEFT);
        JTextField contact1Entry = new JTextField("",10);
        FlowLayout newflow = new FlowLayout(FlowLayout.LEFT,10,30);
        setLayout(newflow);
        row3.add(contact1);
        row3.add(contact1Entry);
        add(row3);

        JPanel row4 = new JPanel();
        JLabel contact2 = new JLabel("Contact Details : Phone Number",JLabel.LEFT);
        JTextField contact2Entry = new JTextField("",10);
        row4.add(contact2);
        row4.add(contact2Entry);
        add(row4);

        JPanel row5 = new JPanel();
        JLabel time = new JLabel("Duration Of Stay                             ",JLabel.LEFT);
        JTextField timeEntry = new JTextField("",10);
        row5.add(time);
        row5.add(timeEntry);
        add(row5);


        JPanel row6 = new JPanel();
        JComboBox<String> type = new JComboBox<String>();
        type.addItem("Type Of Room");
        type.addItem("Single Room");
        type.addItem("Double Room");
        type.addItem("VIP Room");
        row6.add(type);
        add(row6);

        JPanel row7 = new JPanel();
        FlowLayout amt = new FlowLayout(FlowLayout.LEFT,100,10);
        setLayout(amt);
        JLabel amount = new JLabel("Amount Per Day                               ");
        JTextField AmountField = new JTextField("\u20ac ",10);
        row7.add(amount);
        row7.add(AmountField);
        add(row7);

        JPanel row8 = new JPanel();
        FlowLayout prc = new FlowLayout(FlowLayout.LEFT,100,10);
        setLayout(prc);
        JLabel price = new JLabel("Total Price                                         ");
        JTextField priceField = new JTextField("\u20ac ",10);
        row8.add(price);
        row8.add(priceField);
        add(row8);

        JPanel row9 = new JPanel();
        JButton clear = new JButton("Clear");
        row9.add(clear);
        add(row9);

        JPanel row10 = new JPanel();
        JButton save = new JButton("Save");
        save.addActionListener(fun);
        row10.add(save);
        add(row10);

        //Adding ActionListners
        nameEntry.addActionListener(fun);
        clear.addActionListener(fun);
        save.addActionListener(fun);

        setVisible(true);
    }

    private static void setLookAndFeel() {
            try {
                UIManager.setLookAndFeel(
                    "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
                );
            } catch (Exception exc) {
            // ignore error
                }
    }

}

//Import Statements
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import javax.swing.JOptionPane;
import java.awt.event.*;


//Class Name
public class Function implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
        if(command.equals("Add Customer")) {
            Login();
        }
        else if(command.equals("Register")){
            Registration();
        }
        else if(command.equals("Exit")){
            System.exit(0);
        }       
        else if(command.equals("Clear")){
            ClearAllFields();
        }
        else if(command.equals("Save")){
            SaveIt();
        }
    }

    public static void Login(){
        Customer cust = new Customer();
    }

    public static void Registration(){
        //Do Nothing

    }
    //This clears all the text from the JTextFields
    public static void ClearAllFields(){

    }

    //This will save Info on to another Class
    public static void SaveIt(){


    }


}

Answer:

Alternatively, you can make nameEntry known to the Function class by defining it before calling the constructor for Function and then passing it into the constructor, like:

JTextField nameEntry = new JTextField("",20);

Function fun = new Function(nameEntry);

Then, in Function, add nameEntry as a member variable of Function and make a constructor for Function which accepts nameEntry, (right after the "public class Function..." line), like:

JTextField nameEntry;

public Function(JTextField nameEntry) {
    this.nameEntry = nameEntry;
}

Now, the following will compile:

public void ClearAllFields(){
    nameEntry.setText("");
}

And, the Clear button will clear the name field.

Question:

I have a keypad made up of jbuttons and a jtextfield that has an action listener. When I press the button the number shows in the textfield but the next number overwrites it. Could anyone tell me how to append the text to the length 13 numbers and when it get's there to carriage return.

If I use the keyboard to enter numbers I can enter a String of numbers but not from the buttons.

I am using:

    JButton buttonNo2 = new JButton("2");
    buttonNo2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            textfield.setText("2");
        }

buttonNo1.setBounds(11, 18, 50, 50);
    keyboardPanel.add(buttonNo2);
    buttonNo1.setForeground(Color.BLUE);
    buttonNo1.setFont(new Font("Perpetua", Font.BOLD, 20));

Answer:

Try using something like

textfield.setText(textfield.getText() + "2");

instead of textfield.setText("2");

setText does just that, sets the text of the text field to the value you specified.

Also buttonNo1.setBounds(11, 18, 50, 50); looks like you're trying to do without a layout manager. Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

You could also make it much simpler for yourself, and use the Action API instead, which would save you a not lot of repeated typing...

public class NumberAction extends AbstractAction {

    private JTextField field;
    private int number;

    public NumberAction(JTextField field, int number) {
        this.field = field;
        this.number = number;
        putValue(NAME, Integer.toString(number));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Document doc = field.getDocument();
        try {
            doc.insertString(doc.getLength(), Integer.toString(number), null);
        } catch (BadLocationException ex) {
            ex.printStackTrace();
        }
    }

}

Then you would just need to add each button as required...

add(new JButton(new NumberAction(textfield, 1)));
add(new JButton(new NumberAction(textfield, 2)));
add(new JButton(new NumberAction(textfield, 3)));

See How to Use Actions for more details

Question:

I'm trying to run my JButton ActionListener in a different class than my GUI. So I get the button working, but I can't "access" the TextFields, they are just "empty" when I want to access them.

So that's my GUI Class:

public class CaeserGUI extends JFrame {

    JPanel contentPane;
    private JTextField txt_input;
    private JTextField number_input;
    private JButton btn_translate;
    private JTextArea txt_output;
    private JTextField txt_input2;
    private JTextField number_input2;
    private JTextArea txt_output2;

    /**
     * Launch the application.
     * Author: Paul Viehmann
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    CaeserGUI frame = new CaeserGUI();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public CaeserGUI() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        txt_input = new JTextField();
        txt_input.setBounds(10, 38, 363, 20);
        contentPane.add(txt_input);
        txt_input.setColumns(10);

        number_input = new JTextField();
        number_input.setBounds(383, 38, 41, 20);
        contentPane.add(number_input);
        number_input.setColumns(10);

        JTextPane txtpnZubersetzenderSatz = new JTextPane();
        txtpnZubersetzenderSatz.setText("Zu \u00FCbersetzender Satz:");
        txtpnZubersetzenderSatz.setBounds(10, 11, 126, 20);
        contentPane.add(txtpnZubersetzenderSatz);

        JTextPane txtpnVerschiebung = new JTextPane();
        txtpnVerschiebung.setText("Verschiebung:");
        txtpnVerschiebung.setBounds(349, 11, 75, 20);
        contentPane.add(txtpnVerschiebung);

        txt_output = new JTextArea();
        txt_output.setBounds(10, 69, 414, 40);
        contentPane.add(txt_output);

        JTextPane txtpnZuDechiffrierenderSatz = new JTextPane();
        txtpnZuDechiffrierenderSatz.setText("Zu dechiffrierender Satz:");
        txtpnZuDechiffrierenderSatz.setBounds(10, 120, 126, 20);
        contentPane.add(txtpnZuDechiffrierenderSatz);

        txt_input2 = new JTextField();
        txt_input2.setColumns(10);
        txt_input2.setBounds(10, 147, 363, 20);
        contentPane.add(txt_input2);

        number_input2 = new JTextField();
        number_input2.setColumns(10);
        number_input2.setBounds(383, 147, 41, 20);
        contentPane.add(number_input2);

        JTextPane textPane_1 = new JTextPane();
        textPane_1.setText("Verschiebung:");
        textPane_1.setBounds(349, 120, 75, 20);
        contentPane.add(textPane_1);

        txt_output2 = new JTextArea();
        txt_output2.setBounds(10, 176, 414, 40);
        contentPane.add(txt_output2);

        ActionListener actionListener = new ButtonListener(number_input, number_input2, btn_translate, txt_output, txt_input, txt_input2, txt_output2);

        btn_translate = new JButton("\u00DCbersetzen");
        btn_translate.addActionListener(actionListener);
        btn_translate.setBounds(10, 227, 414, 23);
        contentPane.add(btn_translate);
    }
}

And that's my Listener class:

    public class ButtonListener implements ActionListener{

    private JTextField txt_input;
    private JTextField number_input;
    private JButton btn_translate;
    private JTextArea txt_output;
    private JTextField txt_input2;
    private JTextField number_input2;
    private JTextArea txt_output2;

    public ButtonListener(JTextField txt_input, JTextField number_input,
                            JButton btn_translate, JTextArea txt_output, 
                            JTextField txt_input2, JTextField number_input2, 
                            JTextArea txt_output2){

        this.txt_input = txt_input;
        this.number_input = number_input;
        this.btn_translate = btn_translate;
        this.txt_output = txt_output;
        this.txt_input2 = txt_input2;
        this.number_input2 = number_input2;
        this.txt_output2 = txt_output2;
    }

    public void actionPerformed(ActionEvent e){
        if(txt_input.getText().equals("")){
            System.exit(0);
        }else{
        }
    }
}

When I press the button, my program exit even when I write something in the textField.

I read a lot of other posts, but couldn't get it to work.

I appreciate every answer.


Answer:

You seem to be passing the parameters in the incorrect order (as far as I can tell, based on your naming conventions)

+---------------------------+--------------------------+
| ActionListener Parameters | The Order You're Passing |
+---------------------------+--------------------------+
| txt_input                 | number_input             |
| number_input              | number_input2            |
| btn_translate             | btn_translate            |
| txt_output                | txt_output               |
| txt_input2                | txt_input                |
| number_input2             | txt_input2               |
| txt_output2               | txt_output2              |
+---------------------------+--------------------------+

This means, when you inspect the value of txt_input in your ActionListener, you're actually looking at the number_input value ... this allow screams issues to me

My "general" recommendation would be to create an interface which provide getters and setters, with better names than "text" and "text2", so you can better differentiate their meaning. I'd have CaeserGUI implement this interface and then pass it to the ActionListener, which took a single reference to an instance of said interface

Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

If you think I'm be over reactive, this is what happens when I run your code on my PC

See how the "caret" in the second field is broken?

I would recommend using JLabels to provide prompts to the fields instead of setting their text, because that's just confusing. See How to Use Labels for more details

Components like JTextPane really benefit from been wrapped in a JScrollPane, this will allow the user to see the text when it expands beyond the visual boundaries of the component. See How to Use Scroll Panes for more details

Question:

I am making a program using JButtons and JTextFields. The ActionListeners work for JButtons, but not for JTextFields.

    public class Gui extends JFrame {

private JButton Subject[] = new JButton[8];
private String SubjNames[] = {"Length", "Mass", "Currency", "Temperature", "Time", "Speed", "Data", "Cooking"};
private JButton Length1[] = new JButton[8];
private JButton Length2[] = new JButton[8];
private String LengNames[] = {"inches", "feet", "yards", "miles", "millimeters", "centimeters", "meters", "kilometers"};
private JTextField convertedFrom;
private JTextField amountFrom;
private JTextField convertedTo;
private JTextField amountTo;
private String from;
private String CTo;
private String ATo;
private int SubjectLocX = 40;
private int SubjectLocY = 50;
private int Length1LocX = 40;
private int Length1LocY = 150;
private int Length2LocX = 330;
private int Length2LocY = 150;
private int t = 0;

public Gui (){

    super("Converter");
    setLayout(null);

    System.out.println("yes");

    for (int i = 0; i<8; i++) {
    Subject[i] = new JButton(SubjNames[i]);
    Subject[i].setLocation(SubjectLocX,SubjectLocY);
    Subject[i].setSize(200,50);
    add(Subject[i]);
    if (i < 3) {
        SubjectLocX = 40;
        SubjectLocY += 100;
    } else if (i == 3) {
        SubjectLocX = 330;
        SubjectLocY = 50;
    } else if (i > 3) {
        SubjectLocY += 100;
        }
    }

    HandlerClass handler = new HandlerClass();

    for (int i = 0; i<8; i++) {
    Subject[i].addActionListener(handler);
    }


    for (int i = 0; i<8; i++) {
    Length1[i] = new JButton(LengNames[i]);
    Length2[i] = new JButton(LengNames[i]);
    }
    convertedFrom = new JTextField(from, 20);
    convertedTo = new JTextField(CTo, 20);
    amountFrom = new JTextField("amount", 20);
    amountFrom.addActionListener(handler);
    amountTo = new JTextField(ATo, 20);

    for (int i = 0; i<8; i++) {
        Length1[i].addActionListener(handler);
        Length2[i].addActionListener(handler);
        }

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(600,500);
    setLocation(400,200);
    setVisible(true);
}

public void Step2() {

    for (int i = 0; i<8; i++) {
        remove(Subject[i]);
    }
    for (int i = 0; i<8; i++) {
        remove(Length1[i]);
        remove(Length2[i]);
    }
    remove(convertedFrom);
    remove(convertedTo);
    remove(amountFrom);
    remove(amountTo);

    HandlerClass handler = new HandlerClass();

    convertedFrom = new JTextField(from, 20);
    convertedFrom.setEditable(false);
    convertedFrom.setLocation(40,50);
    convertedFrom.setSize(200,30);
    add(convertedFrom);

    convertedTo = new JTextField(CTo, 20);
    convertedTo.setEditable(false);
    convertedTo.setLocation(330,50);
    convertedTo.setSize(200,30);
    add(convertedTo);

    amountFrom = new JTextField("amount", 20);
    amountFrom.setLocation(40,100);
    amountFrom.setSize(200,30);
    add(amountFrom);

    amountTo = new JTextField(ATo, 20);
    amountTo.setEditable(false);
    amountTo.setLocation(330,100);
    amountTo.setSize(200,30);
    add(amountTo);

    Length1LocX = 40;
    Length1LocY = 150;
    Length2LocX = 330;
    Length2LocY = 150;

    for (int i = 0; i<8; i++) {
        Length1[i].setLocation(Length1LocX, Length1LocY);
        Length1[i].setSize(90, 50);
        add(Length1[i]);
        if (i < 3) {
            Length1LocX = 40;
            Length1LocY += 100;
        } else if (i == 3) {
            Length1LocX = 150;
            Length1LocY = 150;
        } else if (i > 3) {
            Length1LocY += 100;
            }
        Length2[i].setLocation(Length2LocX, Length2LocY);
        Length2[i].setSize(90, 50);
        add(Length2[i]);
        if (i < 3) {
            Length2LocX = 330;
            Length2LocY += 100;
        } else if (i == 3) {
            Length2LocX = 440;
            Length2LocY = 150;
        } else if (i > 3) {
            Length2LocY += 100;
            }
    } 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(600,600);
    setLocation(400,200);
    setVisible(true);
}
private class HandlerClass implements ActionListener {
    public void actionPerformed(ActionEvent event) {
        System.out.println("bruhhh");
        if (event.getSource() == amountFrom) {
            System.out.println("works");
        }
        for (int i = 0; i<8; i++) {
            if (event.getSource() == Length1[i]) {
                from = event.getActionCommand();
            }
            if (event.getSource() == Length2[i]) {
                CTo = event.getActionCommand();
            }
        }

        Step2();
    }
}
}

In the middle of my Gui constructor, the "amountFrom" TextField is created, and then I add an actionListener. Then, at the bottom inside of the ActionHandler class I Look for it's event. However, when I Run the program (click on 'Length') and then change the amount From the text Field and press enter, I do not get a console print (It is suppose to print "works" to the console when the textField action occurs). All of the other Jbutton actionlisteners work but this textfield actionListener won't work.


Answer:

In your constructor you add the ActionListener to your JTextField.

amountFrom = new JTextField("amount", 20);
amountFrom.addActionListener(handler);

But in your method Step2() you create a new instance of a JTextField and don't add a listener to it.

amountFrom = new JTextField("amount", 20);
amountFrom.setLocation(40,100);
amountFrom.setSize(200,30);
add(amountFrom);

Note: Please have a look at Layout Managers and consider using them. https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

Question:

I am creating a simple form for a class and I want the user to be able to press enter after filling out one JTextField. It moves on to the next available JTextField (not all of them are editable at a given time), similar to using tab.

When it gets to the last editable JTextField it should submit the form. Is that possible or is tab and the usual enter function (as a submit my only option)?

I'll post the code if necessary, but if you can answer the question without it, that'd be great too.


Answer:

Like Durandal mentioned, there are multiple ways to go about it.

You could use JTextField's addActionListener method, addAction method, addKeyListener method, etc... They're all fairly similar - you're telling the text field to do something when something happens. (Although exactly how you do it differs by method)

Regardless, each time the action will need to know which text field is next in line. Then you can call JTextField#requestFocus() to transfer input focus to it.

You can also do this with setFocusTraversalKeys and setNextFocusableComponent

Question:

I am creating a program were the user enters their grade of all their assignment and the weight of each individual assignment and the program calculates the aggregate grade.

Nearly completed the program with loads of help from here/internet but I have no idea how to do this last section.

So when user clicks enter the program will aggregate all marks taking into account their specific weight and output an average. For example:

The equation for something like this is weight/100*mark. (Adding them all together). So... (40/100)*60 + (40/100)*80... etc

So how can I do this with my program? I need to implement some type of for loop because the number of assignments changes all the time.

I have already implemented an actionlistener on the Enter button were the Mark/Weight/Assignment counter gets passed on to the next class.

However the actionlistener only records the last mark/weight. so 50 and 20 in the example above. This is another problem I'm facing.

So basically I ask for a way to get inputs from all JTextField and analyse them to create one output which aggregates all the scores. (Considering their weight)

Code:

public class test{

public JButton button;

private static final Insets normalInsets = new Insets(10,10,0,10);
private static final Insets finalInsets = new Insets(10,10,10,10);

private static JPanel createMainPanel(){
    GridBagConstraints gbc = new GridBagConstraints();

    //Adding the JPanels. Panel for instructions
    JPanel panel = new JPanel();
    panel.setLayout(new GridBagLayout());

    int gridy = 1;

    //JLabel for the Instructions
    JTextArea instructionTextArea = new JTextArea(5, 30);
    instructionTextArea.setEditable(false);
    instructionTextArea.setLineWrap(true);
    instructionTextArea.setWrapStyleWord(true);

    JScrollPane instructionScrollPane = new JScrollPane(instructionTextArea);
    addComponent(panel, instructionScrollPane, 0, gridy++, 3, 1, finalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

    //JLabels for Assignment
    JLabel label1 = new JLabel("Assignment");
    label1.setHorizontalAlignment(JLabel.CENTER);
    addComponent(panel, label1, 0, gridy, 1, 1, finalInsets,GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL);

    //JLabel for Mark
    JLabel label2 = new JLabel("Mark");
    label2.setHorizontalAlignment(JLabel.CENTER);
    addComponent(panel, label2, 1, gridy, 1, 1, finalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

    //JLabel for Weight.
    JLabel label3 = new JLabel("Weight");
    label3.setHorizontalAlignment(JLabel.CENTER);
    addComponent(panel, label3, 2, gridy++, 1, 1, finalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

    //JLabel Number for the number list of assignments at the side.
    gbc.gridy = 3;

    for(int i = 1; i<=3; i++){
        String kok = String.valueOf(i);
    JLabel number = new JLabel(kok);
    number.setHorizontalAlignment(JLabel.CENTER);
    addComponent(panel, number, 0, gbc.gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
    }
    gbc.gridy =3;

    //JTextfield for Mark
    for(int i=0; i<3; i++){
    JTextField mark = new JTextField(20);
    mark.setHorizontalAlignment(JLabel.CENTER);
    addComponent(panel, mark, 1, gbc.gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER,GridBagConstraints.NONE);
    }
    gbc.gridy = 3;

    //JTextfield for Weight       
    for(int i=0; i<3; i++){    
    JTextField weight = new JTextField(20);
    weight.setHorizontalAlignment(JLabel.CENTER);   
    addComponent(panel, weight, 2, gbc.gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER,GridBagConstraints.NONE);
    }

    JButton button = new JButton("Enter");
    button.setHorizontalAlignment(SwingConstants.CENTER);
    addComponent(panel, button, 3, gbc.gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER,GridBagConstraints.CENTER);

return panel;
}

private static void addComponent(Container container, Component component, int gridx, int gridy, int gridwidth, int gridheight, Insets insets, int anchor, int fill ){
    GridBagConstraints grid = new GridBagConstraints(gridx, gridy, gridwidth, gridheight, 1.0D,1.0D,anchor,fill,insets,0,0);
    container.add(component,grid);
}


    public static void main(String[] args) {    
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(createMainPanel());
    frame.pack();
    frame.setVisible(true);
    new test();
}

The next class that has the mark/weight info.

public class test1 implements ActionListener { 

 private final JTextField mark;
 private final JTextField weight;



public test1(JTextField mark, JTextField weight) {
    this.mark = mark;
    this.weight = weight;

}


@Override
public void actionPerformed(ActionEvent e) {

String markstring = mark.getText();
String weightstring = weight.getText();

double markdouble = Double.parseDouble(markstring);
double weightdouble = Double.parseDouble(weightstring);  

}

Answer:

  • You just need to save your JTextFields in a vector, so you can access them later.
  • You don't need the second class.
  • The listener for your button was also created.

    import java.awt.Component;
    import java.awt.Container;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingConstants;
    
    public class Test {
        public JButton button;
    
        private static final Insets normalInsets = new Insets(10,10,0,10);
        private static final Insets finalInsets = new Insets(10,10,10,10);
    
        public final static int NUM_OF_FIELDS = 3;
    
        private static JTextField[] markTextFields = new JTextField[NUM_OF_FIELDS];
        private static JTextField[] weightTextFields = new JTextField[NUM_OF_FIELDS];
    
        private static JPanel createMainPanel() {
            GridBagConstraints gbc = new GridBagConstraints();
    
            //Adding the JPanels. Panel for instructions
            JPanel panel = new JPanel();
            panel.setLayout(new GridBagLayout());
    
            int gridy = 1;
    
            //JLabel for the Instructions
            JTextArea instructionTextArea = new JTextArea(5, 30);
            instructionTextArea.setEditable(false);
            instructionTextArea.setLineWrap(true);
            instructionTextArea.setWrapStyleWord(true);
    
            JScrollPane instructionScrollPane = new JScrollPane(instructionTextArea);
            addComponent(panel, instructionScrollPane, 0, gridy++, 3, 1, finalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
    
            //JLabels for Assignment
            JLabel label1 = new JLabel("Assignment");
            label1.setHorizontalAlignment(JLabel.CENTER);
            addComponent(panel, label1, 0, gridy, 1, 1, finalInsets,GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL);
    
            //JLabel for Mark
            JLabel label2 = new JLabel("Mark");
            label2.setHorizontalAlignment(JLabel.CENTER);
            addComponent(panel, label2, 1, gridy, 1, 1, finalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
    
            //JLabel for Weight.
            JLabel label3 = new JLabel("Weight");
            label3.setHorizontalAlignment(JLabel.CENTER);
            addComponent(panel, label3, 2, gridy++, 1, 1, finalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
    
            //JLabel Number for the number list of assignments at the side.
            gbc.gridy = 3;
    
            for (int i = 1; i <= 3; i++) {
                String kok = String.valueOf(i);
                JLabel number = new JLabel(kok);
                number.setHorizontalAlignment(JLabel.CENTER);
                addComponent(panel, number, 0, gbc.gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
            }
            gbc.gridy = 3;
    
            //JTextfield for Mark
            for (int i = 0; i < NUM_OF_FIELDS; i++) {
                JTextField mark = new JTextField(20);
                markTextFields[i] = mark;
                mark.setHorizontalAlignment(JLabel.CENTER);
                addComponent(panel, mark, 1, gbc.gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER, GridBagConstraints.NONE);
            }
            gbc.gridy = 3;
    
            //JTextfield for Weight       
            for (int i = 0; i < NUM_OF_FIELDS; i++) {    
                JTextField weight = new JTextField(20);
                weightTextFields[i] = weight;
                weight.setHorizontalAlignment(JLabel.CENTER);   
                addComponent(panel, weight, 2, gbc.gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER,GridBagConstraints.NONE);
            }
    
            JButton button = new JButton("Enter");
            button.setHorizontalAlignment(SwingConstants.CENTER);
            addComponent(panel, button, 3, gbc.gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER,GridBagConstraints.CENTER);
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    double finalScore = 0;
                    for (int i = 0; i < NUM_OF_FIELDS; i++) {
                        double weight = Double.parseDouble(weightTextFields[i].getText());
                        double mark = Double.parseDouble(markTextFields[i].getText());
                        finalScore += weight / 100 * mark;
                    }
                    JOptionPane.showMessageDialog(null, "Final score: " + finalScore, "Final Score", JOptionPane.OK_OPTION);
                }
            });
            return panel;
        }
    
        private static void addComponent(Container container, Component component, int gridx, int gridy, int gridwidth, int gridheight, Insets insets, int anchor, int fill) {
            GridBagConstraints grid = new GridBagConstraints(gridx, gridy, gridwidth, gridheight, 1.0D, 1.0D, anchor, fill, insets, 0, 0);
            container.add(component, grid);
        }
    
        public static void main(String[] args) {    
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(createMainPanel());
            frame.pack();
            frame.setVisible(true);
            new Test();
        }
    }
    

Question:

I am trying to create example for GUI its take the name from user in JTextFiled and appear message for user with their name that was entered in JtextField, now I wanna make method check if the user enter on the button without enter anything, I trying to use this method in ActionListener but I see error in editor, while when I use it outside the ActionListener I see it's works! , please see the attachment picture

    public class Example01 extends JFrame {

    public JTextField text;
    public Example01() {
        setTitle("Example 01");
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50));
        JLabel label = new JLabel("Enter Your Name : ");
        text = new JTextField();
        text.setSize(30, 10);
        JButton btn1 = new JButton("Enter");

        btn1.addActionListener(new ActionListener() {

        if (text.getText().equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Please enter anything");
        }

            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(rootPane, "Hello : " + text.getText());
            }
        });
        panel.add(label);
        panel.add(Box.createRigidArea(new Dimension(0, 20)));
        panel.add(text);
        panel.add(Box.createRigidArea(new Dimension(0, 20)));
        panel.add(btn1);

        add(panel);
        setVisible(true);
        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

}

error message

Edit the problem is because I put code outside of an executable context "a method"


Answer:

Take...

if (text.getText().equals("")) {
    JOptionPane.showMessageDialog(rootPane, "Please enter anything");
}

and put it inside you actionPerformed method...

btn1.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        if (text.getText().equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Please enter anything");
        }
        JOptionPane.showMessageDialog(rootPane, "Hello : " + text.getText());
    }
});