2015-08-15 79 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编程非常陌生,程序中的一半东西似乎对我来说很复杂,而且超出了我的头脑。 –