[英]How can I draw an oval using jbuttons and actionlistener?
我调查了可能已经回答的其他一些问题,但没有发现任何与我有关的问题,或者至少没有我所了解的问题。
我正在尝试创建一个交通信号灯,而我遇到的问题是单击按钮时红色,绿色和黄色圆圈的实际绘制。 一个快速的答案将不胜感激,谢谢。
public class TrafficLight extends JApplet implements ActionListener {
private Image Hayden;
JButton btn1;
JButton btn2;
JButton btn3;
int x;
public void init() {
setLayout(new FlowLayout());
btn1 = new JButton("Stop");
btn2 = new JButton("Wait");
btn3 = new JButton("Go");
Boolean Answer;
add(btn1);
btn1.addActionListener(this);
add(btn2);
btn2.addActionListener(this);
add(btn3);
btn3.addActionListener(this);
Hayden = getImage(getDocumentBase(), "49.jpg");
}
public void actionPerformed(ActionEvent event){
if (event.getSource()==btn1){
boolean one = true;
}
if (event.getSource()==btn2){
boolean two = true;
}
if (event.getSource()==btn3){
boolean three = true;
}
repaint();
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.black);
g.drawRect(0, 400, 700, 200);//creating the rectangle
g.fillRect(0, 400, 700, 200);
g.setColor(Color.black);
g.drawRect(645, 0, 55, 155);//creating the rectangle
g.fillRect(645, 0, 55, 155);
g.setColor(Color.white);
g.drawOval(650, 5, 45, 45);//creating the oval
g.fillOval(650, 5, 45, 45);
g.setColor(Color.white);
g.drawOval(650, 55, 45, 45);//creating the oval
g.fillOval(650, 55, 45, 45);
g.setColor(Color.white);
g.drawOval(650, 105, 45, 45);//creating the oval
g.fillOval(650, 105, 45, 45);
if (one == true){
g.setColor(Color.red);
g.drawOval(650,5,45,45);
}
else if (two == true){
g.setColor(Color.red);
g.drawOval(650,55,45,45);
}
else if (three == true){
g.setColor(Color.red);
g.drawOval(650,105,45,45);
}
g.drawImage(Hayden, 0, 500, 150, 100, this);//create the image
}
}
isSelected()
方法与切换按钮更为相关。 在您的情况下,在actionPerformed()
内部,任何条件都不会返回true。 快速而肮脏的解决方法可能是检查事件的来源,即:
if (event.getSource() == btn1){
x = 5;
}
清洁将是:
btn1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
x = 5;
}
});
另一个注意事项是,您是否在JPanel或JComponent上自定义绘画,然后将该组件添加到JApplet的内容窗格中。 有关详细信息,请参见课程:执行自定义绘画 。
另外,建议使用布局管理器而不是绝对布局。 请查看《布局管理器视觉指南》以获取更多信息。
确保阅读“ 如何制作小程序”教程以获取一般指导。
编辑:关于
减少一点,希望不会更糟}
您上一次编辑不正确,无法编译。 您在声明局部变量boolean one = true;
并尝试在另一种方法中使用它。 使boolean one
班级成员。 与two
和three
变量相同。
您需要警惕的一件事是可变范围。 布尔值1、2和3在其各自的if语句中具有范围。 如果您使这些布尔实例变量(在类的顶部创建像int x和您的按钮这样的变量),则它们的作用域就是整个类,并且可以在每个方法中引用它们。
JButton btn2;
JButton btn3;
boolean one, two three;
截至目前,这些布尔值不能由任何不在其if语句中的东西(包括paint方法)访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.