gpt4 book ai didi

java repaint() 问题

转载 作者:行者123 更新时间:2023-12-01 15:04:25 25 4
gpt4 key购买 nike

使用任何类型的转换调用重绘时遇到一些问题例如:g2D.scale(1.1,1.1)查看代码示例repaint() 没有问题,但如果你调用 repaint(x,y,w,h) 重绘会变成梨形并且不起作用。您如何解决这个问题?

import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseMotionAdapter;

public class RepaintDemo {

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}

private static void createAndShowGUI() {
JFrame f = new JFrame("Swing Paint Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new MyPanel());
f.setSize(400,400);
f.setVisible(true);
}
}

class MyPanel extends JPanel {

private int squareX = 50;
private int squareY = 50;
private int squareW = 20;
private int squareH = 20;

public MyPanel() {

setBorder(BorderFactory.createLineBorder(Color.black));

addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
moveSquare(e.getX(),e.getY());
}
});

addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
moveSquare(e.getX(),e.getY());
}
});

}

private void moveSquare(int x, int y) {
int OFFSET = 1;
if ((squareX!=x) || (squareY!=y)) {
repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
squareX=x;
squareY=y;
repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
}
}


protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D = (Graphics2D)g;
g2D.scale(1.1,1.1);
g.setColor(Color.RED);
g.fillRect(squareX,squareY,squareW,squareH);
g.setColor(Color.BLACK);
g.drawRect(squareX,squareY,squareW,squareH);
}
}

最佳答案

像这样的东西怎么样

 if ((squareX!=x) || (squareY!=y)) {
repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
squareX=x;
squareY=y;
repaint(squareX+x,squareY+y,squareW+x+OFFSET,squareH+y+OFFSET);
}

显然,您可以根据您的具体需求修改和改进行为

关于java repaint() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13170502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com