Search code examples
javaswinguser-interfaceactionlistenerjtextfield

How to bind action with any gui interface in java


I am new to java.

Can someone tell me how to add ActionListener with my code?

Do I need to make a different function for it? I want to retrieve value from textfield which is entered by user. I am getting error.

Please explain me the background logic behind when to make function of methods that already exists in java or can we use them directly? My code is:

Also tell me how by pressing ENTER I can get value attached with text field in string?

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.*;
import javax.swing.JList;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Clientgui
{
    public static void main(String[] args)
    {
        JFrame guiFrame=new JFrame();
        guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        guiFrame.setTitle("Client GUI");
        guiFrame.setSize(30,30);
        guiFrame.setLocationRelativeTo(null);

        final JPanel comboPanel = new JPanel();
        JLabel Msg = new JLabel("Type Message");
        JTextField textbox=new JTextField(10);
        comboPanel.add(Msg);
        comboPanel.add(textbox);
        textbox.addActionListener(this);
        String text = textbox.getText();
        //textArea.append(text + newline);
        //textbox.selectAll();
        textbox.setText("Enter message here");

        //final JPanel comboPanel1 = new JPanel();
        //JLabel listLb2 = new JLabel("Connect");
        //comboPanel.add(listLb2 );
        JButton connect=new JButton("Connect");
        guiFrame.add(comboPanel,BorderLayout.NORTH);
        guiFrame.add(connect,BorderLayout.SOUTH);
        guiFrame.setVisible(true);
    }
}

Solution

  • As mentioned by Elliott Frisch You can add the Action to the instance of something that implements ActionListener which you can achieve in two way

        textbox.addActionListener(new ActionListener() {            
            public void actionPerformed(ActionEvent e) {
                //Write your action here.
            }
        });
    

    OR

        public class Clientgui implements ActionListener{
        // content of class goes here 
        textbox.addActionListener(this);
        // content of class goes here 
        }
    

    In order to bind the enter key with your text box you should implements KeyListener

    textbo.addKeyListener(new KeyAdapter()
    {
      public void keyPressed(KeyEvent e)
      {
        if (e.getKeyCode() == KeyEvent.VK_ENTER)
        {
          System.out.println("ENTER key pressed");
        }
      }
    });