Java 如何在扩展类的情况下使用JPanel对象?

Java 如何在扩展类的情况下使用JPanel对象?,java,swing,object,jpanel,Java,Swing,Object,Jpanel,我有一个类Main,我调用所有扩展JPanel的类。所以,只要做: Frame.add(new JPanel) 知道这样的类扩展了JPanel。但是,我不能在该类中使用objectJPanel。我尝试使用new创建类的对象,但添加一些组件无效。它的工作方式如下:add,因为它是一个扩展类 主要类别: private void initialize() { tab = new JTabbedPane(); frame.add(new JScrollPane(tab));

我有一个类
Main
,我调用所有扩展
JPanel
的类。所以,只要做:

Frame.add(new JPanel)
知道这样的类扩展了
JPanel
。但是,我不能在该类中使用object
JPanel
。我尝试使用
new
创建类的对象,但添加一些组件无效。它的工作方式如下:
add
,因为它是一个扩展类

主要类别:

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);



}
在这个类中,我被称为我的
Toolbar
类,并将其添加到
JFrame

我的工具栏类:

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;

}

现在,我将创建一个
ActionListener
来进行搜索。因此,我想将
ActionListener
添加到
JPanel
ToolBar
)中。但是,我没有用于此目的的对象类。

您必须扩展
JPanel
,以满足您的需要:

class SpecialPanel extends JPanel{

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

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

}
然后,您可以在其他地方使用自定义的
JPanel

JFrame f = new JFrame("Hello World");
f.add(new SpecialPanel());
我创建了一个
ActionListener

用于封装
JToolBar
组件的功能,如本文所述


您是否可以显示一段代码,或者更好地说,一旦您扩展了类,它就是jpanel。因此,您需要创建一个新的Jframe
frame.add(this)
来访问从jpanel继承的方法,只需键入
this.TheMethodYouwantCall()
如果您根据他写的内容正确推断出他的意思,我将+1这个,我不太理解,希望有人这样做并编辑了OP.抛弃
paint
方法…
paintComponent
是执行自定义绘制的推荐和首选方法