油漆中的坐标

Posted

技术标签:

【中文标题】油漆中的坐标【英文标题】:Coordinates in paint 【发布时间】:2016-05-06 16:35:33 【问题描述】:

当您单击一个框时,它应该在该框中从指定坐标创建一个圆圈。除非它已经存在,否则将其删除。如何将 currentx 和 currenty 坐标放入填充椭圆中?

public class Grid extends Applet

boolean click;

public void init()

    click = false;
    addMouseListener(new MyMouseListener());


public void paint(Graphics g)

    super.paint(g);

    g.drawRect(100, 100, 400, 400);
    //each box
    g.drawRect(100, 100, 100, 100);
    g.drawRect(200, 100, 100, 100);
    g.drawRect(300, 100, 100, 100);
    g.drawRect(400, 100, 100, 100);
    //2y
    g.drawRect(100, 200, 100, 100);
    g.drawRect(200, 200, 100, 100);
    g.drawRect(300, 200, 100, 100);
    g.drawRect(400, 200, 100, 100);
    //3y1x
    g.drawRect(100, 300, 100, 100);
    g.drawRect(200, 300, 100, 100);
    g.drawRect(300, 300, 100, 100);
    g.drawRect(400, 300, 100, 100);
    //4y1x
    g.drawRect(100, 400, 100, 100);
    g.drawRect(200, 400, 100, 100);
    g.drawRect(300, 400, 100, 100);
    g.drawRect(400, 400, 100, 100);


    if (click)
    
        g.fillOval(currentx, currenty, 100, 100); // problem HERE
    


private class MyMouseListener implements MouseListener
       
         public void mouseClicked(MouseEvent e)
         
             int nowx = e.getX();
             int nowy = e.getY();

             nowx = nowx / 100;
             String stringx = Integer.toString(nowx);
             stringx = stringx+"00";
             int currentx = Integer.parseInt(stringx);

             nowy = nowy /100;
             String stringy = Integer.toString(nowy);
             stringy = stringy+"00";
             int currenty = Integer.parseInt(stringy);

             click = true;
             repaint();
         

    @Override
    public void mousePressed(MouseEvent e) 
        // TODO Auto-generated method stub

    

    @Override
    public void mouseReleased(MouseEvent e) 
        // TODO Auto-generated method stub

    

    @Override
    public void mouseEntered(MouseEvent e) 
        // TODO Auto-generated method stub

    

    @Override
    public void mouseExited(MouseEvent e) 
        // TODO Auto-generated method stub

    


【问题讨论】:

Java Plugin support deprecated 和 Moving to a Plugin-Free Web 【参考方案1】:

您的主要问题是,在 Swing/AWT 中绘制具有破坏性,即每次调用您的 paint 方法时,都希望您重新绘制组件的当前状态。

在这种情况下,您真正​​需要的是某种方式来模拟游戏的状态,因此当调用paint 时,您可以以某种有意义的方式重新绘制它。这是Model-View-Controller 范式的基本概念,您可以将程序的职责分成不同的层。

那么问题就变成了,如何从视图转换为模型?

基本思想是将鼠标的当前 x/y 坐标除以单元格大小。您还需要确保结果在预期范围内,因为您可能会得到超出网格列/行的结果

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test 

    public static void main(String[] args) 
        new Test();
    

    public Test() 
        EventQueue.invokeLater(new Runnable() 
            @Override
            public void run() 
                try 
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                 catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) 
                    ex.printStackTrace();
                

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            
        );
    

    public static class TestPane extends JPanel 

        protected static final int CELL_COUNT = 3;

        private int[][] board;
        private int[] cell;

        private boolean isX = true;

        public TestPane() 
            board = new int[CELL_COUNT][CELL_COUNT];

            addMouseListener(new MouseAdapter() 
                @Override
                public void mouseClicked(MouseEvent e) 
                    int[] cell = getCellAt(e.getPoint());
                    if (board[cell[0]][cell[1]] == 0) 
                        board[cell[0]][cell[1]] = isX ? 1 : 2;
                        isX = !isX;
                        repaint();
                    
                
            );

            addMouseMotionListener(new MouseAdapter() 
                @Override
                public void mouseMoved(MouseEvent e) 
                    cell = getCellAt(e.getPoint());
                    repaint();
                
            );
        

        protected int[] getCellAt(Point p) 
            Point offset = getOffset();
            int cellSize = getCellSize();

            int x = p.x - offset.x;
            int y = p.y - offset.y;

            int gridx = Math.min(Math.max(0, x / cellSize), CELL_COUNT - 1);
            int gridy = Math.min(Math.max(0, y / cellSize), CELL_COUNT - 1);

            return new int[]gridx, gridy;
        

        protected Point getOffset() 
            int cellSize = getCellSize();
            int x = (getWidth() - (cellSize * CELL_COUNT)) / 2;
            int y = (getHeight() - (cellSize * CELL_COUNT)) / 2;
            return new Point(x, y);
        

        protected int getCellSize() 
            return Math.min(getWidth() / CELL_COUNT, getHeight() / CELL_COUNT) - 10;
        

        @Override
        public Dimension getPreferredSize() 
            return new Dimension(200, 200);
        

        @Override
        protected void paintComponent(Graphics g) 
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();

            Point offset = getOffset();
            int cellSize = getCellSize();
            if (cell != null) 
                g2d.setColor(new Color(0, 0, 255, 128));
                g2d.fillRect(
                        offset.x + (cellSize * cell[0]),
                        offset.y + (cellSize * cell[1]),
                        cellSize,
                        cellSize);
            

            g2d.setColor(Color.BLACK);

            FontMetrics fm = g2d.getFontMetrics();
            for (int col = 0; col < CELL_COUNT; col++) 
                for (int row = 0; row < CELL_COUNT; row++) 
                    int value = board[col][row];
                    int x = offset.x + (cellSize * col);
                    int y = offset.y + (cellSize * row);
                    String text = "";
                    switch (value) 
                        case 1:
                            text = "X";
                            break;
                        case 2:
                            text = "O";
                            break;
                    
                    x = x + ((cellSize - fm.stringWidth(text)) / 2);
                    y = y + ((cellSize - fm.getHeight()) / 2) + fm.getAscent();
                    g2d.drawString(text, x, y);
                
            

            int x = offset.x;
            int y = offset.y;
            for (int col = 1; col < CELL_COUNT; col++) 
                x = offset.x + (col * cellSize);
                g2d.drawLine(x, y, x, y + (cellSize * CELL_COUNT));
            
            x = offset.x;
            for (int row = 1; row < CELL_COUNT; row++) 
                y = offset.x + (row * cellSize);
                g2d.drawLine(x, y, x + (cellSize * CELL_COUNT), y);
            
            g2d.dispose();
        

    


【讨论】:

【参考方案2】:

首先,如果您想将一个数字截断到最接近的 100,例如142变成100,你要做的就是:

num = (num/100)*100;

这是因为当您将 2 个整数相除时,它会自动将其截断,您只需将其相乘即可得到数字。在这种情况下,我认为您想要的是创建一些字段变量和一些访问器方法。在 MouseListener 类的顶部,您需要添加:

private int mouseX=0;
private int mouseY=0;

然后为了能够从 mouselistener 类之外访问这些变量,您需要添加访问器方法:

public int getMouseX()
    return mouseX;

在您的网格类中,您可以添加字段:

private MyMouseListener listener;

然后在你的init中初始化它:

listener = new MyMouseListener();
addMouseListener(listener);

然后你可以对mouseY做同样的事情,最后你可以从你的paint方法中调用:

int mouseX = listener.getMouseX();
int mouseY = listener.getMouseY();

然后从那里可以很简单地找到您单击的框!

【讨论】:

您为什么建议原发帖人打破 OOP 规则并使用静态字段和方法,而这似乎没有必要也没有好处? @HovercraftFullOfEels 有一些涉及 OOP 的方法可以做到这一点,但我不确定 OP 是否需要它,不过我会更改它以适应 OOP

以上是关于油漆中的坐标的主要内容,如果未能解决你的问题,请参考以下文章

LQ0139 油漆面积枚举

如何从 UICollectionView 的另一个类中的函数加载图像?我正在使用油漆代码

AWT 标签/按钮/文本字段 + 油漆?

有啥办法能快速清除Centos6中的无用软件包

2022-02-01:粉刷房子 II。 假如有一排房子,共 n 个,每个房子可以被粉刷成 k 种颜色中的一种,你需要粉刷所有的房子并且使其相邻的两个房子颜色不能相同。 当然,因为市场上不同颜色油漆的价

opencv-python提取某种颜色在另一个图层上显示