状态发生变化时,在paintComponent()上调用@Override

时间:2016-12-25 05:18:33

标签: java swing user-interface awt override

如何通过响应状态更改来覆盖paintComponent方法? 错误消息:void是变量paintComponent

的无效类型
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 个答案:

答案 0 :(得分:1)

在上一个问题中:How do I make the superclass go beyond just the content pane?您获得了Swing基础知识的Swing教程链接。

嗯,Custom Painting还有一节供您阅读。然后,您可以下载该示例并使用它来了解绘画的工作原理。

基本上,Container类没有paintComponent()方法,因此您不应该尝试在该类中进行自定义绘制。

如果要更改绘制属性,则需要在类中添加一个方法来更改属性的状态,然后在自身上调用repaint()。

因此,从第3步中的教程示例中,您可以看到moveSquare(...)方法如何更改类的状态,然后调用repaint()。

请注意,您永远不应该在paintComponent()方法中调用repaint(),因为这会导致绘画不断重新安排。