这是我在这个网站上的第一个问题。我有这个问题,在这个类中,我有两个按钮,有两个不同的功能,一个用于退出,另一个用于将名字和姓氏放在文本字段中。我无法让第二个动作事件工作,请帮助我,谢谢。
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);
}
}
删除public void actionPerformed1(ActionEvent e)
方法并将该方法的主体添加到public void actionPerform(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);
}
}
当您向按钮按钮提供操作侦听器
对象时。addActionListener(侦听器)
您有几种方法可以实现此目的。
button.addActionListener(this);
只有一种方法。这种方式表示该类实现ActionListener。实际上,它实现了
public void actionPerformed(ActionEvent e)
方法。
你
public void actionPerformed1(ActionEvent e)
完全不能被按钮使用。
幸运的是,还有许多其他方法可以描述在生成操作事件时应该执行的代码。
一个内部类,不管是不是静态的。其他类/对象。lambda表达式。
你可以在这里找到如何表达lambda。