我是堆叠溢出的新手,所以我不知道一切是如何工作的,顺便说一下。顺便说一句,我知道我在这里有什么错,它绝对是paint组件,但是如何更改它以便我的ActionListener可以完成我给它的命令。我想说的是,如果单击JButton一次,那么代码中的停止灯区域 - 尺寸将以某种颜色点亮,并且一次又一次按下,灯光将移动到下一个颜色,等等。以下是我需要帮助的具体方面。
package trafficlight;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class TrafficMethods extends JPanel
{
private JButton c;
private final int x=50, y=50, xx=100, yy=260, d=60;
private int count;
public TrafficMethods()
{
c = new JButton("Change the color");
c.addActionListener(new ActC());
add(c);
}
private class ActC implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
public void paintComponent(Graphics p)
{
count++;
switch(count)
{
case '1':
p.setColor(Color.red);
p.fillOval(x+20, y+20, d, d);
break;
case '2':
p.setColor(Color.green);
p.fillOval(x+20, y+100, d, d);
break;
case'3':
p.setColor(Color.yellow);
p.fillOval(x+20, y+180, d, d);
break;
}
}
}
}
}
*****编辑***** 我制作了一个全新的类代码,我想知道我是否可以让它工作。一切正常,就在我点击“改变颜色”的按钮时,什么都不会发生。我可以在代码中更改哪些内容,以便每次单击“更改颜色”时,它实际上都会这样做?
package trafficlight;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TrafficPanel extends JPanel implements ActionListener {
private int clicks;
private final int x=50, y=50, xx=100, yy=260, d=60;
private Button color;
private JPanel panel;
private boolean redclick = false, yellowclick = false, greenclick = false;
public TrafficPanel()
{
setPreferredSize(new Dimension(200,400));
panel = new JPanel();
color = new Button ("Change the color");
panel.add(color);
add(panel, BorderLayout.NORTH);
color.addActionListener(this);
}
public void paint (Graphics g)
{
setBackground(Color.blue);
g.setColor(Color.black);
g.fillRect(x, y, xx, yy);
if(redclick == true)
{
g.setColor(Color.red);
g.fillOval(x+20, y+20, d, d);
redclick = false;
}
if(yellowclick == true)
{
g.setColor(Color.yellow);
g.fillOval(x+20, y+100, d, d);
yellowclick = false;
}
if(greenclick == true)
{
g.setColor(Color.green);
g.fillOval(x+20, y+180, d, d);
greenclick = false;
}
}
@Override
public void actionPerformed(ActionEvent e) {
clicks++;
switch (clicks)
{
case '1':
greenclick = true;
repaint();
case '2':
yellowclick = true;
repaint();
case '3':
redclick = true;
repaint();
}
}
}