2015-10-06 83 views
0
public class Iconshape implements Icon { 


private Color color = Color.RED; 

public Iconshape (Color c) 
{ 
    this.color = c; 
} 
@Override 
public void paintIcon(Component c, Graphics g, int x, int y) { 
    Graphics2D g1 = (Graphics2D) g; 
    Ellipse2D.Double circle = new Ellipse2D.Double (0, 0, 20, 20); 
    g1.setColor(color); 
    g1.fill(circle); 

} 

@Override 
public int getIconWidth() { 
    // TODO Auto-generated method stub 
    return 0; 
} 

@Override 
public int getIconHeight() { 
    // TODO Auto-generated method stub 
    return 0; 
} 
public Color setColor(Color c) 
{ 
    return this.color = c; 

} 
} 


public class Button { 

private static JLabel label; 
private static Iconshape icon = new Iconshape(Color.RED); 

public static void main(String[] args) 
{ 
    JFrame frame = new JFrame(); 
    JButton red = new JButton("Red"); 
    JButton green = new JButton("Green"); 
    JButton blue = new JButton("Blue"); 
    label = new JLabel(icon); 
    final int FRAME_WIDTH = 600; 
    final int FRAME_HEIGHT = 400; 

    red.addActionListener(createRedButtonListener(Color.RED)); 
    blue.addActionListener(createRedButtonListener(Color.BLUE)); 
    green.addActionListener(createRedButtonListener(Color.GREEN)); 

    frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); 
    frame.setLayout(new FlowLayout()); 
    frame.add(red); 
    frame.add(blue); 
    frame.add(green); 
    frame.add(label); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    //frame.pack(); 
    frame.setVisible(true); 



} 

private static ActionListener createRedButtonListener(Color color) { 

    return new ActionListener() 
       { 
       public void actionPerformed(ActionEvent event) 
       { 
        if (color == Color.RED) 
        { icon.setColor(Color.RED); 
         label.repaint(); 
        } 
        if (color == Color.BLUE) 
        { icon.setColor(Color.BLUE); 
         label.repaint(); 
        } 
        if (color == Color.GREEN) 
        { icon.setColor(Color.GREEN); 
         label.repaint(); 
        } 
       } 
      }; 
} 
} 

嗨,我要實現一個程序,在按鈕單擊時更改標籤顏色,但唯一顯示在Jframe上的是3個按鈕。我能否得到一些幫助,我剛開始學習時並不知道很多GUI的東西。標籤不顯示在Jframe上

這是我迄今爲止

enter image description here

回答

5

你的圖標的寬度和高度都爲0的截圖,所以沒有什麼作畫。

他們getIconHeight()getIconWidth()方法應該返回20,因爲那是你的橢圓的大小。

+0

謝謝,我無法看到, – KhoaVo

+0

我upvoted這個答案 – KhoaVo