Java 数组循环图形页面不起作用

标签 java arrays swing oop user-interface

编辑2:我决定把整个代码放出来,这样你就可以测试它,这样会更容易理解。

编辑:我意识到我说的不清楚,所以我会尽力解释这一点。基本上,我使用 fillRect 方法在图形页面上绘制矩形。问题是,当我改变一个的大小时,它们都会改变,因为每次绘制新的时它们都会被重新绘制。为了纠正这个问题,我添加了一个数组,用于存储通过问题的另一部分中的滚轮输入的所有尺寸。无论如何,我知道问题与循环无关,据说该循环将它们全部绘制到一定的大小,所以我添加了一个循环,理论上应该每次都给我一个临时变量,以重新绘制从 0 开始的所有矩形大小主循环运行的时间。问题在于,这实际上并没有将矩形重新绘制为其各自的大小,而是将它们绘制为当前大小。我也更新了代码部分。

我在使用 Java 项目时遇到问题。它应该做的是将每个矩形对象存储在数组中,然后根据数组的长度重新创建矩形,从而更改每个矩形对象的大小。我(至少我认为)通过创建一个变量来做到这一点,该变量应该等于程序另一部分中更改的 SIZE,然后将其设置为等于数组中 i 处的特定元素。无论如何,当我这样做时,我将所有长度更改为绘制矩形时当前的长度。我知道问题出在我在尺寸部分使用 i ,但我会使用什么?预先感谢您的帮助!

这是代码:

public class Dots
{

public static void main(String[] args)
{
  JFrame frame = new JFrame("Array Rectangles");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  DotsPanel dotsPanel = new DotsPanel();
  frame.getContentPane().add(dotsPanel);

  //buttons
  JButton btnNewButton = new JButton("RED");
  btnNewButton.setHorizontalAlignment(SwingConstants.LEFT);
  btnNewButton.setVerticalAlignment(SwingConstants.BOTTOM);
  btnNewButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
    }
  });
  btnNewButton.setForeground(Color.RED);
  dotsPanel.add(btnNewButton);

  JButton btnNewButton_1 = new JButton("GREEN");
  btnNewButton_1.setForeground(Color.GREEN);
  btnNewButton_1.setVerticalAlignment(SwingConstants.BOTTOM);
  dotsPanel.add(btnNewButton_1);

  JButton btnNewButton_2 = new JButton("BLUE");
  btnNewButton_2.setForeground(Color.BLUE);
  dotsPanel.add(btnNewButton_2);

  JButton btnNewButton_3 = new JButton("BLACK");
  btnNewButton_3.setForeground(new Color(0, 0, 0));
  dotsPanel.add(btnNewButton_3);


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



import java.util.ArrayList;
import java.util.Random;

import javax.swing.JPanel;

import java.awt.*;
import java.awt.event.*;

public class DotsPanel extends JPanel
{
// radius of each dot
private int SIZE = 25;  
private int SIZEAccess;

private static final Random generator = new Random();

//used to count amount of dots
private ArrayList<Point> pointList;

int[] sizes = new int [10000];


//Sets up this std. sized panel to listen for mouse events.
public DotsPanel()
{
    pointList = new ArrayList<Point>();

    addMouseListener (new DotsListener());
    addMouseMotionListener(new DotsListener());
    addMouseWheelListener(new DotsListener());

    setBackground(Color.white);
    setPreferredSize(new Dimension(1024, 768));
}


//used to generate a random color
public static Color randomColor() {
    return new Color(generator.nextInt(256), generator.nextInt(256), generator.nextInt(256));
}

//  Draws all of the dots stored in the list.
public void paintComponent(Graphics page)
{
    super.paintComponent(page);

    //draws a centered dot of random color
    int i = 0;
    for (Point spot : pointList)
    {
        sizes[i] = SIZE;
        //SIZEAccess = SIZE;
        //sizes[i] = SIZEAccess;
        //page.fillRect(spot.x-SIZE, spot.y-SIZE, SIZE*2, SIZE*2);
        for (int temp = 0; temp <= i; temp++)
            page.fillRect(spot.x-sizes[temp], spot.y-sizes[temp], sizes[temp]*2, sizes[temp]*2);
        //page.fillRect(spot.x-SIZE, spot.y-SIZE, SIZE*2, SIZE*2);
        //page.setColor(randomColor());

        //page.setColor(c)
        i++;

    }

    //displays the amount of rectangles drawn at the top left of screen
    page.drawString("Count: " + pointList.size(), 5, 15);

    page.drawString("To change the size of the squares, use mouse scroll wheel.", 350, 15);

    page.drawString("Size: " + SIZE, 950, 15);

}

//  Represents the listener for mouse events.
private class DotsListener implements MouseListener, MouseMotionListener, MouseWheelListener
{

    //  Adds the current point to the list of points and redraws
    //  the panel whenever the mouse button is pressed.

    public void mousePressed(MouseEvent event)
    {
        pointList.add(event.getPoint());
        repaint();
    }


    //  Provide empty definitions for unused event methods.

    public void mouseClicked(MouseEvent event) {

    }
    public void mouseReleased(MouseEvent event) {

    }
    public void mouseEntered(MouseEvent event) {

    }
    public void mouseExited(MouseEvent event) {}


    //  Adds the current point to the list of points and redraws
    //  the panel whenever the mouse button is dragged.
    public void mouseDragged(MouseEvent event) {
        pointList.add(event.getPoint());
        repaint();

    }

    public void mouseMoved(MouseEvent event) {

    }


    public void mouseWheelMoved(MouseWheelEvent event)
    { 
        int notches = 0;
        notches = event.getWheelRotation();
        //int 

        if (notches > 0)
        {
            SIZE = SIZE + notches;
            notches = 0;
        }
        else if (notches < 0)
        {
            int tempSIZE = SIZE;
            tempSIZE = tempSIZE + notches;
            //prevents the program from having dots that increase due to multiplying negatives by negatives 
            //by making anything less than 1 equal 1
            if(tempSIZE < 1)
                tempSIZE = 1;
            SIZE = tempSIZE;
            notches = 0;

        }
    }
}




//SIZE = SIZE + notches;

}

最佳答案

您似乎将 ArrayList 与数组以一种令人困惑的方式进行交互,这使得我们很难遵循您的逻辑。这表明您的逻辑可能过于复杂,不利于您的利益,并且您的代码可能会从简化中受益。为什么不创建一个 List<Rectangle>例如 ArrayList<Rectangle> ,然后简单地在您的paintComponent方法中循环遍历这个列表,并使用Graphics2D对象的draw(...)绘制每个矩形。或fill(...)方法:

private List<Rectangle> rectangleList = new ArrayList<>();

@Override
protected void paintComponent(Graphics g) {
   super.paintComponent(g);
   Graphics2D g2 = (Graphics2D) g;
   for (Rectangle rectangle : rectangleList) {
      g2.fill(rectangle);
   }
}

例如:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;

@SuppressWarnings("serial")
public class Foo extends JPanel {
   private static final int PREF_W = 600;
   private static final int PREF_H = PREF_W;
   private static final Color BACKGROUND = Color.black;
   private static final Color FILL_COLOR = Color.pink;
   private static final Color DRAW_COLOR = Color.red;
   private static final Stroke STROKE = new BasicStroke(3);
   private List<Rectangle> rectangleList = new ArrayList<>();
   private Point pressPoint = null;
   private Point dragPoint = null;

   public Foo() {
      setBackground(BACKGROUND);
      MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
      addMouseListener(myMouseAdapter);
      addMouseMotionListener(myMouseAdapter);
   }

   @Override
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      Stroke oldStroke = g2.getStroke();
      g2.setStroke(STROKE);
      for (Rectangle rectangle : rectangleList) {
         g2.setColor(FILL_COLOR);
         g2.fill(rectangle);
         g2.setColor(DRAW_COLOR);
         g2.draw(rectangle);
      }
      g2.setStroke(oldStroke);
      if (pressPoint != null && dragPoint != null) {
         g2.setColor(FILL_COLOR.darker());
         int x = Math.min(pressPoint.x, dragPoint.x);
         int y = Math.min(pressPoint.y, dragPoint.y);
         int width = Math.abs(pressPoint.x - dragPoint.x);
         int height = Math.abs(pressPoint.y - dragPoint.y);
         g2.drawRect(x, y, width, height);
      }
   }

   private class MyMouseAdapter extends MouseAdapter {
      @Override
      public void mousePressed(MouseEvent e) {
         pressPoint = e.getPoint();
         repaint();
      }

      @Override
      public void mouseDragged(MouseEvent e) {
         dragPoint = e.getPoint();
         repaint();
      }

      @Override
      public void mouseReleased(MouseEvent e) {
         dragPoint = e.getPoint();
         int x = Math.min(pressPoint.x, dragPoint.x);
         int y = Math.min(pressPoint.y, dragPoint.y);
         int width = Math.abs(pressPoint.x - dragPoint.x);
         int height = Math.abs(pressPoint.y - dragPoint.y);
         Rectangle rect = new Rectangle(x, y, width, height);
         rectangleList.add(rect);

         pressPoint = null;
         dragPoint = null;
         repaint();
      }
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("Foo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new Foo());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

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

关于Java 数组循环图形页面不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28203699/

相关文章:

java - 使用 @JsonProperty 的通用 JSON 响应

java - 为什么 Spring Boot 应用程序在 Azure Web 应用程序上部署后无法运行

python - 将 numpy 数组从 3D reshape 为 2D

java - JInternal 框架上的嵌套 JSplitPane

java - 限制 PLAIN_MESSAGE JOptionPane 中输入文本的大小

java - 我需要帮助以一种方法将 child 作为父亲传递 [Java]

java - 在 Java 中将字符串压缩为 gzip

php - 如何从文本文件中读取数组?

javascript - 用空格和破折号分割字符串

Java Swing - 在不覆盖的情况下绘制 JPanel