为什么每次调整窗口大小时paintComponent都会更新?
这是我添加到添加到JFrame的JPanel的类。每次重新调整窗口大小时是否调用对象,或者使用paint组件进行调整的是什么?
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;
}
}
答案 0 :(得分:2)
将模型与视图结合起来会发生什么。永远不要将gui / graphics显示与内部应用逻辑相结合。这些在逻辑上是分开的,应该保持这样。
但要回答你的问题:你无法控制何时调用paintComponent()
。即使调用repaint也不过是java的GUI的建议,它应该重新绘制组件。
是的,在大多数情况下,调整大小会导致paintComponent()
来电。
答案 1 :(得分:1)
通过调整窗口大小,您已更改窗口的属性,因此应再次绘制视图元素。我认为这是合理的,因为显示布局的图形属性更改应该触发paintComponent以允许窗口适应更改。