它们制作方法之外的绘制按钮?

时间:2016-04-04 22:20:57

标签: java swing jbutton

基本上,我绘制了主要方法中的所有代码。我正在尝试创建一个开始菜单,所以我希望能够有一个方法(名为drawMenu),我可以运行以绘制井字游戏按钮。

更简短的解释,如何在此drawMenu方法中绘制此主要方法之外的按钮?

package myClass;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.tools.ToolProvider;

public class mainClass {


    //Boolean switcher for playing/not


    //Create panel sides for action listeners
    enum ESide {
              tleft, tmid, tright,
              mleft, mmid, mright,
              bleft, bmid, bright,
            };

public static void main(String[] args) {

    //Objects

    //create window
    JFrame mainWindow = new JFrame("Tic Tac Toe");
    //properties of mainWindow
    mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainWindow.setSize(600, 600); // buttons will fill entirely, 200x200      buttons
    mainWindow.setLayout(new GridLayout(3, 3));

    //create buttons
    JButton startButton = new JButton("Start");
    JButton topLeft = new JButton("");
    JButton topMid = new JButton("");
    JButton topRight = new JButton("");
    JButton midLeft = new JButton("");
    JButton midMid = new JButton("");
    JButton midRight = new JButton("");
    JButton botLeft = new JButton("");
    JButton botMid = new JButton("");
    JButton botRight = new JButton("");

    //Definitions
    final Map<ESide, Boolean> board = new HashMap<>();
    for (ESide side : ESide.values()) {
        board.put(side, false);
    }
    //Dimensions
    Dimension selectionButtonSize = new Dimension(100,25);
    Dimension buttonSize = new Dimension(200,200);

    //Action listener

topLeft.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt)
        {
            if (board.get(ESide.tleft).booleanValue() == false) {
                topLeft.setText("X");
                board.put(ESide.tleft, true);
            }
        }

  });

topMid.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt)
        {
            if (board.get(ESide.tmid).booleanValue() == false) {
                topMid.setText("X");
                board.put(ESide.tmid, true);
            }
        }

  });

topRight.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt)
              {
                  if (board.get(ESide.tright).booleanValue() == false) {
                      topRight.setText("X");
                      board.put(ESide.tright, true);
                  }
              }

  });

midLeft.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt)
              {
                  if (board.get(ESide.mleft).booleanValue() == false) {
                      midLeft.setText("X");
                      board.put(ESide.mleft, true);
                  }
              }

  });

midMid.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt)
              {
                  if (board.get(ESide.mmid).booleanValue() == false) {
                      midMid.setText("X");
                      board.put(ESide.mmid, true);
                  }
              }

  });

midRight.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt)
              {
                  if (board.get(ESide.mright).booleanValue() == false) {
                      midRight.setText("X");
                      board.put(ESide.mright, true);
                  }
              }

  });

botLeft.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt)
              {
                  if (board.get(ESide.bleft).booleanValue() == false) {
                      botLeft.setText("X");
                      board.put(ESide.bleft, true);
                  }
              }

  });

botMid.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt)
              {
                  if (board.get(ESide.bmid).booleanValue() == false) {
                      botMid.setText("X");
                      board.put(ESide.bmid, true);
                  }
              }

  });

botRight.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt)
              {
                  if (board.get(ESide.bright).booleanValue() == false) {
                      botRight.setText("X");
                      board.put(ESide.bright, true);
                  }
              }

  });



drawMenu();
mainWindow.setVisible(true); // draw it



}

public static void drawMenu() {
    System.out.println("Drawing menu button");
    //I want to be able to access the buttons to draw them here.

}

}

1 个答案:

答案 0 :(得分:3)

建议:从当前的主要方法中获取所有内容

而是创建一个符合OOP的类,它具有非静态实例JButton字段以及您需要的任何其他字段,在此类的构造函数中创建GUI,并使用main方法简单地创建此类的实例,放置它进入一个JFrame(如果它是一个JPanel,应该是它),然后将其设置为可见。这里的关键概念是使用面向对象技术,因为Java首先是面向对象的编程语言,通过这样做,您将减少当前的复杂性,尤其是未来的复杂性。

例如,

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class SimpleTicTacToe extends JPanel {
    private static final int SIDE = 3;
    private static final float BTN_FONT_SIZE = 64f;
    public static final Color X_COLOR = Color.RED;
    public static final Color O_COLOR = Color.BLUE;
    private boolean xTurn = true;
    private JButton[][] buttonGrid = new JButton[SIDE][SIDE];

    public SimpleTicTacToe() {
        JPanel btnPanel = new JPanel(new GridLayout(SIDE, SIDE));
        for (int i = 0; i < buttonGrid.length; i++) {
            for (int j = 0; j < buttonGrid[i].length; j++) {
                buttonGrid[i][j] = new JButton(new TicTacToeBtnAction());
                buttonGrid[i][j].setFont(buttonGrid[i][j].getFont().deriveFont(Font.BOLD, BTN_FONT_SIZE));
                btnPanel.add(buttonGrid[i][j]);
            }
        }

        JPanel bottomPanel = new JPanel();
        bottomPanel.add(new JButton(new ResetAction("Reset", KeyEvent.VK_R)));

        setLayout(new BorderLayout());
        add(btnPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.PAGE_END);
    }

    class TicTacToeBtnAction extends AbstractAction {
        public TicTacToeBtnAction() {
            super("   ");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            JButton btn = (JButton) e.getSource();
            String btnText = btn.getText().trim();
            if (!btnText.isEmpty()) {
                return;
            }
            if (xTurn) {
                btn.setForeground(X_COLOR);
                btn.setText("X");
            } else {
                btn.setForeground(O_COLOR);
                btn.setText("O");
            }
            xTurn = !xTurn;
        }
    }

    private class ResetAction extends AbstractAction {
        public ResetAction(String name, int mnemonic) {
            super(name);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            for (JButton[] jButtons : buttonGrid) {
                for (JButton jButton : jButtons) {
                    jButton.setText("");
                }
            }
            xTurn = true;
        }
    }

    private static void createAndShowGui() {
        SimpleTicTacToe mainPanel = new SimpleTicTacToe();

        JFrame frame = new JFrame("Tic Tac Toe");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGui();
        });
    }
}

是的,正如FredK建议的那样 - 确保在Swing事件线程上启动所有Swing应用程序(如上所示)。