我有以下代碼:的JLabel不會改變顏色兩次
public class Test extends JFrame implements ActionListener{
private static final Color TRANSP_WHITE = new Color(new Float(1), new Float(1), new Float(1), new Float(0.5));
private static final Color TRANSP_RED = new Color(new Float(1), new Float(0), new Float(0), new Float(0.1));
private static final Color[] COLORS = new Color[]{ TRANSP_RED, TRANSP_WHITE};
private int index = 0;
private JLabel label;
private JButton button;
public Test(){
super();
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
label = new JLabel("hello world");
label.setOpaque(true);
label.setBackground(TRANSP_WHITE);
getContentPane().add(label);
button = new JButton("Click Me");
button.addActionListener(this);
getContentPane().add(button);
pack();
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(button)){
label.setBackground(COLORS[index % (COLORS.length - 1)]);
index++;
}
}
public static void main(String[] args) {
new Test();
}
}
當我運行它,我得到了TRANSP_WHITE
背景標籤,然後當我點擊按鈕,這個顏色更改爲TRANSP_RED
但是當我點擊它我再次看到顏色沒有變化。有誰知道爲什麼?
謝謝
這是正確的,因爲我使用半透明顏色,因此在提供JLabel之前Swing不會繪製它下面的組件 – Aly 2010-03-21 16:15:16