java为什么JButton的图片会再次出现在顶部?
当鼠标点击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 楼答案
您需要在
paintComponent
方法中调用super.paintComponent
。而且paintComponent
应该具有protected
可见性