我想要一个显示在窗口中的形状列表。每当更改窗口大小时,我都希望缩放所有图纸。
我已经准备好了一些类,这些类将有关随机形状的信息存储在列表中(矩形,椭圆形等)。将它们全部绘画都没有问题,但是我无法处理缩放问题。我的解决方案不会改变任何东西,也不会使所有形状消失。
public class Shape extends JPanel{
int x, y,width,height,red,green,blue;
double scX, scY; //scale x and y
public Shape(int x, int y, int width, int height, int red, int green, int blue) {
//...long constructor
scX=1;
scY=1;
}
void randomizeValues(){...}
void setScale(double x, double y) {
this.scX = x;
this.scY = y;
}
}
public class Rectangle extends Shape{
public Rectangle(int x, int y, int width, int height, int red, int green, int blue) {
super(x, y, width, height, red, green, blue);
}
@Override
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
graphics.fillRect((int)(x*scX), (int)(y*scY), (int)(width*scX), (int)(height*scY));
}
}
class Window extends JFrame {
int defaultWidth = 768;
int defaultHeight = 512;
List<Shape> paintList = new ArrayList<>();
public Window() {
setTitle("Shape");
add(new DrawShape);
setSize(defaultWidth, defaultHeight);
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
class DrawShape extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i< paintList.size(); i++) {
Shape s = paintList.get(i);
s.setScale(this.getWidth()/defaultWidth, this.getHeight()/defaultHeight);
s.paintComponent(g);
}
}
}
如何制作适当的音阶技巧?我应该在哪里乘以值,以使一切正常?
答案 0 :(得分:0)
首先,您不应将JPanel添加到窗口中,而应将其设置为ContentPane:setContentPane(new DrawShape());
。接下来,您不应该在循环内部而是在外部重新绘画(例如,在paintComponent(Graphics g)
方法的末尾)。这样,应该再次永久绘制JPanel。
如果您需要根据窗口尺寸更改形状的大小,请像在JPanel paintComponent(Graphics g)
方法中那样进行操作:
//fill it with the shapes base sizes (index 0 = width, index 1 = height)
Map<Shape,int[]> shapeSizes = new HashMap<Shape,int[]>();
public void paintComponent(Graphics g) {
double widthCoeff = this.getWidth()/(double)Window.this.defaultWidth;
double heightCoeff = this.getHeight()/(double)Window.this.defaultHeight;
for (int i = 0; i< paintList.size(); i++) {
Shape s = paintList.get(i);
int[] baseSize = shapeSizes.get(s);
int oldWidth = baseSize[0], oldHeight = baseSize[1];
int width = oldWidth*widthCoeff, height = oldHeight*heightCoeff;
//you can now give the shape its new width and height
}
}