GUI多帧切换

如何解决GUI多帧切换

| 我正在写一个二十一点游戏程序。这是一项我们不使用gui的任务,但是为了获得更多的荣誉,我正在这样做,我创建了两个框架,它们正起作用。在第二帧上,我希望能够在按下按钮时切换回第一帧。我该怎么做呢? 第一个窗口.............
import javax.swing.* ;
import java.awt.event.* ;
import java.awt.* ;
import java.util.* ;


public class BlackJackWindow1 extends JFrame implements ActionListener
{
  private JButton play = new JButton(\"Play\");
  private JButton exit = new JButton(\"Exit\");
  private JPanel pane=new JPanel();
  private JLabel lbl ;

  public BlackJackWindow1()
  {
    super();
    JPanel pane=new JPanel();
    setTitle (\"Black Jack!!!!!\") ;
    JFrame frame = new JFrame(\"\");

    setVisible(true);
    setSize (380,260) ;
    setLocation (450,200) ;
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) ;

    setLayout(new FlowLayout());
    play = new JButton(\"Start\");
    exit = new JButton(\"exit\");
    lbl = new JLabel (\"Welcome to Theodores Black Jack!!!!!\");

    add (lbl) ;
    add(play,BorderLayout.CENTER);
    play.addActionListener (this);
    add(exit,BorderLayout.CENTER);
    exit.addActionListener (this);
  }
  @Override
  public void actionPerformed(ActionEvent event)
  {
    // TODO Auto-generated method stub
    BlackJackWindow2 bl = new BlackJackWindow2();
    if (event.getSource() == play)
    {
      bl.BlackJackWindow2();
    }
    else if(event.getSource() == exit){
      System.exit(0);
    }
  }
第二个窗口...
import javax.swing.* ;

import java.awt.event.* ;
import java.awt.* ;
import java.util.* ;

public class BlackJackWindow2 extends JFrame implements ActionListener
{
  private JButton hit ;
  private JButton stay ;
  private JButton back;
  //private JLabel lbl;

  public void BlackJackWindow2() 
  {
    // TODO Auto-generated method stub
    JPanel pane=new JPanel();
    setTitle (\"Black Jack!!!!!\") ;
    JFrame frame = new JFrame(\"\");

    setVisible(true);
    setSize (380,200) ;
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) ;

    setLayout(new FlowLayout());
    hit = new JButton(\"Hit\");  
    stay = new JButton(\"stay\");
    back = new JButton(\"return to main menu\");

    // add (lbl) ;
    add(hit,BorderLayout.CENTER);  
    hit.addActionListener (this) ;
    add(stay,BorderLayout.CENTER);
    stay.addActionListener (this) ;
    add(back,BorderLayout.CENTER);
    back.addActionListener (this) ;
  }

  @Override
  public void actionPerformed(ActionEvent event) 
  {
    // TODO Auto-generated method stub
    BlackJackWindow1 bl = new BlackJackWindow1();
    if (event.getSource() == hit)
    {
      //code for the game goes here i will complete later
    }
    else if(event.getSource() == stay){
      //code for game goes here i will comeplete later.
    }
    else 
    {
      //this is where i want the frame to close and go back to the original.
    }
  }
}
    

解决方法

第二帧需要参考第一帧,以便可以将焦点设置回第一帧。 同样,您的类扩展了JFrame,但它们还在其构造函数中创建其他框架。     ,一些建议: 您正在将组件添加到使用FlowLayout的JPanel中,但在执行此操作时却使用BorderLayout常量,您不应该这样做,因为这样做没有意义:
  add(play,BorderLayout.CENTER);
相反,如果使用FlowLayout,只需添加不带这些常量的组件。 另外,您可能要考虑使用CardLayout并在单个JFrame中交换veiws,而不是交换JFrames。例如:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class FooBarBazDriver {
   private static final String INTRO = \"intro\";
   private static final String GAME = \"game\";
   private CardLayout cardlayout = new CardLayout();
   private JPanel mainPanel = new JPanel(cardlayout);
   private IntroPanel introPanel = new IntroPanel();
   private GamePanel gamePanel = new GamePanel();

   public FooBarBazDriver() {
      mainPanel.add(introPanel.getMainComponent(),INTRO);
      mainPanel.add(gamePanel.getMainComponent(),GAME);

      introPanel.addBazBtnActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            cardlayout.show(mainPanel,GAME);
         }
      });

      gamePanel.addBackBtnActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            cardlayout.show(mainPanel,INTRO);
         }
      });
   }

   private JComponent getMainComponent() {
      return mainPanel;
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame(\"Foo Bar Baz\");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new FooBarBazDriver().getMainComponent());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

class IntroPanel {
   private JPanel mainPanel = new JPanel();
   private JButton baz = new JButton(\"Baz\");
   private JButton exit = new JButton(\"Exit\");

   public IntroPanel() {
      mainPanel.setLayout(new FlowLayout());
      baz = new JButton(\"Start\");
      exit = new JButton(\"exit\");

      mainPanel.add(new JLabel(\"Hello World\"));
      mainPanel.add(baz);
      mainPanel.add(exit);

      exit.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            Window win = SwingUtilities.getWindowAncestor(mainPanel);
            win.dispose();
         }
      });
   }

   public void addBazBtnActionListener(ActionListener listener) {
      baz.addActionListener(listener);
   }

   public JComponent getMainComponent() {
      return mainPanel;
   }

}

class GamePanel {
   private static final Dimension MAIN_SIZE = new Dimension(400,200);
   private JPanel mainPanel = new JPanel();

   private JButton foo;
   private JButton bar;
   private JButton back;

   public GamePanel() {
      foo = new JButton(\"Foo\");
      bar = new JButton(\"Bar\");
      back = new JButton(\"return to main menu\");

      mainPanel.add(foo);
      mainPanel.add(bar);
      mainPanel.add(back);
      mainPanel.setPreferredSize(MAIN_SIZE);
   }

   public JComponent getMainComponent() {
      return mainPanel;
   }

   public void addBackBtnActionListener(ActionListener listener) {
      back.addActionListener(listener);
   }

}
    ,因为我必须自己测试它是否真的那么容易实现,所以我建立了这个简单的示例。它展示了您的问题的解决方案。 @jzd的答案略有启发(为此+1)。
import java.awt.Color;
import java.awt.HeadlessException;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class FocusChangeTwoFrames
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() 
        {
            @Override
            public void run()
            {   
                createGUI();
            }
        });
    }

    private static void createGUI() throws HeadlessException
    {
        final JFrame f2 = new JFrame();
        f2.getContentPane().setBackground(Color.GREEN);     
        final JFrame f1 = new JFrame();     
        f1.getContentPane().setBackground(Color.RED);
        f1.setSize(400,300);
        f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f1.setVisible(true);
        MouseListener ml = new MouseAdapter()
        {
            @Override
            public void mousePressed(MouseEvent e)
            {
                if(f1.hasFocus())
                    f2.requestFocus();
                else
                    f1.requestFocus();
            }
        };
        f1.addMouseListener(ml);
        f2.setSize(400,300);
        f2.setLocation(200,150);
        f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f2.setVisible(true);
        f2.addMouseListener(ml);
    }
}
享受,博罗。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-