JFrame在另一个JFrame中

我有一盘棋。 我写过3节课。 如果是比赛,第1名。 (棋盘,棋子等)另一个是菜单。 (按钮如新,开,设定时间)

他们都使用JFrame。

我想把上面提到的两个类都放到第三课。 例如,游戏窗口位于左侧,菜单位于右侧。 第三节课也将展示JFrame的整个应用程序。

怎么做?

你不能把一个JFrame放在另一个JFrame中。 你有几个设计选择。 您可以将JFrame更改为JPanel。 这可能是最容易的改变。 另一方面,您可以查看使用内部框架 。

你可以使用JPanels。 这样更简单…使用JFrame作为主窗口,菜单项使用其中的JPanel。 搜索有关JPanel用法的教程。

最好的办法是保持外框不变,并将内部内容更改为JPanels。 当我写国际象棋时,我有一个扩展JFrame的外框,以及扩展我放置电路板的JPanel的内部面板。 董事会本身由64个JButtons组成。

鉴于您的描述,我认为这将是一个很好的起点:

 package data_structures; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; @SuppressWarnings("serial") public class Chess extends JFrame implements ActionListener { private JButton[][] tiles; public Chess() { setTitle("Chess"); setSize(500, 500); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); setLayout(new BorderLayout()); JPanel board = new JPanel(); board.setLayout(new GridLayout(8, 8)); tiles = new JButton[8][8]; for(int y = 0; y < tiles.length; y++) { for(int x = 0; x < tiles[y].length; x++) { tiles[x][y] = new JButton(); tiles[x][y].setActionCommand(x + " " + y); tiles[x][y].addActionListener(this); board.add(tiles[x][y]); } } add(board, BorderLayout.CENTER); JPanel options = new JPanel(); options.setLayout(new GridLayout(1, 3)); JButton newGame = new JButton("New"); newGame.addActionListener(this); options.add(newGame); JButton openGame = new JButton("Open"); openGame.addActionListener(this); options.add(openGame); JButton setTime = new JButton("Set Time"); setTime.addActionListener(this); options.add(setTime); add(options, BorderLayout.SOUTH); revalidate(); } public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); System.out.println(command); revalidate(); } public static void main(String[] args) { new Chess(); } } 

还有一句警告:

无论你为图形做什么,完全实现国际象棋的逻辑是非常困难的。

希望这可以帮助!

我猜这就是你想要做的。

 public class OuterFrame extends JFrame { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { OuterFrame outerFrame = new OuterFrame(); outerFrame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public OuterFrame() { JFrame innerFrame = new JFrame(); innerFrame.setVisible(true); } } 

你有一个MainFrame(OuterFrame),你创建它。 但是,您在此MainFrame中创建了一个JFrame。 这不是一件好事,但它确实是一种在另一个中打开“JFrame”的方式。 这将在屏幕上显示两个“窗口”。 您可以在MainFrame中创建无数的JFrame。