[英]How to automatically resize buttons on BorderPane as the window is resized?
[英]Resize window calls paintComponent each time Window is resized?
为什么每次我调整窗口大小时paintComponent都会更新?
这是我要添加到添加到JFrame的JPanel的类。 每次调整窗口大小时,是否要调用对象?或者绘画组件到底发生了什么?
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Random;
import javax.swing.JComponent;
import javax.swing.JPanel;
class DrawString extends JPanel {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
Font font = new Font("Serif", Font.PLAIN, 10);
g2.setFont(font);
g2.drawString("Test string",randInt(1,1000), randInt(1, 1000));
for(int i = 0; i < 100; i++) {
g.setColor(new Color(randInt(1,255), randInt(1,255),randInt(1,255)));
g.drawLine(randInt(1,1000), randInt(1,1000), randInt(1,1000), randInt(1,1000));
}
}
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
super.setBackground(new Color(100,100,100));
paint(g);
}
public static int randInt(int min, int max) {
// Usually this can be a field rather than a method variable
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}
这就是将模型与视图结合在一起时发生的情况。 切勿将显示GUI /图形与内部应用程序逻辑相结合。 这些在逻辑上是分开的,应该保持这样。
但要回答您的问题:您无法控制何时调用paintComponent()
。 甚至调用repaint也无非是建议 Java GUI重新绘制组件。
是的,在大多数情况下,调整大小将导致paintComponent()
调用。
通过调整窗口的大小,可以更改窗口的属性,因此应再次绘制视图元素。 我认为这是合理的,因为显示布局的图形属性更改应触发paintComponent,以使您的窗口适应更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.