繁体   English   中英

如何使用类扩展的JPanel对象?

[英]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添加到该JPanelToolBar )。 但是,我没有那个类的对象。

我创建了一个ActionListener

使用Action来封装JToolBar组件的功能,如本例所示

图片

您必须扩展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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM