[英]Java Paintcomponent Not Called
public class AnaMetod {
public static void main(String[] args) {
Grafik2D g2 = new Grafik2D(10, 50, "StackOverFlow");
}
}
package kibAr2D;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Grafik2D extends JPanel {
public static int a, b = 0;
public static String c = "";
public Grafik2D(int a, int b, String c) {
this.a = a;
this.b = b;
this.c = c;
JFrame j = new JFrame();
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setTitle("kibAr");
j.setBounds(150, 200, 613, 253);
j.setVisible(true);
}
public void paintComponent(Graphics g){
super.paintComponents(g);
g.drawString(c, a, b);
}
}
I cant understand why the paint method dont invoke? 我不明白为什么油漆方法不会调用? Maybe when JFrame create then automaticaly paintComponent and paint method invoke.. So how i can replace this problem?
也许当JFrame创建然后自动paintComponent和paint方法调用..所以我怎么可以替换这个问题?
Sory for my bad english.. 索里因为我的英语不好..
The problem is that you have created an empty JFrame
, but you have not added any components to it. 问题是您已经创建了一个空的
JFrame
,但是您没有添加任何组件。 Since your Grafik2D
class is a JPanel
, you need to add it to the frame with the line: 由于您的
Grafik2D
类是JPanel
,您需要使用以下行将其添加到框架中:
j.add(this);
in the constructor. 在构造函数中。
There are two problems with your code: 您的代码有两个问题:
1.) An instance of your Grafik2D
class needs to be in the visual tree. 1.)
Grafik2D
类的实例需要在可视化树中。 You should add it like this: 你应该像这样添加它:
public Grafik2D(int a, int b, String c) {
// ...
JFrame j = new JFrame();
// ...
j.add(this);
}
2.) You should either delete the call to paintComponents
or correct the spelling: 2.)您应该删除对
paintComponents
的调用或更正拼写:
super.paintComponent(g);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.