2017-06-13 12 views
0
public class MyClass extends JFrame implements ActionListener { 

public MyClass() { 
    super("Frame Window"); 
    setLayout(new FlowLayout()); 
    setSize(700, 500); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    JButton setInv = new JButton("set invisible"); 
    setInv.setVisible(true); 
    setInv.setPreferredSize(new Dimension(50, 50)); 
    add(setInv); 

} 

public static void main(String[] args) { 
    MyClass obj = new MyClass(); 
    obj.setVisible(true); 

} 

public void actionPerformed(ActionEvent e) { 
    if (e.getActionCommand() == "set invisible") { 


    // I want an Accessor method for the parent JFrame and then I want to 
    // set it invisible here! 

    } 
} 
} 

一個人建議getParent()方法,但它不工作,因爲我想要的! getParent()回報在這種情況下,JFrame我覺得有些容器..在java中有沒有Accessor方法來獲取在我的類的構造函數中初始化的當前JFrame對象?

我已經試過getParent().setInvisible(false); 但沒有任何反應.. 我知道這是錯誤在我的邏輯或東西,但我應該怎麼辦?

Java很靈活,但在很多方面都有例外!

有一件事是,如果我不從JFrame擴展MyClass並創建一個公共實例JFrame,然後setVisible(false);可以通過其參考調用! 但我不想這樣做......因爲我已經做了很多課程的項目,我不想像這樣改變我的代碼... 任何幫助傢伙!

+3

的[獲取在Java應用程序的任何/所有活動JFrames?(可能的複製https://stackoverflow.com/questions/7364535/get-any-all-active- jframes-in-java-application) – Berger

+0

也看看這個:https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – Berger

+0

沒有用.. JFrame沒有隱藏或任何! –

回答

0

您還沒有在您的JButton中添加ActionListener。另外,你不會在ActionListener中處置或隱藏你的JFrame

附註:StringObject。使用String::equals而不是==

public class MyClass extends JFrame implements ActionListener { 

    public MyClass() { 
     super("Frame Window"); 
     setSize(700, 500); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     JButton setInv = new JButton("set invisible"); 
     setInv.addActionListener(this); 
     add(setInv); 
    } 

    public static void main(String[] args) { 
     MyClass obj = new MyClass(); 
     obj.setVisible(true); 

    } 

    public void actionPerformed(ActionEvent e) { 
     if ("set invisible".equals(e.getActionCommand())) { 
      dispose(); 
     } 
    } 
} 
0

只需

if (e.getActionCommand() == "set invisible") { 
     setVisible(false); // or this.setVisible(false); 
} 
相關問題