user2279895
user2279895

Reputation:

How to use JPanel object with class extended?

I have a class Main, which I'm calling all my classes that extend JPanel. So, just do:

Frame.add(new JPanel)

Knowing, that such class extends JPanel. However, I cannot use object JPanel in that class. I tried to create an object of the class using new, but it does not work to add some component. Just works the of ways: add, because it is an extended class.

Main Class:

private void initialize() 
{

    tab = new JTabbedPane();
    frame.add(new JScrollPane(tab));
    frame.setTitle(TITLE);
    frame.setSize(800,500);
    frame.add(new ToolBar);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setJMenuBar(getJMenuBar());
    frame.setVisible(true);



}

In this class, I'm called my Toolbar class and add it to JFrame.

My ToolBar Class:

public class ToolBar extends JPanel {

private JToolBar toolbar;
private JButton icon;

/**
 * 
 * @param tab
 */
public ToolBar()
{

    setLayout(new BorderLayout());
    add(setJToolBar(),BorderLayout.NORTH); // add JToolbar to panel
    setBackground(getColor()); // sets up color for panel.



}

/**
 * Sets setJButtonNewFileIcon with icon
 * @return
 * JButton
 */
private JButton setJButtonNewFileIcon()
{
    icon = new JButton();
    icon.setBorder(border);
    icon.setBackground(getColor());
    icon.setToolTipText("New File");
    icon.setIcon(new ImageIcon(getClass().getClassLoader().getResource("icons/new.png")));

    return icon;

}

Now, I going to create an ActionListener to search. So, I want to add that ActionListener to that JPanel (ToolBar). However, I do not have object that class for that.

Upvotes: 1

Views: 507

Answers (2)

trashgod
trashgod

Reputation: 205845

I created an ActionListener.

Use Action to encapsulate the functionality of your JToolBar components, as suggested in this example.

image

Upvotes: 2

moonwave99
moonwave99

Reputation: 22797

You have to extend JPanel in order to fit your needs:

class SpecialPanel extends JPanel{

  public SpecialPanel(){
    super();
    // some more logic in constructor 
  }

  public void paintComponent(Graphics g){
    super.paintComponent(g);
    // override paint() for example
  }

}

Then you can use your custom JPanel elsewhere:

JFrame f = new JFrame("Hello World");
f.add(new SpecialPanel());

Upvotes: 1

Related Questions