保存信息 - 摇摆形状 [英] Saving Information - Swing Shapes

查看:158
本文介绍了保存信息 - 摇摆形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要存储一个使用图形对象创建的形状作为一个变量,但输出的类型为void,并且转换不起作用。

I want to be able to store a shape created using a graphics object as a variable, however the output is of type void and casting it doesn't work.

目前我只能使用paintComponent方法使用Graphics引用。但是,我想要存储一个形状(类似于void)的形状作为图形的实例变量...

At the moment I am only able to use a Graphics reference using the paintComponent method. However I want to be able to store a shape (which happens to be of type void) as an instance variable of type Graphic...

请考虑以下内容: p>

Consider the following:

test class{
      Graphics instanceOfGraphics;

      public void createShape(Graphics g1){
             g1.setPaint(new Color(255, 0, 0));
             instanceOfGraphics = g1.fillOval(//xPosition, //yPosition,
                                              //width, //height);

             }
          }

上面的源代码没有起作用,因为fillOval方法的返回类型是无效的,即使我尝试抛出静默的返回值,它也没有起作用。

The source code above did not work, because the return type of the fillOval method is void, even when I try to cast the silent return value it did not work.

我如何去保存/存储创建的形状作为变量。

How would I go about saving/storing the created shape as a variable.

将来我希望能够在Shape上注册一个监听器,并允许我创建的形状作为一个事件源。 / p>

In the future I would like to be able to register a Listener on the Shape and allow my created shape to be an event source.

推荐答案


上面的源代码不起作用,因为fillOval方法的返回类型是void,即使我试图抛出无声的返回值,它也无法正常工作。

The source code above did not work, because the return type of the fillOval method is void, even when I try to cast the silent return value it did not work.

您正在寻找存储效果这是不可能的,你想要做的是存储数据。如果要存储椭圆型数据,只需使用 Ellipse2D 字段即可存储信息。

You're looking at storing an effect which is impossible, and what you want to do is store data. If you want to store oval type data, simply use an Ellipse2D field and store the information there.

Ellipse2D ellipse = new Ellipse2D.Double(//xPosition, //yPosition,
                                          //width, //height);

然后用paintComponent中的Graphics2D对象绘制。

then draw it with your Graphics2D object within paintComponent.

Swing有一个有用的Shape界面,已经被实现为几个具体的类,可以很好地满足你的目的。

Swing has the useful Shape interface which has been implemented into several concrete classes that could serve your purpose well.

例如,

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.*;

public class GraphicsEg extends JPanel {
   private static final int PREF_W = 400;
   private static final int PREF_H = PREF_W;
   private List<Shape> shapes = new ArrayList<>();
   private Map<Shape, Color> shapeColorMap = new HashMap<>();

   public GraphicsEg() {
      Shape shape = new Ellipse2D.Double(10, 10, 30, 30);
      shapeColorMap.put(shape, Color.RED);
      shapes.add(shape);

      shape = new Rectangle2D.Double(140, 140, 200, 200);
      shapeColorMap.put(shape, Color.BLUE);
      shapes.add(shape);

      shape = new RoundRectangle2D.Double(200, 200, 80, 80, 10, 10);
      shapeColorMap.put(shape, Color.GREEN);
      shapes.add(shape);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      for (Shape shape : shapes) {
         Color color = shapeColorMap.get(shape);
         g2.setColor(color);
         g2.fill(shape);
      }
   }

   @Override
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }
   private static void createAndShowGui() {
      JFrame frame = new JFrame("GraphicsEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new GraphicsEg());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

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

这里有几个不同的形状(Ellipse2D,Rectangle2D,RoundRectangle2D)存储在Shape对象的ArrayList中,然后在将Graphics对象转换为Graphics2D之后,在JPanel的paintComponent方法中绘制这些对象。我还添加了一个 HashMap< Shape,Color> ,以便容易地将Shape与颜色相关联。

Here several different Shapes (Ellipse2D, Rectangle2D, RoundRectangle2D) are stored in an ArrayList of Shape objects, and then these are drawn within the JPanel's paintComponent method after first casting the Graphics object into a Graphics2D. I've also added a HashMap<Shape, Color> to allow easy association of a Shape with a Color.

另外你在评论中说,


将其用作事件源

use it as an event source

它为实现Shape的所有类提供了另一个有用的功能 - 它们有一个 contains(...)方法,如果与一个MouseListener将允许你轻松地看到鼠标点击你的一个形状。

which brings another useful feature about all classes that implement Shape -- they have a contains(...) method that if used well with a MouseListener will allow you to easily see if a mouse clicked inside of one of your shapes.

例如: p>

For example:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.*;

@SuppressWarnings("serial")
public class GraphicsEg extends JPanel {
   private static final int PREF_W = 400;
   private static final int PREF_H = PREF_W;
   private static final Color SELECTED_COLOR = Color.RED;
   private static final Stroke SELECTED_STROKE = new BasicStroke(8f);
   private List<Shape> shapes = new ArrayList<>();
   private Map<Shape, Color> shapeColorMap = new HashMap<>();
   private Shape selectedShape = null;

   public GraphicsEg() {
      Shape shape = new Ellipse2D.Double(10, 10, 90, 90);
      shapeColorMap.put(shape, Color.GRAY);
      shapes.add(shape);

      shape = new Rectangle2D.Double(140, 140, 200, 200);
      shapeColorMap.put(shape, Color.BLUE);
      shapes.add(shape);

      shape = new RoundRectangle2D.Double(200, 200, 80, 80, 10, 10);
      shapeColorMap.put(shape, Color.GREEN);
      shapes.add(shape);

      addMouseListener(new MyMouseListener());
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      for (Shape shape : shapes) {
         Color color = shapeColorMap.get(shape);
         g2.setColor(color);
         g2.fill(shape);
      }

      if (selectedShape != null) {
         Graphics2D newG2 = (Graphics2D) g2.create();
         newG2.setColor(SELECTED_COLOR);
         newG2.setStroke(SELECTED_STROKE);
         newG2.draw(selectedShape);
         newG2.dispose(); // because this is a created Graphics object
      }
   }

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

   private class MyMouseListener extends MouseAdapter {
      @Override
      public void mousePressed(MouseEvent e) {
         for (int i = shapes.size() - 1; i >= 0; i--) {
            if (shapes.get(i).contains(e.getPoint())) {
               selectedShape = shapes.get(i);
               repaint();
               return;
            }
         }
      }
   }

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

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

这篇关于保存信息 - 摇摆形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆