[英]How to use JPanel object with class extended?
我有一个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
。
我的ToolBar类:
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.