如何在JPanel上绘画? [英] How to paint over a JPanel?

查看:159
本文介绍了如何在JPanel上绘画?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我(新手程序员)正在尝试在JPanel上绘制椭圆形.我正在尝试使用油漆方法.但是,它需要一个Graphics参数.当我将Graphics作为参数包含在内时,会得到NullPointerException,因为它为null,但是我不知道如何绘制椭圆形.我尝试重新粉刷,但是什么也没发生.任何帮助,将不胜感激.这是我的主要课程:

I (A novice programmer) am trying to paint an oval over a JPanel. I am trying to use the method paint. However, it requires a Graphics argument. I get a NullPointerException when I include my Graphics as a argument because it is null, but I do not know how else to paint the oval. I tried repaint instead but nothing happened. Any help would be appreciated. Here is my main class:

public class Checkers extends JPanel{
 public static final int BOARDSQUARES = 8;
 public static final int BOARDSIZE = 75;
   private JPanel[][] board;
   private final Point point1;
   private final LineBorder border1;
   public JFrame frame;
   checkerPiece piece = new checkerPiece(this);
   Graphics g;

public Checkers(){
    board = new JPanel[BOARDSQUARES][BOARDSQUARES];
    point1 = new Point (BOARDSIZE,BOARDSIZE);
    border1=new LineBorder(Color.BLACK, 1);

}


/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

     Checkers checkers = new Checkers();
   checkers.frame=checkers.createJFrame();

   checkers.board =checkers.createBoard(checkers.board, checkers.point1, checkers.border1);

  for (int y=0;y<BOARDSQUARES;y++){
      for (int x = 0;x<BOARDSQUARES;x++){
      checkers.frame.getContentPane().add(checkers.board[y][x]);

        }

  }

    checkers.paint(checkers.g);
}

private JPanel[][] createBoard (JPanel[][] board, Point point, LineBorder border1){
    for (int row = 0; row<BOARDSQUARES;row++){
        point.y=BOARDSIZE;
        for (int col = 0; col <BOARDSQUARES;col++){

            board[row][col] = new JPanel();
            board[row][col].setLocation(point);
            board[row][col].setVisible(true);
            board[row][col].setSize(BOARDSIZE,BOARDSIZE);
            board[row][col].setOpaque(true);
             if ((row%2==0&&col%2==0)||(row%2==1&&col%2==1)){
                board[row][col].setBackground(new Color (230,200,150));
            } else if ((row%2==0&&col%2==1)||(row%2==1&&col%2==0)) {

                 board[row][col].setBackground(new Color (165, 42,42) );
             }
             board[row][col].setBorder(border1);
                             point.y = point.y+BOARDSIZE;
        }
        point.x=point.x+BOARDSIZE;
    }

    return board;
}

private JFrame createJFrame (){
    JFrame mainFrame = new JFrame("Checkers");
    mainFrame.setSize(1000,1000);
    mainFrame.setVisible(true);
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  mainFrame.add(new Checkers());
return mainFrame;
}
 @Override
public void paint (Graphics g){
    System.out.println("hi");
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;

    piece.paint(g2d,board[0][0].getLocation().x,board[0][0].getLocation().y,Color.BLACK);

   }
}

另一个班上的必要片段(cherkerPiece片段):

A necessary snippet from my other class (cherkerPiece piece):

public void paint (Graphics2D g, int x, int y, Color color){
    g.setColor(color);
    g.fillOval(x, y, DIAMETER, DIAMETER);
}

谢谢您的帮助

推荐答案

要创建像跳棋游戏一样复杂的内容,您应该遵循

To create something as complex as a checkers game, you should follow the model / view / controller pattern when creating your Java Swing GUI.

我为棋盘格正方形创建了一个模型类,为棋盘格创建了另一个模型类.我为棋盘创建了一个模型类,并为容纳所有棋子创建了另一个模型类.

I created a model class for a checker board square and another model class for a checker piece. I created a model class for the checker board and another model class to hold all of the checker pieces.

我创建了一个视图类来绘制棋盘.我创建了另一个视图类来创建主窗口.

I created a view class to draw the checker board. I created another view class to create the main window.

我没有创建任何控制器类.这段代码仅向您展示如何绘制棋盘.我将所有的类放在一起以使其更容易粘贴代码.您应该将这些类分为单独的Java文件.

I did not create any controller classes. This code just shows you how to draw a checker board. I put all of the classes together to make it easier to paste the code. You should separate the classes into separate Java files.

package com.ggl.testing;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class CheckerBoard implements Runnable {

    private Board board;

    private CheckerBoardPanel checkerBoardPanel;

    private JFrame frame;

    private Pieces pieces;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new CheckerBoard());
    }

    public CheckerBoard() {
        this.board = new Board();
        this.pieces = new Pieces();
    }

    @Override
    public void run() {
        frame = new JFrame("Checker Board");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        checkerBoardPanel = new CheckerBoardPanel(board, pieces);
        frame.add(checkerBoardPanel);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public class CheckerBoardPanel extends JPanel {

        private static final long serialVersionUID = 3770663347384271771L;

        private Board board;

        private Pieces pieces;

        public CheckerBoardPanel(Board board, Pieces pieces) {
            this.board = board;
            this.pieces = pieces;
            this.setPreferredSize(board.getPreferredSize());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            Square[][] checkerBoard = board.getBoard();

            for (int row = 0; row < checkerBoard.length; row++) {
                for (int column = 0; column < checkerBoard[row].length; column++) {
                    Square square = checkerBoard[row][column];
                    Rectangle drawingRectangle = square.getDrawingRectangle();
                    g.setColor(square.getColor());
                    g.fillRect(drawingRectangle.x, drawingRectangle.y,
                            drawingRectangle.width, drawingRectangle.height);
                }
            }

            List<Piece> checkerPieces = pieces.getPieces();

            for (Piece checkerPiece : checkerPieces) {
                Point coordinate = checkerPiece.getCoordinate();
                Rectangle drawingRectangle = checkerBoard[coordinate.x][coordinate.y]
                        .getDrawingRectangle();

                int x = drawingRectangle.x + drawingRectangle.width / 2;
                int y = drawingRectangle.y + drawingRectangle.height / 2;
                int radius = board.getSquareWidth() * 2 / 6;

                g.setColor(checkerPiece.getColor());
                g.fillOval(x - radius, y - radius, radius + radius, radius
                        + radius);
            }
        }
    }

    public class Board {

        private static final int BOARD_WIDTH = 8;
        private static final int SQUARE_WIDTH = 64;

        private Square[][] board;

        public Board() {
            this.board = initalizeBoard(BOARD_WIDTH, SQUARE_WIDTH);
        }

        private Square[][] initalizeBoard(int boardWidth, int squareWidth) {
            Square[][] board = new Square[boardWidth][boardWidth];

            int x = 0;
            int y = 0;

            for (int row = 0; row < boardWidth; row++) {
                for (int column = 0; column < boardWidth; column++) {
                    Square square = new Square();
                    if (isLightSquare(row, column)) {
                        square.setColor(Color.WHITE);
                    } else {
                        square.setColor(Color.LIGHT_GRAY);
                    }

                    square.setCoordinate(new Point(row, column));
                    square.setDrawingRectangle(new Rectangle(x, y, squareWidth,
                            squareWidth));

                    board[row][column] = square;

                    x += squareWidth;
                }
                x = 0;
                y += squareWidth;
            }

            return board;
        }

        public boolean isLightSquare(int row, int column) {
            if (row % 2 == 0) {
                if (column % 2 == 0) {
                    return true;
                } else {
                    return false;
                }
            } else {
                if (column % 2 == 0) {
                    return false;
                } else {
                    return true;
                }
            }
        }

        public Dimension getPreferredSize() {
            int width = SQUARE_WIDTH * 8 + 1;
            return new Dimension(width, width);
        }

        public Square[][] getBoard() {
            return board;
        }

        public int getSquareWidth() {
            return SQUARE_WIDTH;
        }

    }

    public class Square {

        private Color color;

        private Point coordinate;

        private Rectangle drawingRectangle;

        public Point getCoordinate() {
            return coordinate;
        }

        public void setCoordinate(Point coordinate) {
            this.coordinate = coordinate;
        }

        public Rectangle getDrawingRectangle() {
            return drawingRectangle;
        }

        public void setDrawingRectangle(Rectangle drawingRectangle) {
            this.drawingRectangle = drawingRectangle;
        }

        public Color getColor() {
            return color;
        }

        public void setColor(Color color) {
            this.color = color;
        }

    }

    public class Pieces {

        private List<Piece> pieces;

        public Pieces() {
            this.pieces = addPieces();
        }

        private List<Piece> addPieces() {
            List<Piece> pieces = new ArrayList<Piece>();

            Piece piece = new Piece();
            piece.setColor(Color.RED);
            piece.setCoordinate(new Point(2, 1));
            pieces.add(piece);

            piece = new Piece();
            piece.setColor(Color.BLACK);
            piece.setCoordinate(new Point(5, 0));
            pieces.add(piece);

            // Add the rest of the red and black pieces here

            return pieces;
        }

        public List<Piece> getPieces() {
            return pieces;
        }

        public void addPiece(Piece piece) {
            this.pieces.add(piece);
        }
    }

    public class Piece {

        private Color color;

        private Point coordinate;

        public Color getColor() {
            return color;
        }

        public void setColor(Color color) {
            this.color = color;
        }

        public Point getCoordinate() {
            return coordinate;
        }

        public void setCoordinate(Point coordinate) {
            this.coordinate = coordinate;
        }

    }

}

这篇关于如何在JPanel上绘画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆