当前位置: 首页 > 知识库问答 >
问题:

addPropertyChangeListener() to JFrame from a JPanel on a JTabbedPane

诸腾
2023-03-14

我正在创建一个具有多个选项卡(JTabbedPane)的程序,在选项卡中有一个JPanel,上面打开了我所有的conent。当我按开始(JButton)时,我创建了一个新的任务实例(一个扩展Swingworker的类),我想把我所有的菜单项设置为启用(false)。这是在JFrame上。

但我无法从Jpanel访问JFrame

控制器类别:

public class Controller {
    private Task task;

    public Controller() {
        newTask();
    }

    public void newTask(){
        task = new Task();
    }

    public Task getTask() {
        return task;
    }
}

框架类:

public class Frame extends JFrame implements PropertyChangeListener {

    private Controller controller;

    public Frame(String title, Controller controller) {
        super(title);
        this.controller = controller;
        controller.getTask().addPropertyChangeListener(this);
        JTabbedPane tabbedPane = new JTabbedPane();
        TabbedPane0 tabbedPane0 = new TabbedPane0(controller);
        JPanel jPanel = new JPanel();
        tabbedPane.add(tabbedPane0);
        tabbedPane.add(jPanel);
        add(tabbedPane);
        setSize(400, 500);
        setVisible(true);
        controller.getTask().TestPropertyChange();

    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        if (evt.getPropertyName() == "changed") {
            System.out.println("Changed property, disabled all MenuItems that I added on this FRAME");
        }else if(evt.getPropertyName().equals("test")){
        System.out.println("Tested");
    }
    }
}

TabbedPane0类:

public class TabbedPane0 extends JPanel {

    private Controller controller;

    public TabbedPane0(Controller controller) {
        this.controller = controller;
        JButton  button = new JButton("Start");
        add(button);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                controller.newTask();
                /*My frame needs to be added to the TaskPropertyChangeListeners but I can't acces it*/
                controller.getTask().addPropertyChangeListener(Frame);
            }
        });
    }
}

任务类:

public class Task extends SwingWorker<Void, Void> {

    @Override
    protected Void doInBackground() throws Exception {
        System.out.println("Task Is executed");
        return null;
    }

    public void TestPropertyChange(){
        firePropertyChange("test", null,null);
    }
}

运行类:

public class Run {

    public static void main(String[] args) {
        Controller controller = new Controller();
        new Frame("StackOverFlow Example TabbedPane", controller);
    }
}

共有1个答案

祁远
2023-03-14

我发现我可以用这个:

这将得到我的父JFrame,我的JTabbedPane/Jpanel将被添加到其中

controller.getTask().addPropertyChangeListener((JFrame) SwingUtilities.getWindowAncestor(FolderCreatorTab.this));
 类似资料:

相关问答

相关文章

相关阅读