[英]Java doubts about ActionEvent
这是我在这个网站上的第一个问题。 我有这个问题,在这个 class 中,我有两个具有两种不同功能的按钮,一个用于退出,另一个用于将名字和姓氏放在文本字段中。 我无法让第二个 ActionEvent 工作,请帮助我,谢谢。
import javax.swing.*;
import java.awt.event.*;
public class Prueba1 extends JFrame implements ActionListener{
private JLabel nombre, apellidos,respondo;
private JTextField textfield, textfield1;
private JButton boton,botonoff;
public Prueba1() {
setLayout(null);
nombre = new JLabel("Nombre:");
nombre.setBounds(10, 10, 300, 30);
add(nombre);
apellidos = new JLabel("Apellidos");
apellidos.setBounds(10, 40, 300, 30);
add(apellidos);
textfield = new JTextField();
textfield.setBounds(100,10,150,20);
add(textfield);
textfield1 = new JTextField();
textfield1.setBounds(100,40,150,20);
add(textfield1);
boton = new JButton("¿Que saldrá?");
boton.setBounds(10,80,120,30);
boton.addActionListener(this);
add(boton);
botonoff = new JButton("Salir");
botonoff.setBounds(10,120,120,30);
botonoff.addActionListener(this);
add(botonoff);
respondo = new JLabel("UwU");
respondo.setBounds(160,80,300,30);
add(respondo);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == boton) {
String nombreyapellidos, nombre1, apellidos1;
nombre1 = textfield.getText();
apellidos1 = textfield1.getText();
nombreyapellidos = nombre1 + apellidos1;
respondo.setText(nombreyapellidos);
}
}
public void actionPerformed1(ActionEvent e) {
if(e.getSource() == botonoff) {
System.exit(0);
}
}
public static void main(String args[]) {
Prueba1 clase = new Prueba1();
clase.setVisible(true);
clase.setBounds(0, 0, 500, 500);
clase.setResizable(true);
clase.setLocationRelativeTo(null);
}
}
当您向按钮 button.addActionListener(listener) 提供ActionListener
object
您有几种方法可以实现这一点。
button.addActionListener(this);
只是一种方式。 这样说 class 实现了 ActionListener。 实际上它实现了
public void actionPerformed(ActionEvent e)
方法。
您的
public void actionPerformed1(ActionEvent e)
按钮根本无法使用。
幸运的是,还有许多其他方法可以描述在产生动作事件时应该执行的代码。
内部 class、static 与否。 其他类/对象。 lambda 表达式。
您可以在此处找到如何表达 lambda。
删除public void actionPerformed1(ActionEvent e)
方法并将该方法的主体添加到public void actionPerformed(ActionEvent e)
void actionPerformed(ActionEvent e) 主体的 else 分支中。
public void actionPerformed(ActionEvent e) {
if (e.getSource() == boton) {
String nombreyapellidos, nombre1, apellidos1;
nombre1 = textfield.getText();
apellidos1 = textfield1.getText();
nombreyapellidos = nombre1 + apellidos1;
respondo.setText(nombreyapellidos);
} else if (e.getSource() == botonoff) {
System.exit(0);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.