0

I am trying to add a panel to my frame, but it keeps giving me one error that I don't seem to understand.

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);
    } 
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045

1 Answers1

2

This complete, working example, based on your code, suggests that the problem is in your build environment. In addition,

  • JFrame::add() forwards to the contend pane implicitly.

  • Construct and manipulate Swing GUI objects only on the event dispatch thread.

  • Don't use setSize() when you really mean to override getPreferredSize().

  • Invoke super.paintComponent() to avoid visual artifacts.

  • For convenience in testing, a private static class is semantically equivalent to a package-private class.

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);
        }
    }
}
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045