如何实现另一个类中的JavaSwing GUI?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (77)

以下是我编写的代码:

TicTacToeGUI:

package TicTacToee;

import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;

public class TicTacToeGUI {



    public TicTacToeGUI() {
        super();
        Board board = new Board();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    TicTacToeGUI window = new TicTacToeGUI();
                    //window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

Board:

package TicTacToee;

import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;

public class Board {

    private JFrame frame;
    private JButton[][] board;

    public Board(){
        initializeBoard();
    }



    public void initializeBoard() {
        frame = new JFrame();
        frame.setTitle("Tic Tac Toe v0.1");
        frame.setBounds(100, 100, 600, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new BorderLayout(0, 0));
        frame.setResizable(false);
        //Creating MENU
        MenuBar menuBar = new MenuBar();
        frame.setJMenuBar(menuBar);
        frame.setVisible(true);

        //JPanel panel = new JPanel();
        //panel.setBorder(new LineBorder(new Color(0, 0, 0), 2));
        //frame.getContentPane().add(panel, BorderLayout.CENTER);
        //panel.setLayout(new GridLayout(3, 3, 2, 2));


        //board = new JButton[3][3];


    }
}

package TicTacToee;

import javax.swing.*;

public class MenuBar extends JMenuBar{

    private JMenuBar menuBar;
    private JMenu menu;
    private JMenuItem newGame;
    private JMenuItem quit;


    public MenuBar(){
        initializeMenuBar();
    }

    public void initializeMenuBar(){
        //Create menu Bar
        menuBar = new JMenuBar();

        menu = new JMenu("MENU");
        menuBar.add(menu);

        newGame = new JMenuItem();
        menu.add(newGame);

    }
}
提问于
用户回答回答于

没有JMenuBar正确扩展,尝试这样的事情:

public void initializeMenuBar(){

    menu = new JMenu("MENU");
    this.add(menu);

    newGame = new JMenuItem();
    menu.add(newGame);

}

或者

public void initializeMenuBar(){
    //Create menu Bar
    menuBar = new JMenuBar();

    menu = new JMenu("MENU");
    menuBar.add(menu);

    newGame = new JMenuItem();
    menu.add(newGame);

    this = menuBar;

}

扫码关注云+社区

领取腾讯云代金券