简体   繁体   English

使用动作侦听器在同一类中调用void函数

[英]use actionlistener to call void function in same class

I have problem to use action listener to call function void in same class. 我在使用动作侦听器在同一个类中调用void时遇到问题。

example.. code: 示例..代码:

public class Product extends JPanel {

    JButton add;
    JPanel pAdd;
    JLabel test;
    JFrame frame;

    public Product() {
        add = new JButton("Add Product");
        add.addActionListener(new ButtonListener());

        add(add);
    }

    public void panelAdd(){
        pAdd = new JPanel();
        pAdd.add(new JLabel("try"));
        add(pAdd);

    }

    private class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            panelAdd();
        }
    }
}

How to make call the panelAdd void method? 如何调用panelAdd void方法?

If you put 如果你把

 System.out.println("hi");

to

public void panelAdd(){
  System.out.println("hi");
   pAdd = new JPanel();
   pAdd.add(new JLabel("try"));
   add(pAdd);

} }

you will see hi printed to your console , your code are working, but you have problem in Layout . 您会看到喜好打印到您的控制台,您的代码正在运行,但是Layout中存在问题。

When you add components to visible JFrame / JPanel /other components, you neet to call revalidate() and repaint() methods after adding. 将组件添加到可见的JFrame / JPanel /其他组件时,添加后无需调用revalidate()repaint()方法。 Change your panelAdd() like next: 如下更改您的panelAdd()

public void panelAdd(){
    pAdd = new JPanel();
    pAdd.add(new JLabel("try"));
    add(pAdd);
    revalidate();
    repaint();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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