James F
James F

Reputation: 130

Why extend JPanel when adding to frame from another class?

I'm breaking down a GUI program into manageable classes. Was wondering why the following example code works when I extend a JPanel but not when I create an JPanel object in the constructor. Could anyone explain this? This works ->

public class SomePanel extends JPanel{
private JScrollPane scroll;
private JTextArea text;

public SomePanel() {

    // TextArea
    text = new JTextArea(10,50);
    text.setBackground(Color.black);

    // JScrollPane
    scroll = new JScrollPane(text);
    scroll.getHorizontalScrollBar().setEnabled(false);
    scroll.setWheelScrollingEnabled(false); 

    add(scroll);
}

This will not work ->

public class SomePanel{

private JScrollPane scroll;
private JTextArea text;
private JPanel panel;

public SomePanel() {

    panel = new JPanel();

    text = new JTextArea(10,50);
    text.setBackground(Color.black);

    // JScrollPane
    scroll = new JScrollPane(text);
    scroll.getHorizontalScrollBar().setEnabled(false);
    scroll.setWheelScrollingEnabled(false); 

    panel.add(scroll);
}

Add to frame etc..

public class Frame {
   SomePanel panel;
public Frame(){
      */*
       * Construct frame etc
      */*
       frame.add(panel = new SomePanel());
      }
}

Upvotes: 2

Views: 709

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

It's because in the second case, SomePanel is not a class that extends from Component and so it can't be added to a Container such as a JFrame's contentPane. To fix this, give the class a method that allows other classes to extract its contained JPanel:

public JComponent getPanel() {
    return panel;
}

and add it to your JFrame:

frame.add(new SomePanel().getPanel());

Upvotes: 2

Related Questions