user294698
user294698

Reputation: 35

Adding an object to Jpanel

I know how to add JButton to a JPanel but how about a class I make?

I have this class:

public class Monster
{
    private ImageIcon monster;
    private JButton b;

    public Monster()
    {
        monster = new ImageIcon("Monster.jpg");
        b = new JButton(monster);
        b.setIcon(monster);
    }
}

I have another class and in that class I want to add the icon to my swing window.

import javax.swing.*;
import java.awt.*;
public class GameWindow
{
    private JFrame frame;
    private JPanel panel;
    private Monster monster;

    public GameWindow()
    {
        frame = new JFrame();
        panel = new JPanel();
        monster = new Monster();

        panel.add(monster); 

        frame.setContentPane(panel); 
        frame.setTitle("Game"); 
        frame.setSize(400,400); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

The panal.add() method works for JButtons but not for my Monster class. How can I add my Monster object to the Swing window I made in GameWindow class?

Upvotes: 0

Views: 809

Answers (3)

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51565

You should use Swing components. The only reason to extend a Swing component (or any other Java class) is if you want to override one of the class methods.

You were missing a method in your Monster class.

public class Monster
{
    private ImageIcon monster;
    private JButton b;

    public Monster()
    {
        monster = new ImageIcon("Monster.jpg");
        b = new JButton(monster);
        b.setIcon(monster);
    }

    public JButton getMonsterButton() {
        return b;
    }
}

The add line in your GameWindow class would look like this:

    panel.add(monster.getMonsterButton());

Upvotes: 2

ItachiUchiha
ItachiUchiha

Reputation: 36792

Try this, since JPanel accepts a Swing UI Components, this makes your class MonsterIcon a part of Swing (in lay man's term)

public class MonsterIcon extends JButton {

      public MonsterIcon () {
        this(new ImageIcon("Monster.jpg"));
      }

      public MonsterIcon (ImageIcon icon) {
        setIcon(icon);
        setMargin(new Insets(0, 0, 0, 0));
        setIconTextGap(0);
        setBorderPainted(false);
        setBorder(null);
        setText(null);
        setSize(icon.getImage().getWidth(null), icon.getImage().getHeight(null));
      }
 }

Upvotes: 1

Martin Dinov
Martin Dinov

Reputation: 8825

Make your class extend ImageIcon or JButton. This is because the add() method of the JPanel expects a JComponent.

Upvotes: 0

Related Questions