3

这是我的代码:

package survival;
import javax.swing.*;
import java.awt.*;

public class Survival extends JFrame { 
    private static int applicationWidth = 1400;
    private static int applicationHeight = 900;  

    public Survival() {
        setTitle("Survival");
        setResizable(false);
        setSize(applicationWidth, applicationHeight);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public void paint(Graphics g) {
        g.drawString("Test", 0, 0);
    }

    public static void main(String[] args) {
        new Survival();
    }
}

为什么“测试”没有出现?

4

2 回答 2

3

不要覆盖paint. 每当您自定义组件时,覆盖paintComponent.

例子 -

@Override
protected final void paintComponent(final Graphics g){
    super.paintComponent(g);
    final Graphics gCopy = g.create(); // Prevents clobbering
    gCopy.drawString("Test", 0, 0);
    gCopy.dispose();
}
于 2011-12-13T02:25:03.630 回答
2

You need to invoke paint() method of super class. (Article - Painting in AWT and Swing)

 public Survival() {
        setTitle("Survival");
        setResizable(false);
        setSize(applicationWidth, applicationHeight);
        setVisible(true);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        repaint();
    }

    public void paint(Graphics g) {
        super.paint(g);    
        g.drawString("Test", 120, 120); //change the co-odrinates
    }

Override the paintComponent of JPanel.

 public Survival() {
        setTitle("Survival");
        setResizable(false);
        setSize(applicationWidth, applicationHeight);
        setVisible(true);
        add(new DrawPanel());
        setDefaultCloseOperation(EXIT_ON_CLOSE);
     }

   class DrawPanel extends JPanel
   {
    @Override
    protected  void paintComponent( Graphics g){
       g.drawString("Test", 220,220);
      }
   }
于 2011-12-13T02:30:20.653 回答