java如何使用扩展类的JPanel对象?
我有一个类Main
,我调用所有扩展JPanel
的类。所以,只要做:
Frame.add(new JPanel)
知道这样的类扩展了JPanel
。但是,我不能在该类中使用对象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
)上。然而,我并没有那个类的对象
# 1 楼答案
使用^{} 封装
JToolBar
组件的功能,如本example中所述# 2 楼答案
为了满足您的需求,您必须扩展
JPanel
:然后,您可以在其他地方使用自定义
JPanel
: