【问题标题】:Opening a new JFrame and close previous after clicking button单击按钮后打开一个新的 JFrame 并关闭上一个
【发布时间】:2015-03-04 17:26:14
【问题描述】:

如何编写一个按钮,当单击该按钮时,会关闭当前的JFrame 并打开一个新的?

这是我目前所拥有的,但旧框架保持打开状态:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    practise1 s = new practise1();
    s.setVisible(true);
} 

我曾尝试在第一个 { 之后使用 .close(),但它给了我一个错误。

【问题讨论】:

标签: java swing jframe jbutton


【解决方案1】:

如果您打算以后使用原始 JFrame,请在原始 JFrame 上使用setVisible(false)。如果您打算关闭第一个 JFrame 并且不再重复使用它,您可以使用dispose()

【讨论】:

  • 有时最好将 OP 引导到正确的路径上,而不是回答他们的确切问题。这是其中之一。事实上,这个建议正在将他们推向他们不应该遵循的道路,并且会导致许多问题。
【解决方案2】:
  public void actionPerformed(ActionEvent e)
  {
    if(e.getSource () == button)
    {
      test = new JFrame();
      test.setSize(300,300);
      test.setVisible (true);
      this.dispose();

    }
  }

在创建新框架后处理。

【讨论】:

  • 有时最好将 OP 引导到正确的路径上,而不是回答他们的确切问题。这是其中之一。事实上,这个建议正在将他们推向他们不应该遵循的道路,并且会导致许多问题。
  • OP 要求为多个 JFrame 提供解决方案。当然,多帧不是最好的解决方案。而且我确信 OP 不是 GUI 专家,所以为什么不让 OP 玩多个框架呢? OP 迟早会注意到,多帧太难维护了。
  • 如果 OP 询问如何在脚上射击自己。你会帮忙吗?
【解决方案3】:

感谢大家的帮助。我使用 this.dispose();方法

【讨论】:

    【解决方案4】:

    假设当前 Frame 是 FirstFrame 并单击 JButton 转到 NewFrame

    import javax.swing.*;
    
    public class FirstFrame extends Jframe implements ActionListener{
    
    
      JButton button;    
    
      public FirstFrame(){
       setVisible(true);
       setSize(500,500);
    
        button=new JButton("Click me");
        button.addActionListner(this);
       add(button);     
      }
    
      public static void main(String[] args)
      {
       new FirstFrame();
      }
    
      public void actionPerformed(ActionEvent e)
       {
       if(e.getSource()==button)
        {
            NewFrame nf=new NewFrame();    // Clicking on the Button will OPEN new Frame in NewFrame.java file 
            dispose();  //this method will close the FirstFrame 
         }
       }
    
    
    }
    

    【讨论】:

      【解决方案5】:

      您只需将其放入您的代码中:

      (这里的例子是 JButton 使用 ActionPerformed 方法来做到这一点)

      /**************************************************** ************************/

      private void openBTNActionPerformed(java.awt.event.ActionEvent evt) {                                                  
              dispose();
              FrameTarget t = new FrameTaregt();
              t.setVisible(true);
              //set the size : 1250 pixels de width and 720 pixels de height
              t.setSize(1250, 720);
              //make the frame in the center wuth this 
              t.setLocationRelativeTo(null);
              t.setResizable(true);     
      
      }
      
                                                   
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-25
        相关资源
        最近更新 更多