有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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加到JPanelToolBar)上。然而,我并没有那个类的对象


共 (2) 个答案

  1. # 1 楼答案

    I created an ActionListener.

    使用^{}封装JToolBar组件的功能,如本example中所述

    image

  2. # 2 楼答案

    为了满足您的需求,您必须扩展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());