我有一个国际象棋游戏。
我已经写了3个类。
第一个是游戏类(包括棋盘、棋子等)。
另一个是菜单类(例如新建、打开、设置时间等按钮)。
两个类都使用JFrame。
我想把上述两个类放到第三个类中。例如,游戏窗口在左边,菜单在右边。 第三个类还会通过JFrame显示整个应用程序。
如何实现这一点?
两个类都使用JFrame。
我想把上述两个类放到第三个类中。例如,游戏窗口在左边,菜单在右边。 第三个类还会通过JFrame显示整个应用程序。
如何实现这一点?
你不能将一个JFrame放置在另一个JFrame内。在这里,你有几个设计选择。你可以将你的JFrames更改为JPanels,这可能是最简单的更改。另一方面,你可以考虑使用内部框架。
在您的情况下,我建议您使用可以添加到JFrame中的JInternalFrame。请尝试以下代码,希望它有效:
package demo;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
public class Demo {
public static void main(String[] args) {
JFrame jf=new JFrame();
jf.setLayout(null);
jf.setSize(1280, 720);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JInternalFrame jInternalFrame=new JInternalFrame();
jInternalFrame.setLocation(100, 100);
jInternalFrame.setSize(500, 300);
jInternalFrame.setTitle("Internal frame");
jInternalFrame.setVisible(true);
jInternalFrame.setClosable(true);
jInternalFrame.setResizable(true);
jf.add(jInternalFrame);
jf.repaint();
}
}
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);
}
}
Game
窗口内容放在一个JPanel
上,而Menu
则放在另一个JPanel
上。这样你就可以将它们部署到任何地方。 - MadProgrammer