java方法add(Component)不适用于参数
我试图添加一个面板到我的框架,但它一直给我一个错误,我似乎不明白
Multiple markers at this line
- Debug Current Instruction Pointer
- The method add(Component) in the type Container is
not applicable for the arguments (TestPanel)
import javax.swing.*;
public class FrameTest3 {
public static void main(String[] args) {
TestPanel samplePanel=new TestPanel();
JFrame sampleFrame = new JFrame();
sampleFrame.getContentPane().add(samplePanel);
sampleFrame.setSize(300,200);
sampleFrame.setVisible(true);
System.out.println("Done");
}
}
import java.awt.*;
import javax.swing.*;
public class TestPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.red);
g.drawString("hello", 30, 80);
}
}
# 1 楼答案
这个完整的工作示例基于您的代码,表明问题出在您的构建环境中。此外
JFrame::add()
隐式转发到竞争窗格在event dispatch thread上构造和操作Swing GUI对象仅
当你真的想覆盖^{} 时,不要使用
setSize()
调用
super.paintComponent()
以避免visual artifacts为了便于测试,一个
private static
类在语义上等同于一个package-private类