方法add(Component)不适用于参数

时间:2017-04-30 13:58:47

标签: java swing

我正在尝试向我的框架添加一个面板,但它一直给我一个我似乎不理解的错误。

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 个答案:

答案 0 :(得分:1)

这个完整的工作示例基于您的代码,表明问题出在您的构建环境中。另外,

image

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

public class FrameTest3 {

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            TestPanel samplePanel = new TestPanel();
            JFrame sampleFrame = new JFrame();
            sampleFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            sampleFrame.add(samplePanel);
            sampleFrame.pack();
            sampleFrame.setVisible(true);
            System.out.println("Done");
        });
    }

    private static class TestPanel extends JPanel {

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.red);
            g.drawString("hello", 30, 80);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(300, 200);
        }
    }
}