简体   繁体   English

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

[英]How to use JPanel object with class extended?

I have a class Main , which I'm calling all my classes that extend JPanel . 我有一个Main类,我正在调用扩展JPanel所有类。 So, just do: 那么,就这样做:

Frame.add(new JPanel)

Knowing, that such class extends JPanel . 知道,这样的类扩展了JPanel However, I cannot use object JPanel in that class. 但是,我不能在该类中使用对象JPanel I tried to create an object of the class using new , but it does not work to add some component. 我尝试使用new创建类的对象,但它不能添加一些组件。 Just works the of ways: add , because it is an extended class. 只是工作方式: add ,因为它是一个扩展类。

Main Class: 主类:

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



}

In this class, I'm called my Toolbar class and add it to JFrame . 在这个类中,我称之为我的Toolbar类并将其添加到JFrame

My ToolBar Class: 我的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;

}

Now, I going to create an ActionListener to search. 现在,我将创建一个ActionListener来搜索。 So, I want to add that ActionListener to that JPanel ( ToolBar ). 所以,我想将ActionListener添加到该JPanelToolBar )。 However, I do not have object that class for that. 但是,我没有那个类的对象。

I created an ActionListener . 我创建了一个ActionListener

Use Action to encapsulate the functionality of your JToolBar components, as suggested in this example . 使用Action来封装JToolBar组件的功能,如本例所示

图片

You have to extend JPanel in order to fit your needs: 您必须扩展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
  }

}

Then you can use your custom JPanel elsewhere: 然后您可以在其他地方使用自定义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