Java Array Loop Graphics页面无法正常运行

时间:2015-01-28 22:30:28

标签: java arrays swing oop user-interface

编辑2:我决定如果我把整个代码放在一起会更容易理解,以便你可以测试它。

编辑:我意识到我说的不清楚,所以我会尽可能地解释这个。基本上,我使用fillRect方法在Graphics页面上绘制矩形。问题在于,当我改变一个的大小时,它们都会改变,因为每次绘制一个新的都会重新绘制它们。为了解决这个问题,我添加了一个数组,它存储了在问题的另一部分通过滚轮输入的所有大小。无论如何,我知道这个问题被隔离到了一个循环,据说它会把它们全部拉成一定的大小,所以我添加了一个循环,理论上应该给我一个临时变量,每次使用重绘所有矩形的大小每次运行主循环时从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;

}

1 个答案:

答案 0 :(得分:2)

您似乎让ArrayList与数组进行交互,这使得我们很难遵循您的逻辑。这表明您的逻辑可能过于复杂而不适合您自己的利益,并且您的代码可能会从简化中受益。为什么不创建List<Rectangle>,例如ArrayList<Rectangle>,然后在paintComponent方法中循环遍历此列表,并使用Graphics2D对象的draw(...)fill(...)绘制每个Rectangle方法:

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();
         }
      });
   }
}