2016-04-25 215 views
0

我有以下程序。它应该在绿色地面上打印红色文字。当程序打开时,我只看到绿色的背景,但没有看到它的红色文字。一旦窗口大小调整并重新计算,就会显示红色文本。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(); 
    } 

} 
+1

对于初学者,您应该重写'paintComponent',而不是'paint'。我个人建议扩展一个'JPanel'而不是'JFrame'。您还需要一种方法来控制对“repaint”的调用,因为通过Swing的逻辑,容器通常只会在需要时重新绘制(即调整窗口大小时)。 – Gorbles

回答

4

您不应该在绘画方法中设置组件的属性。绘画方法仅适用于绘画。不要使用setBackground()。

您应该在创建框架时设置内容窗格的背景。

每当你做自定义绘画时,你也应该重写getPreferredSize()方法来返回组件的大小。

你也不应该扩展JFrame。当您向班级添加功能时,您只能扩展一个班级。

首先阅读Swing教程中有关Custom Painting的部分,详细信息和工作示例。这些示例将向您展示如何更好地构建代码以遵循Swing约定。

2

您应该将setBackground移动到构造函数中。在涂料方法中设置背景是一个不好的方法。

import java.awt.Color; 
import java.awt.Graphics; 

import javax.swing.JFrame; 
import javax.swing.SwingUtilities; 

public class PaintAWT extends JFrame { 

    PaintAWT() { 
     this.setSize(600, 400); 
     this.setLocationRelativeTo(null); 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     // 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)); 
     this.setVisible(true); 
    } 

    @Override 
    public void paint(Graphics g) { 
     super.paint(g); 


     // Set color of text 
     g.setColor(new Color(255,0,0)); 

     // Paint string 
     g.drawString("Test", 50, 50); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       new PaintAWT(); 
      } 
     }); 
    } 

} 
+1

你不应该扩展JFrame来做自定义绘画。你不应该重写paint()。 – camickr

+0

然后如何改变背景颜色?如果我把它放在构造函数中而不是paint方法中,它是固定的,不是吗? – Fuzzzzel