【问题标题】:Java Array Loop Graphics page not functioningJava 数组循环图形页面不起作用
【发布时间】:2015-01-28 22:30:28
【问题描述】:

编辑 2:我决定将整个代码放在上面会更容易理解,以便您进行测试。

edit:我意识到我说的不清楚,所以我会尽我所能解释这一点。基本上,我使用 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;

}

【问题讨论】:

  • 这应该是动画吗?我不清楚你想做什么。如果是动画,则使用 Swing Timer,而不是 for 循环。
  • 对不起,我的解释不是很好;这不是动画。它是一个在触发 MouseEvent 时绘制矩形的程序。
  • 请考虑编辑您的问题,以尽量使您的问题清楚。试着解释你的问题,就好像你在向一个 6 岁的孩子解释这个问题一样。假设我们对您当前的项目、愿望或问题一无所知。

标签: java arrays swing oop user-interface


【解决方案1】:

您似乎让 ArrayList 与数组的交互混杂在一起,这让我们很难遵循您的逻辑。这表明您的逻辑可能对您自己的利益过于复杂,并且您的代码可能会从简化中受益。为什么不改为创建一个List&lt;Rectangle&gt;,例如ArrayList&lt;Rectangle&gt;,然后在您的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();
         }
      });
   }
}

【讨论】:

  • 我没有想到不使用数组和使用arrayLists,但这确实做了代码应该做的事情。我将不得不修补它,但非常感谢您的帮助!
猜你喜欢
  • 2015-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-22
  • 2014-04-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多