nsc*_*010 1 java graphics swing shapes paintcomponent
我已经使用该paintComponent方法在我的面板上绘制形状.但是,每次我最小化帧或调整大小时,它们都会消失.不确定要添加到我的代码中的内容.
public class ShapePanel extends JPanel implements ActionListener, MouseListener{
int a,b,c,d;
Graphics2D g2D;
private Rectangle2D rect = new Rectangle2D(a,b,c-a,d-b);
public ShapePanel(){
addMouseListener(this);
setLayout(new GridLayout());
}
public void paintComponent(Graphics g) {
g2D = (Graphics2D) g;
g2D.draw(rect);
repaint();
}
//get methods for coordinates: MousePressed, MouseReleased
Run Code Online (Sandbox Code Playgroud)
不要repaint()在paintComponent方法下打电话.另外,super.paintComponent(g)在你的paintComponent方法中做第一件事.
更新:您的代码有很多编译错误.但是,请参阅下面的要更改的列表:
new Rectangle2D(a, b, c, d)应该是新的Rectangle2D.Float(10, 10, 100, 100);或者无论如何,a,b,c和d应该有一些值,否则它们都是零,所以没有矩形mouseClicked,mouseEntered和mouseExitedg2D.draw()从班级中删除actionPerformed并不保留引用g2D.如果需要,我有完整的代码.