Patrick Harden
Patrick Harden

Reputation: 45

How to integrate JPanel class into JFrame class?

I have three classes, MessageFrame, MessagePanel, and Message with the main method. I'm not sure how to add the JPanel into the JFrame class.

MessageFrame:

public class MessageFrame extends JFrame{

public MessageFrame(){
    setTitle("Message in a Bottle");
    setSize(960, 960);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    MessagePanel pane = new MessagePanel();
    // <- this is where stackoverflow recommends add(MessagePanel) but it gives me an error
}

public void paint(Graphics g){
    Graphics2D g2 = (Graphics2D)g;
    Font font = new Font("Serif", Font.PLAIN, 30);
    g2.setFont(font);
    g2.drawString("Text", 160, 180);

}
}

MessagePanel:

 public class MessagePanel {
    public MessagePanel(){
    JPanel p = new JPanel();    
    }
}

Message:

public class Message {

public static void main(String[] args) {
    MessageFrame x = new MessageFrame();
    x.paint(null);
}
}

Upvotes: 0

Views: 117

Answers (2)

baxdab
baxdab

Reputation: 141

this is where stackoverflow recommends add(MessagePanel) but it gives me an error

Try instead add(pane)

Upvotes: 0

camickr
camickr

Reputation: 324098

recommends add(MessagePanel) but it gives me an error

MessagePanel is not a Component and only components can be added to a frame.

If you want to add the MessagePanel to the frame, then MessagePanel needs to extend JPanel.

Then there is no need to create a JPanel in the constructor, since the class already is a JPanel.

x.paint(null);

Of course once you get a clean compile you will get a NullPointerException because you are passing null to the paint() method. Get rid of that statement and don't even override the paint() method of the frame. That is not how you do custom painting.

I suggest you read the Swing tutorial for the basics since you code shows a lack of understanding of Swing basics.

Maybe start with Top Level Container. The tutorial has plenty of examples you should be downloading to learn how to better structure your code.

Upvotes: 1

Related Questions