java - 如何将对象形状从一个位置移动到另一个位置?

标签 java swing oop awt 2d

我正在尝试将一个对象(在本例中为蓝色圆圈)从一个位置移动到另一个位置。这将位于 8*8 网格上。

gBoard.setColor(Color.LIGHT_GRAY);
    gBoard.fillRect(0,0,400,400);
    for (int k=000; k<=300; k+=100){
        for (int l=000; l<=300; l+=100){
            gBoard.clearRect(k,l,50,50);
        }
    }
    for (int k=50; k<=350; k+=100){
        for (int l=50; l<=350; l+=100){
            gBoard.clearRect(k,l,50,50);
        }
    }

上面的代码显示我已经成功创建了 8*8 网格,这意味着我可以将对象放置在需要的位置。

    gBoard.setColor(Color.BLUE);
    int x = 0;
    int y = 0;
    gBoard.fillOval(x,y,50,50);

上面的代码显示我已将对象放入网格中,但是这会进入 public void 方法还是一个单独的方法,因为该对象不会处于常量地点。该物体会不断移动。 public void 更合适还是最好为接口(interface)使用单独的方法?

最佳答案

建议:

  • 使用 GridLayout 创建添加到 JPanel 的 JLabel 网格
  • 使用采用 Icon 的 JLabel 构造函数为每个 JLabel 提供一个适当大小的空 ImageIcon。
  • 同时创建另一个包含彩色磁盘的 ImageIcon
  • 通过在 JLabel 上调用 setIcon(...) 将图标移动到相应的 JLabel
  • 通过调用 setIcon(...) 并传入空图标或空白图标,从 JLabel 中删除图标。

例如,

enter image description here

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;

import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

@SuppressWarnings("serial")
public class ColoredOvals extends JPanel {
    public static final int CELL_WIDTH = 50;
    public static final int SIDE = 8;
    private JLabel[][] grid = new JLabel[SIDE][SIDE];
    private Icon emptyIcon;
    private Icon colorIcon;

    public ColoredOvals() {
        // so lines appear between cells
        setBackground(Color.BLACK);

        // empty icon is 50x50 in size, and with clear color
        emptyIcon = createIcon(new Color(0, 0, 0, 0));
        // icon with a RED disk 
        colorIcon = createIcon(Color.RED);

        // create a grid layout to hold the JLabels
        // the 1, 1 is for the empty space between cells to show the black line
        setLayout(new GridLayout(SIDE, SIDE, 1, 1)); 

        // line around the entire JPanel (if desired)
        setBorder(BorderFactory.createLineBorder(Color.BLACK));

        // mouse listener that moves the icon to the selected cell:
        MouseListener mouseListener = new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                clearGrid();  // all labels hold blank icon
                JLabel label = (JLabel) e.getSource();
                label.setIcon(colorIcon);  // selected JLabel holds disk
            }
        };

        // iterate through the grid 2D array, creating JLabels and adding
        // blank icon as well as a MouseListener
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                grid[i][j] = new JLabel(emptyIcon); // blank icon
                grid[i][j].setOpaque(true);
                grid[i][j].setBackground(Color.WHITE);
                add(grid[i][j]);
                grid[i][j].addMouseListener(mouseListener);
            }
        }
    }

    public void clearGrid() {
        for (JLabel[] jLabels : grid) {
            for (JLabel jLabel : jLabels) {
                jLabel.setIcon(emptyIcon);
            }
        }
    }

    // code to create blank icon or disk icon of color of choice
    private Icon createIcon(Color color) {
        BufferedImage img = new BufferedImage(CELL_WIDTH, CELL_WIDTH, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = img.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(color);
        int gap = 2;
        g2.fillOval(gap, gap, CELL_WIDTH - 2 * gap, CELL_WIDTH - 2 * gap);
        g2.dispose();
        return new ImageIcon(img);
    }

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

        JFrame frame = new JFrame("ColoredOvals");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

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

选项 2——如果您想要磁盘更加自由的运动,那么:

  • 将 MouseListener 和 MouseMotionListener 添加到 JPanel 本身
  • 在此组合监听器中(两者均使用 MouseAdapter),更改两个 int 字段(例如 centerX 和 centerY)保存的值,然后调用 repaint();
  • 重写paintComponent方法,注意在重写中调用super的方法
  • 在覆盖中,在鼠标监听器更改的字段指定的位置绘制磁盘。

例如:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

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

@SuppressWarnings("serial")
public class ColoredOvals2 extends JPanel {
    public static final int CELL_WIDTH = 50;
    public static final int SIDE = 8;
    private static final Color BG = Color.WHITE;
    private static final Color DISK_COLOR = Color.BLUE;
    private int centerX = 0;
    private int centerY = 0;

    public ColoredOvals2() {
        setBackground(BG);
        MouseAdapter myMouse = new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                moveDisk(e);
            }

            @Override
            public void mouseDragged(MouseEvent e) {
                moveDisk(e);
            }

            private void moveDisk(MouseEvent e) {
                centerX = e.getX();
                centerY = e.getY();
                repaint();
            }
        };
        addMouseListener(myMouse);
        addMouseMotionListener(myMouse);
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        int w = SIDE * CELL_WIDTH;
        int h = w;
        return new Dimension(w, h);
    }


    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(DISK_COLOR);
        int x = centerX - CELL_WIDTH / 2;
        int y = centerY - CELL_WIDTH / 2;
        int w = CELL_WIDTH;
        int h = CELL_WIDTH;
        g2.fillOval(x, y, w, h);
    }

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

        JFrame frame = new JFrame("ColoredOvals2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

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

关于java - 如何将对象形状从一个位置移动到另一个位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49834416/

相关文章:

java - 使用java代码将图片插入数据库(sqlite)。我应该怎么办?

java - 如何在 Android 中动态转换类的实例

java - 使用 JScrollBar 调整形状尺寸

Java Swing - JPanel 的背景

java - drawString 方法不起作用

java - jScrollPane 中的 jPanel 不起作用

连接到 MySQL 数据库的 Python 脚本 - 代码作为程序脚本运行,在 OOP 重构后失败

java - 如何决定创建一个新的子类

oop - 在测试用例中添加特征时获取 'ObsoleteTrait'

java - 如何将 JSON 数组发送到另一个方法