Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 什么';使用带Swing的鼠标绘制(单色)阵列的最简单方法是什么?_Java_Arrays_Swing - Fatal编程技术网

Java 什么';使用带Swing的鼠标绘制(单色)阵列的最简单方法是什么?

Java 什么';使用带Swing的鼠标绘制(单色)阵列的最简单方法是什么?,java,arrays,swing,Java,Arrays,Swing,我一直在寻找在屏幕上绘制黑白阵列的方法。这是一个简单的数组,只有20x20。我计划做的是用鼠标画一个数组,这样每个像素在点击时都会从黑到白再从黑到白“切换”,然后将数组作为一组布尔(或整数)传递给另一个函数。目前我正在使用Swing。我确实记得曾使用Swing在画布上画画,但我仍然找不到实际的用法。我应该使用画布,还是依赖于JToggleButtons?为什么不在GridLayout(20,20)中放置一个简单的20 x 20 JPanel网格,如果通过MouseStener的mousePres

我一直在寻找在屏幕上绘制黑白阵列的方法。这是一个简单的数组,只有20x20。我计划做的是用鼠标画一个数组,这样每个像素在点击时都会从黑到白再从黑到白“切换”,然后将数组作为一组布尔(或整数)传递给另一个函数。目前我正在使用Swing。我确实记得曾使用Swing在画布上画画,但我仍然找不到实际的用法。我应该使用画布,还是依赖于JToggleButtons?

为什么不在GridLayout(20,20)中放置一个简单的20 x 20 JPanel网格,如果通过MouseStener的mousePressed方法单击,则翻转面板的背景色。您可以将面板保持在二维阵列中,并在需要时查询其背景颜色

您也可以使用jlabel实现这一点,但必须记住将其不透明属性设置为true。JButton或JToggleButton也可以工作。。。选择几乎是无限的。不过,我不建议您使用AWT(Canvas),因为他们不需要在功能上后退,因为Swing可以很好地处理这一点

如果您在这方面遇到困难,为什么不回来向我们展示您的代码,我们将更好地为您提供更具体的帮助

另一种解决方法是使用单个JPanel并重写其paintComponent方法。您可以给它一个int[][]数组作为它的模型,然后在paintComponent方法中根据模型的状态绘制所需颜色的矩形。然后给它一个MouseStener来改变模型的状态并调用repaint

e、 g

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

@SuppressWarnings("serial")
public class BlackWhiteGridPanel extends JPanel {
   // can have multiple colors if desired
   // public static final Color[] COLORS = {Color.black, Color.red, Color.blue, Color.white}; 
   public static final Color[] COLORS = {Color.black, Color.white};
   public static final int SIDE = 20;
   private static final int BWG_WIDTH = 400;
   private static final int BWG_HEIGHT = BWG_WIDTH;

   private int[][] model = new int[SIDE][SIDE]; // filled with 0's.

   public BlackWhiteGridPanel() {
      addMouseListener(new MouseAdapter() {
         @Override
         public void mousePressed(MouseEvent e) {
            myMousePressed(e);
         }
      });
   }

   private void myMousePressed(MouseEvent e) {
      // find relative position of mouse press on grid.
      int i = (e.getX() * SIDE) / getWidth();
      int j = (e.getY() * SIDE) / getHeight();

      int value = model[i][j];
      // the model can only hold states allowed by the COLORS array. 
      // So if only two colors, then value can only be 0 or 1.
      value = (value + 1) % COLORS.length;
      model[i][j] = value;
      repaint();
   }

   public int[][] getModel() {
      // return a copy of model so as not to risk corruption from outside classes 
      int[][] copy = new int[model.length][model[0].length];
      for (int i = 0; i < copy.length; i++) {
         System.arraycopy(model[i], 0, copy[i], 0, model[i].length);
      }
      return copy;
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      int width = getWidth();
      int ht = getHeight();
      for (int i = 0; i < model.length; i++) {
         for (int j = 0; j < model[i].length; j++) {
            Color c = COLORS[model[i][j]];
            g.setColor(c);
            int x = (i * width) / SIDE;
            int y = (j * ht) / SIDE;
            int w = ((i + 1) * width) / SIDE - x;
            int h = ((j + 1) * ht) / SIDE - y;
            g.fillRect(x, y, w, h);
         }
      }
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(BWG_WIDTH, BWG_HEIGHT);
   }

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

      JFrame frame = new JFrame("BlackWhiteGrid");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
import java.awt.*;
导入java.awt.event.*;
导入javax.swing.*;
@抑制警告(“串行”)
公共类BlackWhiteGridPanel扩展了JPanel{
//如果需要,可以有多种颜色
//公共静态最终颜色[]颜色={Color.black,Color.red,Color.blue,Color.white};
公共静态最终颜色[]颜色={Color.black,Color.white};
公共静态最终内部侧=20;
专用静态最终整流罩宽度=400;
专用静态最终内部BWG_高度=BWG_宽度;
私有int[][]模型=新int[SIDE][SIDE];//用0填充。
公共BlackWhiteGridPanel(){
addMouseListener(新的MouseAdapter(){
@凌驾
公共无效鼠标按下(MouseEvent e){
myMousePressed(e);
}
});
}
私有无效myMousePressed(MouseEvent e){
//在网格上查找鼠标按下的相对位置。
inti=(e.getX()*侧)/getWidth();
int j=(e.getY()*侧)/getHeight();
int值=模型[i][j];
//模型只能保存颜色数组允许的状态。
//所以若只有两种颜色,那个么值只能是0或1。
值=(值+1)%COLORS.length;
模型[i][j]=数值;
重新油漆();
}
public int[]getModel(){
//返回模型的副本,以避免来自外部类的损坏风险
int[][]复制=新int[model.length][model[0.length];
for(int i=0;i
您可以简单地使用
JFrame
(或其他Swing组件)并覆盖
paint(Graphics)
方法来绘制布尔矩阵的表示(注意,对于轻量级组件,例如
JPanel
,您应该覆盖
paintComponent(Graphics)
。这将为您提供所需的点击和拖动功能(使用单个Swing组件的网格很难实现)

正如其他人所评论的,AWT
Canvas
不会提供Swing组件未提供的任何东西,在下面的示例中,您会看到我使用了
createBufferStrategy
方法,该方法也出现在
JFrame
上,以确保显示不闪烁

请注意,我的示例相当简单,它切换拖动的每个像素,而不是单击操作,确定您是处于“绘制”模式还是“擦除”模式,然后在拖动期间专门应用黑色或白色像素

public class Grid extends JFrame {
    private static final int SCALE = 10; // 1 boolean value == 10 x 10 pixels.
    private static final int SIZE = 20;

    private boolean[][] matrix = new boolean[SIZE][SIZE];
    private boolean painting;
    private int lastX = -1;
    private int lastY = -1;

    public Grid() throws HeadlessException {
        setPreferredSize(new Dimension(SIZE * SCALE, SIZE * SCALE));
        setResizable(false);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setBackground(Color.WHITE);

        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                painting = true;
                tryAdjustValue(e.getPoint());
            }

            public void mouseReleased(MouseEvent e) {
                painting = false;
                lastX = -1;
                lastY = -1;
            }
        });

        addMouseMotionListener(new MouseMotionListener() {
            public void mouseDragged(MouseEvent e) {
                tryAdjustValue(e.getPoint());
            }

            public void mouseMoved(MouseEvent e) {
                tryAdjustValue(e.getPoint());
            }
        });
    }

    private void tryAdjustValue(Point pt) {
        int newX = pt.x / SCALE;
        int newY = pt.y / SCALE;

        if (painting && isInRange(newX) && isInRange(newY) && (newX != lastX || newY != lastY)) {
            // Only invert "pixel" if we're currently in painting mode, both array indices are valid
            // and we're not attempting to adjust the same "pixel" as before (important for drag operations).
            matrix[newX][newY] = !matrix[newX][newY];
            lastX = newX;
            lastY = newY;
            repaint();
        }
    }

    private boolean isInRange(int val) {
        return val >= 0 && val < SIZE;
    }

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

        for (int x=0; x<SIZE; ++x) {
            for (int y=0; y<SIZE; ++y) {
                if (matrix[x][y]) {
                    g.fillRect(x * SCALE, y * SCALE, SCALE, SCALE);
                }
            }
        }
    }

    public static void main(String[] args) {
        Grid grid = new Grid();
        grid.pack();
        grid.setLocationRelativeTo(null);
        grid.createBufferStrategy(2);
        grid.setVisible(true);
    }
}
公共类网格扩展JFrame{
私有静态最终整数比例=10;//1布尔值==10 x 10像素。
专用静态最终整数大小=20;
私有布尔[][]矩阵=新布尔[SIZE][SIZE];
私人布尔绘画;
private int lastX=-1;
private int lastY=-1;
public Grid()抛出HeadlessException{
setPreferredSize(新维度(大小*比例,大小*比例));
可设置大小(假);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
后退地面(颜色为白色)