That's my support class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TrafficLightPanel extends JPanel
{
private JButton red, amber, green, change;
private JLabel label, label1;
private JPanel buttonPanel;
public TrafficLightPanel()
{
red = new JButton ("Red");
amber = new JButton ("Amber");
green = new JButton ("Green");
change = new JButton ("Change");
ButtonListener listener = new ButtonListener();
red.addActionListener (listener);
amber.addActionListener (listener);
green.addActionListener (listener);
change.addActionListener (listener);
buttonPanel = new JPanel();
buttonPanel.setPreferredSize (new Dimension(80, 390));
buttonPanel.setBackground (Color.white);
label = new JLabel ("Button Panel");
buttonPanel.add (label);
buttonPanel.add (red);
buttonPanel.add (amber);
buttonPanel.add (green);
buttonPanel.add (change);
label1 = new JLabel ("last pressed");
buttonPanel.add (label1);
setPreferredSize (new Dimension(200, 400));
setBackground (Color.blue);
add(buttonPanel);
LightPanel panel = new LightPanel();
add(panel);
panel.setPreferredSize (new Dimension(80, 390));
panel.setBackground (Color.cyan);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
if (event.getSource() == red)
label1.setText("Red");
buttonPanel.setBackground(Color.red);
if (event.getSource() == amber)
label1.setText("Amber");
buttonPanel.setBackground(Color.orange);
if (event.getSource() == green)
label1.setText("Green");
buttonPanel.setBackground(Color.green);
if(event.getSource() == change)
label1.setText("Change");
buttonPanel.setBackground(Color.white);
}
}
private class LightPanel extends JPanel
{
public void paintComponent (Graphics page)
{
super.paintComponent(page);
page.setColor(Color.red);
page.fillOval(15, 30, 40, 40);
page.setColor(Color.orange);
page.fillOval(15, 90, 40, 40);
page.setColor(Color.green);
page.fillOval(15, 150, 40, 40);
}
}
}
And that's my application class
import javax.swing.JFrame;
public class TrafficLight
{
public static void main (String[] args)
{
JFrame frame = new JFrame("Traffic Light");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TrafficLightPanel());
frame.pack();
frame.setVisible(true);
}
}
我想問我的程序是否完全按照它的設想做,但是我似乎無法將環路更改label1改爲紅色,並且同時更改了buttonPanel背景顏色的任何建議嗎?對我的信號燈環路有問題
礦也給出了一個問題 - 當我到達那裏時它總是紅色。 – LouwHopley
按鈕面板背景總是白色的,對吧?在你離開actionPerformed之前,這總是你做的最後一件事:'buttonPanel.setBackground(Color.white);' –
這本身並不是一個壞問題,但是在將來,你可以發佈最少量的代碼你的問題?這樣做意味着你的努力,並鼓勵其他人來幫助你。 –