2015-08-15 68 views
-1

我試圖製作一個紅綠燈程序,將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); 
    } 
} 
+0

不要使用空佈局! Swing旨在與[佈局管理器](http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html)一起使用。閱讀本教程,然後查看其他Swing基礎知識的目錄,這樣就不需要問這麼多問題。 – camickr

+0

至少這次他顯示了代碼,這是他[最後一個問題]的一個重大改進(http://stackoverflow.com/questions/32028972/jbutton-changes-text-colour-of-textfield)。 –

+0

你如何使用一個計數器,所以每次點擊該按鈕時,更新計數器並根據其值設置標籤的顏色? – MadProgrammer

回答

1

您使用的是相同的actionCommand,B每個if塊,所以所有的塊會一直運行,並且最後一個塊將在一個可見。

例如,

int x = 1; 
if (x == 1) { 
    // do something 
} 
if (x == 1) { 
    // do something else 
} 

所有塊會做!

要麼改變使用的actionCommands,要麼不使用actionCommand String,而使用遞增的int索引。此外,不要使用MouseListeners作爲JButtons,而是使用ActionListeners。

例如:

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.Font; 
import java.awt.GridBagLayout; 
import java.awt.event.ActionEvent; 
import java.util.HashMap; 
import java.util.Map; 

import javax.swing.*; 

public class Traffic2 extends JPanel { 
    private static final int PREF_W = 400; 
    private static final int PREF_H = 300; 
    private static final String[] STRINGS = {"Red", "Blue", "Orange", "Yellow", "Green", "Cyan"}; 
    private Map<String, Color> stringColorMap = new HashMap<>(); 
    private JLabel label = new JLabel("", SwingConstants.CENTER); 
    private int index = 0; 

    public Traffic2() { 
     stringColorMap.put("Red", Color.red); 
     stringColorMap.put("Blue", Color.blue); 
     stringColorMap.put("Orange", Color.orange); 
     stringColorMap.put("Yellow", Color.YELLOW); 
     stringColorMap.put("Green", Color.GREEN); 
     stringColorMap.put("Cyan", Color.CYAN); 

     label.setFont(label.getFont().deriveFont(Font.BOLD, 40f)); 
     String key = STRINGS[index]; 
     label.setText(key); 
     label.setForeground(stringColorMap.get(key)); 
     JPanel centerPanel = new JPanel(new GridBagLayout()); 
     centerPanel.add(label); 

     JPanel topPanel = new JPanel(); 
     topPanel.add(new JButton(new AbstractAction("Change Color") { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       index++; 
       index %= STRINGS.length; 

       String key = STRINGS[index]; 
       label.setText(key); 
       label.setForeground(stringColorMap.get(key)); 
      } 
     })); 

     setLayout(new BorderLayout()); 
     add(topPanel, BorderLayout.PAGE_START); 
     add(centerPanel, BorderLayout.CENTER); 
    } 

    @Override 
    public Dimension getPreferredSize() { 
     if (isPreferredSizeSet()) { 
      return super.getPreferredSize(); 
     } 
     return new Dimension(PREF_W, PREF_H); 
    } 

    private static void createAndShowGui() { 
     Traffic2 mainPanel = new Traffic2(); 

     JFrame frame = new JFrame("Traffic2"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       createAndShowGui(); 
      } 
     }); 
    } 
} 
+0

嘿,非常感謝。我複製了程序,它運行得很完美,但我對java編程非常陌生,程序中的一半東西似乎對我來說很複雜,而且超出了我的頭腦。 –