2015-10-19 111 views
0

我在選項卡中創建了一個帶有多個選項卡(JTabbedPane)的程序,其中有一個JPanel,其中包含我所有的內容。當我按下start(JButton)時,我創建了Task的一個新實例(一個擴展Swingworker的類),並且我想將所有的menuItems設置爲啓用(false)。這是在JFrame上。從JTabbedPane上的JPanel向JFrame添加addPropertyChangeListener()

,但我不能從JPanel中達到的JFrame

控制器類:

public class Controller { 
    private Task task; 

    public Controller() { 
     newTask(); 
    } 

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

    public Task getTask() { 
     return task; 
    } 
} 

Frame類:

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

Run類:

public class Run { 

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

例如[Swing和PropertyChangeListener中的MVC](http://stackoverflow.com/q/8169964/714968) – mKorbel

回答

0

我發現我可以只使用這樣的:

這得到我父母的JFrame在我的JTabbedPane中的JPanel添加/到

controller.getTask().addPropertyChangeListener((JFrame) SwingUtilities.getWindowAncestor(FolderCreatorTab.this));