我有以下程序。它应该在绿色地面上打印红色文字。当程序打开时,我只看到绿色的背景,但没有看到它的红色文字。一旦窗口大小调整并重新计算,就会显示红色文本。Java swing.JFrame只在窗口大小调整上绘制内容
如果我在窗口中使用JPanel并在其中添加组件,它将正常工作。如果颜色设置在paintComponent中,那么一切正常。
那么问题在哪里,如果我直接在JFrame上绘图。我是否错过了第一个“更新”或什么?它看起来像窗口第一次绘制时有一些信息缺失(附加文本),程序只有在重新计算和重绘窗口时才会知道该信息。
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class PaintAWT extends JFrame {
PaintAWT() {
this.setSize(600, 400);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
@Override
public void paint(Graphics g) {
super.paint(g);
// Set background color:
// If you don't paint the background, one can see the red text.
// If I use setBackground I only see a green window, until it is
// resized, then the red text appears on green ground
this.getContentPane().setBackground(new Color(0,255,0));
// Set color of text
g.setColor(new Color(255,0,0));
// Paint string
g.drawString("Test", 50, 50);
}
public static void main(String[] args) {
new PaintAWT();
}
}
对于初学者,您应该重写'paintComponent',而不是'paint'。我个人建议扩展一个'JPanel'而不是'JFrame'。您还需要一种方法来控制对“repaint”的调用,因为通过Swing的逻辑,容器通常只会在需要时重新绘制(即调整窗口大小时)。 – Gorbles