【问题标题】:Unwanted button painting on Panel面板上不需要的按钮绘制
【发布时间】:2014-05-01 20:39:02
【问题描述】:

所以我正在制作一个简单的绘画程序,我有两个面板。第一个面板位于右中,是画布。另一个停靠在右侧,用于按住工具按钮,但目前只有一个清除按钮。问题是当我开始点击画布时,清除按钮被绘制在它上面。知道我缺少什么吗?

public class Paint extends JFrame implements ActionListener {

    private Canvas canvas;
    private JButton clear;
    private JPanel tools;

    Paint(){
        canvas= new Canvas();
       add(canvas,BorderLayout.CENTER);
         clear= new JButton("Clear");
         clear.addActionListener(this);
         tools= new JPanel();
         tools.add(clear);
         add(tools,BorderLayout.WEST);

    }

    public void actionPerformed(ActionEvent e){
       if(e.getSource()==clear){
           canvas.clear();
       }
    }

    public static void main(String[] args) {
        Paint paint=new Paint();
        paint.setSize(1000,800);
        paint.setVisible(true);
        paint.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }   
}

画布:

public class Canvas extends JPanel {
    private int x= -10;
    private int y= -10;
    private boolean clear=false; 
    Canvas(){
      addMouseListener(new MouseAdapter(){
            @Override
            public void mousePressed(MouseEvent e){
                x=e.getX();
                y=e.getY();
                draw();
            }
        });

        addMouseMotionListener(new MouseMotionAdapter(){
          @Override
          public void mouseDragged(MouseEvent e){
              x=e.getX();
              y=e.getY();
              draw();
           } 
        });
    }

    @Override
    public void paintComponent(Graphics g){
       if(clear){
           super.paintComponent(g);
           clear=false;
       }
       else{
           g.fillOval(x,y,4,4);
       }


    }

    public void draw(){
        this.repaint();
    }

    public void clear(){
        clear=true;
        repaint();
    }
}

【问题讨论】:

    标签: java swing graphics jpanel paint


    【解决方案1】:

    Graphics 是共享资源,也就是说,在绘制周期中绘制的每个组件都使用相同的Graphics 上下文。

    paintComponent 的工作之一是为组件绘制准备Graphics 上下文,未能调用super.paintComponent 每次调用paintComponent 都会将之前绘制的内容留给Graphics机智的上下文。

    每次调用paintComponent 时都调用super.paintComponent

    在 Swing 中绘制具有破坏性,也就是说,每当调用 paintComponent 时,您都需要重新绘制组件的整个状态。

    【讨论】:

      猜你喜欢
      • 2012-09-07
      • 2012-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-27
      • 1970-01-01
      相关资源
      最近更新 更多