棋盘没有显示?申请部分只是黑色?

时间:2015-03-08 22:26:39

标签: java swing

首先,我想说我明白我问了很多,所以任何帮助都会受到赞赏,我感谢你的时间。我非常感激。

无论如何,我正在为我的A2课程创建一个游戏,通常称为Checkers。我已经完成了我的代码,一切都按照我的计划进行,除了CheckerBoard本身以及checkerpieces似乎没有显示。

我的董事会应该出现的部分只是一个黑色的空间。虽然我的电路板似乎没有显示,但我在其上执行的所有操作(例如单击某个部分)都会产生计划的响应,虽然我已经检查了我的代码,但我无法弄清楚我做错了什么。

无论如何,如果有人可能发现我的错误或者给我一些建议,我将非常感激。谢谢

public class CheckerBoard extends JPanel implements ActionListener, MouseListener {
    // Main routine that opens an Applet that shows a CheckerBoard
    public static void main(String[] args) {
        JFrame application = new JFrame("Checkers"); // Sets the title at the top of the application as 'Checkers'
        JMenuBar bar = new JMenuBar(); // Adds the Menu Bar
        JMenu fileMenu = new JMenu("File"); // Adds a File Tab to the Menu Bar
        JMenu helpMenu = new JMenu("Help"); // Adds a Help Tab to the Menu Bar
        JMenuItem exit = new JMenuItem("Exit"); // Adds the Exit sub-tab as an Item of the JMenu
        JMenuItem mainMenu = new JMenuItem("Main Menu"); // Adds the Main Menu sub-tab as an Item of the JMenu
        final JMenuItem Rules = new JMenuItem("Rules"); // Adds the Rules of Checkers sub-tab as an Item of the JMenu
        helpMenu.add(Rules); // Adds the Rules of Checkers tab into the Help tab
        fileMenu.add(mainMenu);// Adds the Main Menu sub-tab into the File tab 
        fileMenu.addSeparator(); // Adds a line in between the Main Menu sub-tab and the Exit sub-tab
        fileMenu.add(exit); // Adds the Exit sub-tab into the Menu tab
        bar.add(fileMenu); // Adds the Menu tab to the Menu bar
        bar.add(helpMenu); // Adds the Help tab to the Menu Bar
        application.setJMenuBar(bar); // Adds the Menu Bar to the application window
        Rules.addActionListener(new ActionListener() // Adds a new ActionListener to the Rules sub-tab
        {
            public void actionPerformed(ActionEvent ev)
        {
                JOptionPane.showMessageDialog(Rules,
                        "- Pieces must always move diagonally\n" +
                        "- Single pieces are limited to forward moves\n" +
                        "- Kings may move both forward and backward\n" +
                        "- When a piece is captured, it is removed from the board\n" +
                        "- If a player is able to make a capture, there is no option, the jump must be made\n" +
                        "- When a piece reaches the opponents end of the board, it is crowned and becomes a King",
                        "Rules for Checkers",
                        JOptionPane.PLAIN_MESSAGE);
        }
        }); //This has added a JOptionPane action when my Rules sub-tab is clicked, this displays the message dialog of the JOptionPane which can be seen
        exit.addActionListener(new ActionListener() // Adds an ActionListener to the Exit Sub-tab
        {
            public void actionPerformed(ActionEvent ev)
            {
                System.exit(0); // This means that when the Exit sub-tab is clicked, it will exit the application 
            }
        });
        CheckerBoard content = new CheckerBoard(); // Sets the CheckerBoard values into the content to be used in the next line
        application.setContentPane(content); // Container holds the values together, Content pane of the CheckerBoard
        application.pack();  // Use preferred size of content to set size of application.
        Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
        application.setLocation( (screensize.width - application.getWidth())/2,
                (screensize.height - application.getHeight())/2 );
        application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); // Sets so that the application can be exited when the application is closed
        application.setResizable(false);  // This makes it so that the user can't change the application's size.
        application.setVisible(true); // Sets it so that the application can actually be seen
    }
    private JButton NewGameButton;  // Button for starting a new game.
    private JButton ResignButton;   // Button that a player can use to end the game by resigning
    private JLabel MessageDisplay;  // Label for displaying messages to the user.

    public CheckerBoard()  {
// This is going to be a constructor, this constructor will set the layout manager for the panel to be null, it will then add components to the panel
// and it will set their bounds.

    setLayout(null);  // So that it will match my requirement specification, I will do the layout myself
    setBackground(new Color(0,120,0));  // Dark Green Background colour.
    setPreferredSize(new Dimension(350,250)); // The size of the Panel

    BoardComplete checkerboardData = new BoardComplete();
    add(checkerboardData); // This will create the components and add them to the content pane
    add(NewGameButton);
    add(ResignButton);
    add(MessageDisplay);

 // I will now have to produce a method to set the position and size of each component by calling its setBounds() method
    checkerboardData.setBounds(20,20,164,164); // Sets the board dimensions
    NewGameButton.setBounds(210, 60, 120, 30); 
    ResignButton.setBounds(210, 120, 120, 30); 
    MessageDisplay.setBounds(20, 200, 350, 30); 
    }   

    public class BoardComplete extends JPanel implements ActionListener, MouseListener {

    DataForCheckers checkerboardData; // This is where the data for the checkerboard is going to be kept, this board will be responsible for the
                        // generating of the lists of the legal moves then I will define at a later stage.


    boolean CheckerMatchInProgress; // In some of the actions I will be creating, I will have to check whether a game is in progress
                            // therefore this is a boolean value as it is either true or false, only two possible outcomes. 

    // The next three variables as seen below will only be valid when the game is in progress

    int ChosenRow, ChosenColumn;   // If the current player has selected a piece to
                                    //     move, these give the row and column
                                    //     containing that piece.  If no piece is
                                    //     yet selected, then ChosenRow is -1.

    int ChosenPlayer;      // This will check which user turn it is, there will be two possible values which will include DataForCheckers.RED and Checkers.Data.BLACK


    DataForMoves[] LegalMoves;  // An array containing the legal moves for the
                                //   current player.

    // The constructor will create the buttons and the labels. It will
    // listen for mouse clicks and for clicks on the buttons. It will create
    // the board and start the first game. 

    BoardComplete() {
        setBackground(Color.BLACK);
        addMouseListener(this);
        ResignButton = new JButton("Resign");
        ResignButton.addActionListener(this);
        NewGameButton = new JButton("New Game");
        NewGameButton.addActionListener(this);
        MessageDisplay = new JLabel("",JLabel.CENTER);
        MessageDisplay.setFont(new  Font("Serif", Font.BOLD, 14));
        MessageDisplay.setForeground(Color.green);
        checkerboardData = new DataForCheckers();
    }       

    // Now I will have to draw the checkerboard pattern in Gray and LightGray
    // Just like with my CheckerBoard Class, this will draw the checkers, and if
    // a game is in progress, it will highlight the legal moves that the user can make.

    public void PaintCheckerBoard(Graphics g) {

        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // This will draw a two-pixel black border around the edges of the canvas. 

        g.setColor(Color.black);
        g.drawRect(0,0,getSize().width-1,getSize().height-1);
        g.drawRect(1,1,getSize().width-3,getSize().height-3);

        // Draw the squares of the checkerboard and the checkers.

        for (int row = 0; row < 8; row++) {
            for (int col = 0; col < 8; col++) {
                if ( row % 2 == col % 2 )
                    g.setColor(Color.LIGHT_GRAY);
                else
                    g.setColor(Color.GRAY);
                g.fillRect(2 + col*20, 2 + row*20, 20, 20);
                switch (checkerboardData.PieceLocation(row,col)) {
                case DataForCheckers.RED:
                    g.setColor(Color.RED);
                    g.fillOval(4 + col*20, 4 + row*20, 15, 15);
                    break;
                case DataForCheckers.BLACK:
                    g.setColor(Color.BLACK);
                    g.fillOval(4 + col*20, 4 + row*20, 15, 15);
                    break;
                case DataForCheckers.RED_KING:
                    g.setColor(Color.RED);
                    g.fillOval(4 + col*20, 4 + row*20, 15, 15);
                    g.setColor(Color.WHITE);
                    g.drawString("K", 7 + col*20, 16 + row*20);
                    break;
                case DataForCheckers.BLACK_KING:
                    g.setColor(Color.BLACK);
                    g.fillOval(4 + col*20, 4 + row*20, 15, 15);
                    g.setColor(Color.WHITE);
                    g.drawString("K", 7 + col*20, 16 + row*20);
                    break;
                }
            }
        }
    }  // end PaintCheckerBoard()

我知道这有很多要问,但任何帮助都会非常感激,我将非常感激。非常感谢你

1 个答案:

答案 0 :(得分:2)

基本上,没有任何内容可以调用您的PaintCheckerBoard方法。

检查Painting in AWT and SwingPerforming Custom Painting,了解有关绘画如何在Swing中工作的更多详细信息。

基本上,您需要覆盖BoardComplete&#39; paintComponent并从中执行自定义绘画

话虽如此,使用GridLayout

可能更容易实现

避免使用null布局,像素完美布局是现代ui设计中的一种幻觉。影响组件个体大小的因素太多,您无法控制。 Swing旨在与布局管理器一起工作,放弃这些将导致问题和问题的终结,您将花费越来越多的时间来纠正