繁体   English   中英

从另一个类中删除jPanel

[英]removing jPanel from another class

这是场景:我创建了一个可以删除或隐藏主面板内的JPanel的函数,但是如果从另一个类调用它,它将无法正常工作。

该函数是:

public void hideLoginPanel(){
    mainPanel.removeAll();
    mainPanel.repaint();
}

我可以在此处进行设置变量值之类的任何设置,但删除mainPanel中的JPanel将不起作用。

这是调用该函数的另一个类的代码:

public class logService{
    private MainFrame frame = new MainFrame();
    private static logService dataService;

    public static logService getService() {
        if (dataService == null) {
            dataService = new logService();
        }
        return dataService
    }

    public void removePanel(){
        frame.hideLoginPanel // here's where I called the function
    }
}
import javax.swing.*;

public class Test extends JFrame {
    private JPanel nPanel;
    private JLabel label;

    Test() {
        setSize(300,300);
        nPanel = new JPanel();
        label = new JLabel("Hello!");
        nPanel.add(label);
        add(nPanel);
    }

    public void clear(JPanel panel) {
        panel.removeAll();
        panel.repaint();
    }

    public static void main(String[] args) {
        Test t = new Test();
        t.setVisible(true);
        t.clear(t.nPanel); //if you comment this line, you will see label said "Hello" to you!
    }
}

通过查看您的代码,我假设您已经通过使用代码private MainFrame mainFrame = new MainFrame();创建了MainFrame的新对象private MainFrame mainFrame = new MainFrame();

相反,您应该将此对象传递给调用hideLoginPanel()其他类。 可以在构造函数中传递对象。 看一下这两个类:

class MainFrame extends JFrame {
    public MainFrame() {
        this.setLayout(new BorderLayout());
        this.setBounds(50, 50, 200, 300);
        this.setVisible(true);
        JPanel jp = new JPanel();
        jp.setBackground(Color.BLUE);
        this.add(jp, BorderLayout.CENTER);
        LogService logService = new LogService(this); // This object should be used in your control where you want clear panel
        //logService.removePanel(); // Comment and uncomment this line to see the difference. Change in blue color
    }

    public void hideLoginPanel() {
        this.removeAll();
        this.repaint();
    }

    public static void main(String args[]) {
        new MainFrame();
    }
}

class LogService {
    private  MainFrame mainFrame;

    public LogService(MainFrame mainFrame) {
        this.mainFrame=mainFrame;
    }

    public void removePanel(){
        mainFrame.hideLoginPanel(); // here's where I called the function
    }
}

在此处输入图片说明

暂无
暂无

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

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