如何将动作与 Java 中的任何 gui 接口绑定



我是Java的新手。

有人可以告诉我如何在我的代码中添加ActionListener吗?

我需要为它制作不同的功能吗?我想从用户输入的文本字段中检索值。我收到错误。

请解释一下何时对 java 中已经存在的方法进行功能背后的背景逻辑,或者我们可以直接使用它们吗?我的代码是:

还告诉我如何通过按 ENTER 获得字符串中带有文本字段的值?

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);
    }
}
你需要

一个实现ActionListener的东西的实例,你在这里得到一个编译错误 -

textbox.addActionListener(this); // <-- no instance "this".
                                 // You may have new Clientgui(), but 
                                 // Clientgui does not implement ActionListener.

Elliott Frisch所述,您可以将Action添加到实现ActionListener的实例中,您可以通过两种方式实现

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

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

为了将 Enter 键与文本框绑定,您应该实现KeyListener

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

最新更新