BorderLayout重复按钮

时间:2013-12-14 16:36:13

标签: java swing awt layout-manager border-layout

我正在尝试创建一个可以绘制的画布,以及一个在空状态下重置画布的按钮。 然而,使用BorderLayout我的按钮被复制,第二个是第一个的图像副本,但它仍然看起来不好。 我的代码有什么问题吗?如何修复。

PaintCanvas.java

import javax.swing.* ;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
class framakryesore extends JFrame {
    PaintCanvas p1 = new PaintCanvas();
    JButton b1 = new JButton ("Reset");
    public framakryesore (){


    b1.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
            clearcanvas(p1);
            repaint();
        }
    });

    this.add(b1,BorderLayout.NORTH);            
    this.add(p1,BorderLayout.CENTER);




}
    public void clearcanvas(PaintCanvas p){
        p.setX(0);
        p.setY(0);
    }
}
public class PaintCanvas extends JPanel {
    private int x = 0 ;
    private int y = 0 ;
    public void  setX(int x){
        this.x = x;
    }
    public void setY(int y){
        this.y = y;
    }
    public PaintCanvas() {
    addMouseMotionListener(new MouseMotionListener() {
        @Override
        public void mouseDragged(MouseEvent e){
        x=e.getX();
        y=e.getY();
        repaint();
        }
        public void mouseMoved(MouseEvent e){

        }


    });

    }
    @Override
    protected void paintComponent (Graphics g){
        if (x==0 && y==0){
            super.paintComponent(g);
        }
        else
        {
        g.setFont(new Font("TimesRoman", Font.BOLD, 30)); 
        g.drawString(".", x, y);
        }

    }


}

PaintCanvasTest.java

import javax.swing.JFrame;


public class PaintCanvasTest {
 public static void main(String args[]){
     framakryesore pikturo = new framakryesore();
     pikturo.setVisible(true);
     pikturo.setSize(640, 480);
     pikturo.setTitle("Pikturo");
     pikturo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


 }
}

1 个答案:

答案 0 :(得分:1)

if (x==0 && y==0){
    super.paintComponent(g);

您应该始终调用super.paintComponent()。在您进行自定义绘画之前,它负责清除面板的背景。