这是我的代码:
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();
}
}
为什么不出现“测试”?
答案 0 :(得分:2)
不要覆盖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();
}
答案 1 :(得分:2)
您需要调用超类的paint()方法。 (文章 - 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
}
覆盖JPanel的paintComponent。
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);
}
}