【发布时间】:2016-04-25 16:05:21
【问题描述】:
我有以下程序。它应该在绿色地面上打印红色文本。当程序打开时,我只看到绿色背景,但看不到上面的红色文字。调整窗口大小并重新计算后,将出现红色文本。
如果我在窗口中使用 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 的逻辑,容器通常只会在需要时(即调整窗口大小时)重新绘制。