以下是一个示例代码,演示了如何使用按钮状态、绘制和触发多个按钮:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MultipleButtonsExample extends JFrame implements ActionListener {
private JButton button1;
private JButton button2;
private boolean isButton1Pressed;
private boolean isButton2Pressed;
public MultipleButtonsExample() {
// 创建窗口
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
// 创建按钮
button1 = new JButton("Button 1");
button1.addActionListener(this);
button2 = new JButton("Button 2");
button2.addActionListener(this);
// 将按钮添加到窗口
getContentPane().setLayout(new FlowLayout());
getContentPane().add(button1);
getContentPane().add(button2);
// 初始化按钮状态
isButton1Pressed = false;
isButton2Pressed = false;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MultipleButtonsExample example = new MultipleButtonsExample();
example.setVisible(true);
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) {
isButton1Pressed = !isButton1Pressed;
} else if (e.getSource() == button2) {
isButton2Pressed = !isButton2Pressed;
}
// 重新绘制按钮
repaint();
// 执行其他操作...
// 触发其他按钮事件...
}
@Override
public void paint(Graphics g) {
super.paint(g);
// 绘制按钮状态
if (isButton1Pressed) {
g.setColor(Color.RED);
g.fillRect(button1.getX(), button1.getY(), button1.getWidth(), button1.getHeight());
}
if (isButton2Pressed) {
g.setColor(Color.BLUE);
g.fillRect(button2.getX(), button2.getY(), button2.getWidth(), button2.getHeight());
}
}
}
在这个示例中,我们创建了一个带有两个按钮的窗口。每个按钮都有一个关联的布尔变量来表示它的状态。当按钮被按下时,我们会更新对应的布尔变量,并调用repaint()
方法重新绘制按钮。
在paint()
方法中,我们根据按钮的状态来绘制不同的颜色。如果按钮被按下,我们会用红色或蓝色填充按钮的矩形区域。
通过实现ActionListener
接口,并在actionPerformed()
方法中处理按钮点击事件,我们可以对按钮的状态进行更新,并触发其他操作。
这只是一个简单的示例,你可以根据自己的需求进行扩展和修改。
上一篇:按钮状态-按下和重新按下
下一篇:按钮追加到div