Java - 向框架添加形状

时间:2018-04-12 16:20:43

标签: java swing

我创建一个JFrame,然后是JPanel并设置参数。我有一个名为boardSquares的JPanel,其中每个方块稍后会着色。

尝试将检查器添加到电路板后,将重新排列电路板颜色。

我已经多次尝试解决这个问题,但没有成功。我也相信有更好的方法可以做到这一点。下面是一些代码。感谢所有帮助!

    public void paintComponent(Graphics g)
    {
        g.setColor(Color.BLUE);
        g.fillOval(0, 0, 30, 30);
    }

    public static void checkerBoard()
    {
        for (int i = 0; i < 8; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                boardSquares[i][j] = new JPanel();

                if ((i + j) % 2 == 0)
                {
                    boardSquares[i][j].setBackground(Color.BLACK);
                }
                else
                {
                    boardSquares[i][j].setBackground(Color.WHITE);
                }
                frameOne.add(boardSquares[i][j]);
            }
        }
    }

3 个答案:

答案 0 :(得分:0)

请看这个例子https://www.javaworld.com/article/3014190/learn-java/checkers-anyone.html

我对你的例子进行了一点升级 对不起,我没有太多时间用它

/* 
 *  Component I want to test 
 */ 

import React from 'react';

class DomStyleTest extends React.Component {
    componentDidMount() {
        this.addStyleToElement();
    }

    myElement = null;

    getRefToElement = element => {
        this.myElement = element;
    };

    addStyleToElement() {
        if (this.myElement) {
            this.myElement.style.height = `${window.innerHeight -
            this.myElement.getBoundingClientRect().top}px`;
        }
        _console.log(`height is ${this.myElement.style.height}`); // WORKS -- shows '768px'
    }

    render() {
        return (
          <div
            ref={this.getRefToElement}
            className="widget"
          >
            <div className="widget-stuff">
                Hello, this is a widget.
            </div>
          </div>
      );
    }
}
export default DomStyleTest;

}

答案 1 :(得分:0)

我会创建一个单独的棋盘类并覆盖paintComponent方法来绘制实际网格。

然后我会给电路板一个网格布局并添加面板以保持跳棋。

检查器的边距存在问题,但这可能是由于面板的大小造成的。你可以搞砸了。我通过在面板上应用边框布局来解决这个问题。

最后,避免使用&#34;魔术数字&#34;。尝试在类中声明一些实例变量,并通过构造函数或一些setter / mutator方法传递它们的值。

Checkers Game screenshot

Application.java

package game.checkers;

import java.awt.*;
import java.lang.reflect.InvocationTargetException;
import javax.swing.SwingUtilities;

public class Application implements Runnable {
  public static final String APP_NAME = "Checkers Game";

  private GameFrame gameFrame;
  private GameBoard checkerBoard;

  @Override
  public void run() {
    initialize();

    Checker redChecker = new Checker(50, Color.RED);
    Checker greenChecker = new Checker(50, Color.GREEN);
    Checker blueChecker = new Checker(50, Color.BLUE);

    checkerBoard.placeChecker(redChecker, 1, 5);
    checkerBoard.placeChecker(greenChecker, 2, 4);
    checkerBoard.placeChecker(blueChecker, 3, 3);

    redChecker.addMouseListener(new CheckerMouseListener(redChecker));
    greenChecker.addMouseListener(new CheckerMouseListener(greenChecker));
    blueChecker.addMouseListener(new CheckerMouseListener(blueChecker));
  }

  protected void initialize() {
    gameFrame = new GameFrame(APP_NAME);
    checkerBoard = new GameBoard(8, 8);

    checkerBoard.setPreferredSize(new Dimension(400, 400));
    gameFrame.setContentPane(checkerBoard);
    gameFrame.pack();
    gameFrame.setVisible(true);
  }

  public static void main(String[] args) {
    try {
      SwingUtilities.invokeAndWait(new Application());
    } catch (InvocationTargetException | InterruptedException e) {
      e.printStackTrace();
    }
  }
}

GameFrame.java

package game.checkers;

import javax.swing.JFrame;

public class GameFrame extends JFrame {
  private static final long serialVersionUID = 6797487872982059625L;

  public GameFrame(String title) {
    super(title);

    this.setResizable(false);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
}

GameBoard.java

package game.checkers;

import java.awt.*;
import javax.swing.JPanel;

public class GameBoard extends JPanel {
  private static final long serialVersionUID = 5777309661510989631L;
  private static final Color[] DEFAULT_TILE_COLORS = new Color[] { Color.LIGHT_GRAY, Color.WHITE };

  private BoardZone[][] zones;
  private Color[] tileColors;
  private int rows;
  private int cols;

  public int getRows() {
    return rows;
  }

  public void setRows(int rows) {
    this.rows = rows;
  }

  public int getCols() {
    return cols;
  }

  public void setCols(int cols) {
    this.cols = cols;
  }

  public GameBoard(int rows, int cols, Color[] tileColors) {
    super();

    this.rows = rows;
    this.cols = cols;
    this.tileColors = tileColors;

    initialize();
  }

  public GameBoard(int rows, int cols) {
    this(rows, cols, DEFAULT_TILE_COLORS);
  }

  protected void initialize() {
    this.setLayout(new GridLayout(rows, cols, 0, 0));

    generateZones();
  }

  private void generateZones() {
    this.setLayout(new GridLayout(rows, cols, 0, 0));

    this.zones = new BoardZone[rows][cols];
    for (int row = 0; row < rows; row++) {
      for (int col = 0; col < cols; col++) {
        this.add(zones[row][col] = new BoardZone());
      }
    }
  }

  public void placeChecker(Checker checker, int row, int col) {
    zones[row][col].add(checker);
  }

  public Checker getChecker(int row, int col) {
    return (Checker) zones[row][col].getComponent(0);
  }

  public void removeChecker(Checker checker, int row, int col) {
    zones[row][col].remove(checker);
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    int tileWidth = this.getWidth() / cols;
    int tileHeight = this.getHeight() / rows;

    for (int row = 0; row < rows; row++) {
      for (int col = 0; col < cols; col++) {
        int x = col * tileWidth;
        int y = row * tileHeight;

        g.setColor(tileColors[(row + col) % 2]);
        g.fillRect(x, y, tileWidth, tileHeight);
      }
    }
  }
}

Checker.java

package game.checkers;

import java.awt.*;
import javax.swing.JComponent;

public class Checker extends JComponent {
  private static final long serialVersionUID = -4645763661137423823L;

  private int radius;
  private Color color;

  public int getRadius() {
    return radius;
  }

  public void setRadius(int radius) {
    this.radius = radius;
  }

  public Color getColor() {
    return color;
  }

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

  public String getHexColor() {
    return String.format("#%06X", getColor() == null ? 0 : getColor().getRGB());
  }

  public Checker(int radius, Color color) {
    super();

    this.setPreferredSize(new Dimension(radius, radius));

    this.radius = radius;
    this.color = color;
  }

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

    if (this.radius <= 0 || this.color == null) {
      return; // Do not draw it.
    }

    g.setColor(this.color);
        g.fillOval(0, 0, this.radius - 1, this.radius - 1);
  }
}

BoardZone.java

package game.checkers;

import java.awt.BorderLayout;
import javax.swing.JPanel;

public class BoardZone extends JPanel {
  private static final long serialVersionUID = 8710283269464564251L;

  public BoardZone() {
    this.setOpaque(false);
    this.setLayout(new BorderLayout());
  }
}

CheckerMouseListener.java

package game.checkers;

import java.awt.event.*;

public class CheckerMouseListener implements MouseListener {
  private Checker target;

  public CheckerMouseListener(Checker target) {
    this.target = target;
  }

  private String getCheckerName() {
    String hexCode = target.getHexColor();

    switch (hexCode) {
      case "#FFFF0000":
        return "RED";
      case "#FF00FF00":
        return "GREEN";
      case "#FF0000FF":
        return "BLUE";
      default:
        return hexCode;
    }
  }

  @Override
  public void mouseReleased(MouseEvent e) {
    System.out.println("Released click over " + getCheckerName() + " checker.");
  }

  @Override
  public void mousePressed(MouseEvent e) {
    System.out.println("Pressed on " + getCheckerName() + " checker.");
  }

  @Override
  public void mouseExited(MouseEvent e) {
    System.out.println("Finished hovering over " + getCheckerName() + " checker.");
  }

  @Override
  public void mouseEntered(MouseEvent e) {
    System.out.println("Began hovering over " + getCheckerName() + " checker.");
  }

  @Override
  public void mouseClicked(MouseEvent e) {
    System.out.println("Clicked on " + getCheckerName() + " checker.");
  }
}

答案 2 :(得分:-3)

我认为不适合使用jPanel作为Board Squares使用JPanel paintComponent方法来绘制你的游戏板。这就是我编码的方式。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

public class AddShapeToFrame {

private static GameBoard gb;

public static void main(String[] args) {

    JFrame frameOne = new JFrame();
    frameOne.setSize(new Dimension(400, 400));
    frameOne.getContentPane().setLayout(new BorderLayout());
    frameOne.setVisible(true);
    frameOne.setResizable(false);
    frameOne.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    gb = new GameBoard(1, 1);
    frameOne.add(gb);
    frameOne.setVisible(true);

    frameOne.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();
            switch (keyCode) {
                case KeyEvent.VK_UP:
                    gb.setChecker_y(gb.getChecker_y() - 1);
                    break;
                case KeyEvent.VK_RIGHT:
                    gb.setChecker_x(gb.getChecker_x() + 1);
                    break;
                case KeyEvent.VK_DOWN:
                    gb.setChecker_y(gb.getChecker_y() + 1);
                    break;
                case KeyEvent.VK_LEFT:
                    gb.setChecker_x(gb.getChecker_x() - 1);
                    break;
            }             
        }

     });

    }

  }

  class GameBoard extends JPanel {

   private int checker_x;
   private int checker_y;

   public GameBoard(int checker_x, int checker_y) {
      this.checker_x = checker_x;
      this.checker_y = checker_y;
   }


   @Override
   protected void paintComponent(Graphics g) {
         drawBord(g, checker_x, checker_y);
   }


  private void drawBord(Graphics g, int checker_x, int checker_y) {
    boolean f;
    //boardSquares_higth
    int bsh = this.getHeight() / 8;
    //boardSquares_widht
    int bsw = this.getWidth() / 8;
    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            if ((i + 1) % 2 == 0) {
                f = (j + 1) % 2 == 0;
            } else {
                f = (j + 1) % 2 != 0;
            }
            if (f) {
                g.setColor(Color.GRAY);
            } else {
                g.setColor(Color.WHITE);
            }
            int x = bsw * j;
            int y = bsh * i;
            g.fillRect(x, y, bsw, bsh);
        }
    }

    g.setColor(Color.red);
    g.fillArc(5 + (bsw * (checker_x - 1)), 5 + (bsh * (checker_y - 1)), bsw - 10, bsh - 10, 0, 360);
}

public int getChecker_x() {
    return checker_x;
}

public void setChecker_x(int checker_x) {
    if (checker_x <= 8) {
        if (checker_x >= 1) {
            this.checker_x = checker_x;
            repaint();
        } else {
            System.out.println("Invalid move");
        }

    } else {
        System.out.println("Invalid move");
    }
}

public int getChecker_y() {
    return checker_y;
}

public void setChecker_y(int checker_y) {
    if (checker_y <= 8) {
        if (checker_y >= 1) {
            this.checker_y = checker_y;
            repaint();
        } else {
            System.out.println("Invalid move");
        }

    } else {
        System.out.println("Invalid move");
     }

    }

  }