2016-12-25 18 views
-1

如何覆蓋paintComponent方法並響應狀態變化? 錯誤消息:空隙是一個無效的類型可變的paintComponent狀態變化時在paintComponent()上調用@Override

public class MyContainer extends Container { 
public void paintComponent(Graphics m){ 
    m.drawArc(100,100,100,100,100,100); 
    m.setColor(Color.green); 
    m.fillArc(100,100,100,100,100,100); 
} 
public static void main(String[] args){ 
Container y = new Container(); 
JFrame x = new JFrame(); 
JPanel gg = new JPanel(); 

x.add(y); 
x.setTitle("   Shape Changer"); 
x.setBounds(100,50,500,300); 
x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
x.getContentPane().add(new ContentPanel()); 
x.getContentPane().add(new ContnetPanel()); 
x.setContentPane(new ContnetPanel()); 
x.setVisible(true); 
} 

static class ContentPanel extends JPanel{ 

private Graphics g; 
private JPanel ss; 
public void paint(Graphics g){ 
g.drawArc(100,100,100,100,100,100); 
g.fillRect(100, 100,100,100); 
} 
public ContentPanel(){ 

} 
} 
static class ContnetPanel extends JPanel implements ActionListener, ChangeListener{ 
    JComboBox comboerbox; 
    class appres { 
    public void paint(Graphics h){ 
     h.drawRect(100,100,100,100); 
     h.setColor(Color.red); 
     h.fillRect(100,100,100,100); 

    } 


    } 
public ContnetPanel(){ 
comboerbox = new JComboBox(); 
comboerbox.addItem("Red Square"); 
comboerbox.addItem("Blue Square"); 
comboerbox.addItem("Green Square"); 
comboerbox.setSelectedIndex(1); 
add(comboerbox); 
setLayout(new GridLayout(2,1)); 
} 

@Override 
protected void paintComponent(Graphics h){ 
super.paintComponent(h); 
h.drawArc(100,100,100,100,100,100); 
h.setColor(Color.blue); 
h.fillArc(100,100,100,100,100,100); 
repaint(); 
} 
int yy = 0; 
public void actionPerformed(ActionEvent evt){ 
switch(comboerbox.getSelectedIndex()){ 
case 0:yy=0; 

case 1: yy=1; 
case 2: yy=2; 
} 

} 
//evt.getSource()==comboerbox 
public void stateChanged(ChangeEvent evt){ 

    if(evt.getSource()==comboerbox){ 
    @Override 
    protected void paintComponent(Graphics h){ 
     super.paintComponent(h); 
     h.drawArc(100,100,100,100,100,100); 
     h.setColor(Color.blue); 
     h.fillArc(100,100,100,100,100,100); 
     repaint(); 
    } 
    } 

    else 
    { 
     System.out.println("DONE"); 
    } 

} 
} 
} 

當然,方法的paintComponent不是變量。我如何重寫paintComponent在這裏?或者更好的方式來響應狀態改變來改變形狀?那太棒了! 提前致謝,愛你們!

回答

1

在你的最後一個問題:你How do I make the superclass go beyond just the content pane?給予一個鏈接到了Swing教程一些搖擺基礎。

那麼還有上Custom Painting一個部分供您閱讀。然後,您可以下載該示例並使用它來了解繪畫的工作原理。

基本上容器類不具有的paintComponent()方法,所以你不應該試圖做的風俗畫在該類中。

如果你想改變一個繪畫屬性,那麼你需要的方法本身添加到您的類來更改屬性的狀態,然後調用重繪()。

所以從教程示例在步驟3中可以看到moveSquare(...)方法如何改變類的狀態,然後調用重繪()。

注意你不應該調用重繪()中的paintComponent()方法,因爲這將導致繪畫不斷地加以重新安排。