有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

  1. # 1 楼答案

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

    • JFrame::add()隐式转发到竞争窗格

    • event dispatch thread上构造和操作Swing GUI对象

    • 当你真的想覆盖^{}时,不要使用setSize()

    • 调用super.paintComponent()以避免visual artifacts

    • 为了便于测试,一个private static类在语义上等同于一个package-private

    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);
            }
        }
    }