JFrame inside another JFrame

后端 未结 5 682
[愿得一人]
[愿得一人] 2020-12-19 10:55

I have a game of chess. I have written 3 classes. 1st if for game. (chessboard, pieces, and so on) And another one is for menu. (buttons like new, open, set time)

Bo

5条回答
  •  醉梦人生
    2020-12-19 11:08

    The best thing to do would be to leave the outer frame as it is and change the inner contents to JPanels. When I wrote Chess, I had an outer frame which extended JFrame, and inner panel that extended JPanel on which I placed the board. The board itself was comprised of 64 JButtons.

    Given your description, I think this would be a good starting point:

    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();
        }
    }
    

    Also, a word of warning:

    Fully implementing the logic of Chess is very difficult, no matter what you do for the graphics.

    Hope this helps!

提交回复
热议问题