以下是该方案: 我创建了一个可以在主面板中删除或隐藏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
}
}
答案 0 :(得分:0)
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!
}
}
答案 1 :(得分:0)
通过查看您的代码,我假设您已经创建了一个新对象
使用代码private MainFrame mainFrame = new MainFrame();
相反,您应该将此对象传递给您调用mehtod 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
}
}