2015-11-23 76 views
0

我試圖啓動程序,並選擇jcheckbox帽子和矩形可見,然後矩形消失,當複選框被取消選中並重新選擇複選框時再次被選中。當我運行程序並勾選框時,出現另一個複選框或框架左側。面板不會在窗口中顯示

import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.event.ItemEvent; 
import java.awt.event.ItemListener; 
import javax.swing.*; 

public class Head extends JPanel { 

JCheckBox hat; 

public Head() { 
    hat = new JCheckBox("Hat"); 
    hat.setSelected(true); 
    hat.addItemListener(new CheckSelection()); 

    add(hat); 
} 

class CheckSelection implements ItemListener { 

    public void itemStateChanged(ItemEvent ie) { 
     repaint(); 
    } 
} 


public void paintComponent(Graphics g) { 

    setForeground(Color.RED); 
    g.drawOval(110, 100, 100, 100); 
    g.drawOval(130, 120, 20, 15); 
    g.drawOval(170, 120, 20, 15); 
    g.drawLine(160, 130, 160, 160); 
    g.drawOval(140, 170, 40, 15); 
    if (hat.isSelected()) { 
     g.drawRect(100, 90, 120, 10); 
    } 
    } 


public static void main(String[] args) { 
    Head head = new Head(); 
    JFrame f = new JFrame(); 
    f.add(head); 
    f.setSize(400, 400); 
    //f.setLayout(null); 
    f.setVisible(true); 
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
} 

}

回答

2

您已經通過不調用paintComponentsuper方法打破了油漆鏈

@Override 
protected void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    setForeground(Color.RED); 
    g.drawOval(110, 100, 100, 100); 
    g.drawOval(130, 120, 20, 15); 
    g.drawOval(170, 120, 20, 15); 
    g.drawLine(160, 130, 160, 160); 
    g.drawOval(140, 170, 40, 15); 
    if (hat.isSelected()) { 
     g.drawRect(100, 90, 120, 10); 
    } else { 
     setForeground(Color.RED); 
     g.drawOval(110, 100, 100, 100); 
     g.drawOval(130, 120, 20, 15); 
     g.drawOval(170, 120, 20, 15); 
     g.drawLine(160, 130, 160, 160); 
     g.drawOval(140, 170, 40, 15); 
    } 
} 

Graphics上下文是組件之間的共享資源,的工作之一paintComponent是爲繪畫準備Graphics,通常通過填充組件的背景顏色。所以不能稱之爲super.paintComponent意味着什麼都事先被塗到Graphics方面依然存在

詳情請參閱Painting in AWT and SwingPerforming Custom Painting有關如何在Swing

繪畫作品