我試圖製作一個紅綠燈程序,將JLabel的前景色從紅色更改爲綠色,每當我按下JButton時(即,一旦我按下JButton,JLabel就變成紅色,然後當我再次按JButton它變成黃色等)。但不知何故,顏色只改變一次紅色&沒有進一步按JButton時發生。任何形式的幫助,將不勝感激。謝謝。每當JButton按下時重複更改JLabel顏色
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class traffic {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
traffic window = new traffic();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public traffic() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 798, 512);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblTrafficLight = new JLabel("Traffic Light");
lblTrafficLight.setFont(new Font("Tahoma", Font.BOLD, 40));
lblTrafficLight.setHorizontalAlignment(SwingConstants.CENTER);
lblTrafficLight.setBounds(190, 11, 403, 61);
frame.getContentPane().add(lblTrafficLight);
JLabel lblRed = new JLabel("RED");
lblRed.setHorizontalAlignment(SwingConstants.CENTER);
lblRed.setFont(new Font("Tahoma", Font.PLAIN, 40));
lblRed.setBounds(273, 125, 249, 61);
frame.getContentPane().add(lblRed);
JButton btnButton = new JButton("Button");
btnButton.setActionCommand("B");
btnButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.RED);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.YELLOW);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.GREEN);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.YELLOW);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.RED);
}
}
});
btnButton.setBounds(353, 346, 89, 23);
frame.getContentPane().add(btnButton);
}
}
不要使用空佈局! Swing旨在與[佈局管理器](http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html)一起使用。閱讀本教程,然後查看其他Swing基礎知識的目錄,這樣就不需要問這麼多問題。 – camickr
至少這次他顯示了代碼,這是他[最後一個問題]的一個重大改進(http://stackoverflow.com/questions/32028972/jbutton-changes-text-colour-of-textfield)。 –
你如何使用一個計數器,所以每次點擊該按鈕時,更新計數器並根據其值設置標籤的顏色? – MadProgrammer