我正在为学校设计一个音板程序。实际上我可以编写任何我想要的程序。我为此编写了一段代码,如下所示:
package soundboard;
import javax.swing.*;
import java.awt.event.*;
public class Soundboard implements ActionListener{
JButton loadButton;
JButton clearButton;
JButton Button1;
JButton Button2;
JButton Button3;
JButton Button4;
JPanel mainsPanel;
int load;
public void windowCreate() {
JFrame frame = new JFrame();
mainsPanel = new JPanel();
loadButton = new JButton("Load...");
loadButton.setSize(80, 30);
loadButton.setLocation(4, 4);
loadButton.addActionListener(this);
clearButton = new JButton("Clear");
clearButton.setSize(80, 30);
clearButton.setLocation(92, 4);
clearButton.addActionListener(this);
Button1 = new JButton("1");
Button1.setSize(80, 80);
Button1.setLocation(4, 45);
Button1.addActionListener(this);
Button2 = new JButton("2");
Button2.setSize(80, 80);
Button2.setLocation(92, 45);
Button2.addActionListener(this);
Button3 = new JButton("3");
Button3.setSize(80, 80);
Button3.setLocation(4, 133);
Button3.addActionListener(this);
Button4 = new JButton("4");
Button4.setSize(80, 80);
Button4.setLocation(92, 133);
Button4.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(loadButton);
frame.add(clearButton);
frame.add(Button1);
frame.add(Button2);
frame.add(Button3);
frame.add(Button4);
frame.add(mainsPanel);
frame.setSize(183,245);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
@Override
public void actionPerformed(ActionEvent event){
load += 1;
System.out.println(load);
}
public static void main(String[] args){
Soundboard window = new Soundboard();
window.windowCreate();
}
}
在此示例中,每个按钮都执行完全相同的操作。如何使用此基本代码进行设置,以便按钮执行自己的操作?我计划将其设计为点击“加载”按钮,然后数字按钮将声音加载到该按钮。在没有按下负载的情况下按下数字按钮首先会播放先前指定的声音。点击“清除”会卸载所有按钮。
最佳答案
而不是
ButtonX.addActionListener(this);
写
ButtonX.addActionListener(e -> {
//do stuff here
});
->
表示这是一个 lambda 表达式,它基本上从函数接口(interface)创建一个匿名类并将其作为参数传递。有关 lambda 表达式的更多信息,您可以阅读我的指南 here ,或官方(但很长)教程 here .
创建完所有 lambda 表达式后,您可以删除
@Override
public void actionPerformed(ActionEvent event){
load += 1;
System.out.println(load);
}
和
implements ActionListener
来自你的类(class)。
关于java - 设置各个按钮的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25895447/