为什么JButton的图片重新出现在顶部?

时间:2013-12-08 04:54:41

标签: java swing jpanel awt

我正在尝试制作简单的项目,在鼠标点击JPanel时绘制形状。我有4个选择形状类型的按钮。我还没有为按钮提供任何ActionListiner(我知道该怎么做)。我的项目绘制了Jpanel顶部按钮的图片,我不知道如何解决它。

   import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.Random;
    import javax.swing.JPanel;

    public class ShapeStamper extends JPanel {


    private int x = -1000, y = -1000;
    private boolean outside = false;

    public ShapeStamper() {

        addMouseListener(
                // anonymous inner class
                new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent event) {
                outside = false;
                x = event.getX();
                y = event.getY();
                repaint();
                System.out.println(x + " " + y);
            }
        } // end anonymous inner class
                ); // end call to addMouseMotionListener

        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseExited(MouseEvent e) {
                outside = true;
                repaint();
                x = e.getX();
                y = e.getY();
                System.out.println(x + " " + y);
                System.out.println(outside);

            }
        });

    }

    @Override
    public void paintComponent(Graphics g) {
        g.drawOval(x, y, 40, 40);

    }

}



import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class ShapeStamperTest {



    public static void main(String[] args) {
        JFrame frame= new JFrame("Shape Stamper!");

   JPanel container;
     JButton circle = new JButton("Circle");
     JButton square = new JButton("Square");
      JButton rectangle = new JButton("Rectangle");
      JButton oval = new JButton("Oval");


        container = new JPanel(new GridLayout(1, 4));
        container.add(circle);
        container.add(square);
        container.add(rectangle);
        container.add(oval);


      final ShapeStamper shape = new ShapeStamper();
     circle.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Circle");

            }
        });
      frame.setSize(500, 500);
      frame.add(shape, BorderLayout.CENTER);
        frame.add(container, BorderLayout.SOUTH);;
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

}

1 个答案:

答案 0 :(得分:0)

您需要在super.paintComponent方法中调用paintComponentpaintComponent也应该protected知名度

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawOval(x, y, 40, 40);
}