java在按钮旁边添加按钮代码
时间: 2024-02-23 07:02:38 浏览: 28
可以使用Java Swing库来实现这个功能,以下是一个简单的示例代码:
```java
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MultipleButtonsExample extends JFrame {
private JPanel panel;
private JButton button1;
private JButton button2;
public MultipleButtonsExample() {
panel = new JPanel();
button1 = new JButton("Button 1");
button2 = new JButton("Button 2");
button1.addActionListener(new Button1Listener());
button2.addActionListener(new Button2Listener());
panel.setLayout(new FlowLayout());
panel.add(button1);
panel.add(button2);
add(panel);
setSize(300, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class Button1Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Button 1 was clicked");
}
}
private class Button2Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Button 2 was clicked");
}
}
public static void main(String[] args) {
new MultipleButtonsExample();
}
}
```
这个程序创建了一个窗口,窗口上有两个按钮。当按钮被点击时,程序会将相应的信息打印到控制台上。可以根据需要修改按钮的功能和布局。