2011-09-07 261 views
3

我在java框架中有一个按钮,当它按下时,它从文本框中读取一个值,并将该字符串用作尝试连接到串行设备的端口名称。Java:Swing:按下按钮后隐藏框架

如果此连接成功,则方法返回true,否则返回false。如果它返回true,我希望框架消失。然后在其他类中指定的一系列其他框架将显示控制串行设备的选项。

我的问题是:按钮被连接到一个动作监听器,当按下这个方法时被调用。如果我尝试使用frame.setVisible(true);方法java抛出一个抽象按钮错误,因为我有效地告诉它在按钮按下方法退出之前消失了包含按钮的框架。删除frame.setVisible(true);允许程序正常运行,但我留下了一个不再有用的延续的连接框架。

如何在按下按钮时使框架消失?

package newimplementation1; 

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 


/** 
* 
* @author Zac 
*/ 

public class ConnectionFrame extends JPanel implements ActionListener { 


private JTextField textField; 
private JFrame frame; 
private JButton connectButton; 
private final static String newline = "\n"; 

public ConnectionFrame(){ 

    super(new GridBagLayout()); 

    textField = new JTextField(14); 
    textField.addActionListener(this); 
    textField.setText("/dev/ttyUSB0"); 

    connectButton = new JButton("Connect"); 

    //Add Components to this panel. 
    GridBagConstraints c = new GridBagConstraints(); 
    c.gridwidth = GridBagConstraints.REMAINDER; 

    c.fill = GridBagConstraints.HORIZONTAL; 
    add(textField, c); 

    c.fill = GridBagConstraints.BOTH; 
    c.weightx = 1.0; 
    c.weighty = 1.0; 
    add(connectButton, c); 



    connectButton.addActionListener(new ActionListener() { 

     public void actionPerformed(ActionEvent e) 
     { 

      boolean success = Main.mySerialTest.initialize(textField.getText()); 

      if (success == false) {System.out.println("Could not connect"); return;} 

      frame.setVisible(false); // THIS DOES NOT WORK!! 

      JTextInputArea myInputArea = new JTextInputArea(); 
      myInputArea.createAndShowGUI(); 

      System.out.println("Connected"); 


     } 
    }); 

} 

    public void actionPerformed(ActionEvent evt) { 

      // Unimplemented required for JPanel 

    } 

    public void createAndShowGUI() { 

    //Create and set up the window. 
    frame = new JFrame("Serial Port Query"); 
    frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); 


    //Add contents to the window. 
    frame.add(new ConnectionFrame()); 
    frame.setLocation(300, 0); 


    //Display the window. 
    frame.pack(); 
    frame.setVisible(true); 

      frame.addComponentListener(new ComponentAdapter() { 
     @Override 
     public void componentHidden(ComponentEvent e) { 
      System.out.println("Exiting Gracefully"); 
      Main.mySerialTest.close(); 
      ((JFrame)(e.getComponent())).dispose(); 
      System.exit(0); 
     } 
    }); 


} 

} 
+2

这是不可能的应用程序。应该使用多个'JFrame'。小型用户界面元素可能会弹出在“JDialog”或“JOptionPane”中,而“CardLayout”或各种Swing组件可用于在容器中包含多个UI(或“屏幕”)。 –

+1

为了更快提供更好的帮助,请发布[SSCCE](http://pscode.org/sscce.html)。 –

回答

4

你的问题是这一行:

frame.add(new ConnectionFrame()); 

你正在创建一个新的ConnectionFrame对象,从而显示了一个你的按钮尝试关闭的框架是不一样的,这是你问题的根源。

如果将其更改为,

//!! frame.add(new ConnectionFrame()); 
    frame.add(this); 

使两个JFrames是同一个,事情可能会更加顺畅。但是话说回来,你的整个设计闻起来很糟糕,我会以更多的面向对象和更不静态的方式重新考虑它。此外,使用对话框需要对话框,而不是框架,而不是对话框考虑通过CardLayout交换视图(JPanels)作为更好的选择。我为此创建了一个“哑巴”GUI,创建一个JPanel(在我的例子中,为了简单起见,它扩展了一个JPanel,但如果不是必要的话,我会避免扩展),而且我会让任何调用此代码的人决定如何通过某种控制来处理这些信息。

public interface ConnectionPanelControl { 

    void connectButtonAction(); 

} 
:对于如

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

@SuppressWarnings("serial") 
public class ConnectionPanel extends JPanel { 

    private JTextField textField; 
    private JButton connectButton; 
    private ConnectionPanelControl control; 

    public ConnectionPanel(final ConnectionPanelControl control) { 
     super(new GridBagLayout()); 
     this.control = control; 

     ActionListener listener = new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      if (control != null) { 
       control.connectButtonAction(); 
      } 
     } 
     }; 

     textField = new JTextField(14); 
     textField.addActionListener(listener); 
     textField.setText("/dev/ttyUSB0"); 

     connectButton = new JButton("Connect"); 

     GridBagConstraints c = new GridBagConstraints(); 
     c.gridwidth = GridBagConstraints.REMAINDER; 

     c.fill = GridBagConstraints.HORIZONTAL; 
     add(textField, c); 

     c.fill = GridBagConstraints.BOTH; 
     c.weightx = 1.0; 
     c.weighty = 1.0; 
     add(connectButton, c); 

     connectButton.addActionListener(listener); 
    } 

    public String getFieldText() { 
     return textField.getText(); 
    } 

} 

再次,简单的GUI之外的东西会在如何处理文本字段包含文本和什么做是显示此JPanel的GUI做决策

此外,您可能会在后台线程中进行任何连接,以免冻结GUI,可能是SwingWorker。也许这样的事情:

import java.awt.event.ActionEvent; 
import java.util.concurrent.ExecutionException; 

import javax.swing.*; 

@SuppressWarnings("serial") 
public class MyMain extends JPanel { 
    public MyMain() { 
     add(new JButton(new ConnectionAction("Connect", this))); 
    } 

    private static void createAndShowGui() { 
     JFrame frame = new JFrame("My Main"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(new MyMain()); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGui(); 
     } 
     }); 
    } 
} 

@SuppressWarnings("serial") 
class ConnectionAction extends AbstractAction { 
    private MyMain myMain; 
    private ConnectionPanel cPanel = null; 
    private JDialog dialog = null; 

    public ConnectionAction(String title, MyMain myMain) { 
     super(title); 
     this.myMain = myMain; 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     if (dialog == null) { 
     dialog = new JDialog(SwingUtilities.getWindowAncestor(myMain)); 
     dialog.setTitle("Connect"); 
     dialog.setModal(true); 
     cPanel = new ConnectionPanel(new ConnectionPanelControl() { 

      @Override 
      public void connectButtonAction() { 
       final String connectStr = cPanel.getFieldText(); 
       new MySwingWorker(connectStr).execute(); 
      } 
     }); 
     dialog.getContentPane().add(cPanel); 
     dialog.pack(); 
     dialog.setLocationRelativeTo(null); 
     } 
     dialog.setVisible(true); 
    } 

    private class MySwingWorker extends SwingWorker<Boolean, Void> { 
     private String connectStr = ""; 

     public MySwingWorker(String connectStr) { 
     this.connectStr = connectStr; 
     } 

     @Override 
     protected Boolean doInBackground() throws Exception { 
     // TODO: make connection and then return a result 
     // right now making true if any text in the field 
     if (!connectStr.isEmpty()) { 
      return true; 
     } 
     return false; 
     } 

     @Override 
     protected void done() { 
     try { 
      boolean result = get(); 
      if (result) { 
       System.out.println("connection successful"); 
       dialog.dispose(); 
      } else { 
       System.out.println("connection not successful"); 
      } 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } catch (ExecutionException e) { 
      e.printStackTrace(); 
     } 
     } 
    } 
} 
+1

再次来不及:-) – kleopatra

+1

谢谢所有人谁非常迅速地回复。我发布了这个问题,然后走了15分钟,认为如果我运气好的话可能会有1个回复......而且有4个! – Zac

+0

@Zac:请参阅上面的编辑我的答案。用于'windowForComponent'的 –

5

运行您的片段(在删除/调整自定义类的周围后),会抛出一个NPE。原因是你所访问的框架是空的。那是因为它从未设置。最好不要依赖于任何领域,让按钮找到它的顶层祖先和隐藏,像

 public void actionPerformed(final ActionEvent e) { 

      boolean success = true; 
      if (success == false) { 
       System.out.println("Could not connect"); 
       return; 
      } 

      Window frame = SwingUtilities.windowForComponent((Component) e 
        .getSource()); 
      frame.setVisible(false); //no problem :-) 

     } 
+0

+1。应该被接受为答案 –

1

你的代码将更具可读性,如果你命名的JFrame实例xxxFrame和JPanel的实例xxxPanel。命名JPanel实例xxxFrame使事情非常混乱。

如果粘贴了异常的堆栈跟踪,它也会有所帮助。

我怀疑问题来自frame为null的事实。这是由于这样的事实,所述帧字段在createAndShowGUI方法仅初始化,但此方法并不显示当前连接面板,但是一个新的,因此具有空帧字段:

ConnectionFrame firstPanel = new ConnectionFrame(); 
// The firstPanel's frame field is null 
firstPanel.createAndShowGUI(); 
// the firstPanel's frame field is now not null, but 
// the above call opens a JFrame containing another, new ConnectionFrame, 
// which has a null frame field 

createAndShowGUI的代码应该包含

frame.add(this); 

而不是

frame.add(new ConnectionFrame()); 
1

的Swing GUI的是更好地创造一次JFrame和另一Top-Level ContainersJDialogJWindow(默认情况下未饰),

简单的在这里例如

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class SuperConstructor extends JFrame { 

    private static final long serialVersionUID = 1L; 

    public SuperConstructor() { 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setPreferredSize(new Dimension(300, 300)); 
     setTitle("Super constructor"); 
     Container cp = getContentPane(); 
     JButton b = new JButton("Show dialog"); 
     b.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent evt) { 
       FirstDialog firstDialog = new FirstDialog(SuperConstructor.this); 
      } 
     }); 
     cp.add(b, BorderLayout.SOUTH); 
     JButton bClose = new JButton("Close"); 
     bClose.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent evt) { 
       System.exit(0); 
      } 
     }); 
     add(bClose, BorderLayout.NORTH); 
     pack(); 
     setVisible(true); 
    } 

    public static void main(String args[]) { 
     EventQueue.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       SuperConstructor superConstructor = new SuperConstructor(); 
      } 
     }); 
    } 

    private class FirstDialog extends JDialog { 

     private static final long serialVersionUID = 1L; 

     FirstDialog(final Frame parent) { 
      super(parent, "FirstDialog"); 
      setPreferredSize(new Dimension(200, 200)); 
      setLocationRelativeTo(parent); 
      setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); 
      setModalityType(Dialog.ModalityType.DOCUMENT_MODAL); 
      JButton bNext = new JButton("Show next dialog"); 
      bNext.addActionListener(new ActionListener() { 

       @Override 
       public void actionPerformed(ActionEvent evt) { 
        SecondDialog secondDialog = new SecondDialog(parent, false); 
       } 
      }); 
      add(bNext, BorderLayout.NORTH); 
      JButton bClose = new JButton("Close"); 
      bClose.addActionListener(new ActionListener() { 

       @Override 
       public void actionPerformed(ActionEvent evt) { 
        setVisible(false); 
       } 
      }); 
      add(bClose, BorderLayout.SOUTH); 
      pack(); 
      setVisible(true); 
     } 
    } 
    private int i; 

    private class SecondDialog extends JDialog { 

     private static final long serialVersionUID = 1L; 

     SecondDialog(final Frame parent, boolean modal) { 
      //super(parent); // Makes this dialog unfocusable as long as FirstDialog is visible 
      setPreferredSize(new Dimension(200, 200)); 
      setLocation(300, 50); 
      setModal(modal); 
      setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); 
      setTitle("SecondDialog " + (i++)); 
      JButton bClose = new JButton("Close"); 
      bClose.addActionListener(new ActionListener() { 

       @Override 
       public void actionPerformed(ActionEvent evt) { 
        setVisible(false); 
       } 
      }); 
      add(bClose, BorderLayout.SOUTH); 
      pack(); 
      setVisible(true); 
     } 
    } 
} 

更好才可以重新使用顶层容器,如在运行时创造了大量顶层容器的(可能的内存不足)