其他类中的Java Swing GUI

时间:2018-07-28 22:21:35

标签: java swing oop

我目前正在用Java开发第一个Swing项目。我想将GUI分为3个单独的类。我的主要班级TicTacToeGUI和另外两个班级:MenuBarBoard

我的菜单有问题。我不知道如何使它可见。代码正在编译,但菜单未显示。

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

委员会:

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

1 个答案:

答案 0 :(得分:-1)

您没有正确扩展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;

}