Java 使用 slider 调整形状大小

标签 java swing resize java-2d shapes

代码如下:

主.java:

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

/**
 * Winter Assignment for Java 2012/13
 */

// Class definition

public class Main extends JPanel implements ActionListener {

    private JSlider sizeslider;
    private int startX, startY, endX, endY, val;
    private Color shapeColor = Color.black;
    private JComboBox shapeChoice, colorChoice;
    private Point firstPoint;
    private Circle firstCircle;
    private Square firstSquare;
    private Doughnut firstDoughnut;
    private Triangle firstTriangle;
    private Pentagon firstPentagon;
    private Point aShape;
    static final int SlideMin = 10;
    static final int SlideMax = 110;
    static final int SlideInit = 50;

    // Constructor method declaration

    public Main() {

        //Create the slider.
        sizeslider = new JSlider(JSlider.HORIZONTAL, SlideMin, SlideMax, SlideInit);
        add(sizeslider, BorderLayout.NORTH);

        shapeChoice = new JComboBox();
        shapeChoice.addItem("Point");
        shapeChoice.addItem("Square");
        shapeChoice.addItem("Circle");
        shapeChoice.addItem("Doughnut");
        shapeChoice.addItem("Triangle");
        shapeChoice.addItem("Pentagon");
        add(shapeChoice);
        shapeChoice.addActionListener(this);

        colorChoice = new JComboBox();
        colorChoice.addItem("Black");
        colorChoice.addItem("Red");
        colorChoice.addItem("Green");
        colorChoice.addItem("Blue");
        colorChoice.addItem("Yellow");
        colorChoice.addItem("Purple");
        colorChoice.addItem("Turquoise");
        add(colorChoice);
        colorChoice.addActionListener(this);


    this.addMouseListener(new MouseAdapter() {
    public void mouseReleased(MouseEvent me) {
        repaint();
    }

    public void mouseDragged(MouseEvent me) {
        aShape.moveXY(me.getX(), me.getY());
        repaint();
    }
});

    this.addMouseMotionListener(new MouseAdapter() {
    public void mouseReleased(MouseEvent me) {
        repaint();
    }

    public void mouseDragged(MouseEvent me) {
        aShape.moveXY(me.getX(), me.getY());
        repaint();
    }
});

    sizeslider.addChangeListener(new ChangeListener() {
  public void stateChanged(ChangeEvent e) {
     JSlider source = (JSlider)e.getSource();  // get the slider
     if (!source.getValueIsAdjusting()) {
         val = source.getValue();  // get slider value
         aShape.reSize(val);
         repaint();
  }
}
});



        // Instantiate shape classes
        firstPoint = new Point();
        firstCircle = new Circle();
        firstSquare = new Square();
        firstDoughnut = new Doughnut();
        firstTriangle = new Triangle();
        firstPentagon = new Pentagon();


        // Initially assign aShape a Point object
        aShape = firstPoint;

        // Create a new window using the Swing class JFrame and add this panel
        makeFrame();
    }

    public void actionPerformed(ActionEvent e) {
        // Manipulate respective object when buttons pressed

       // checkbox assigns object to aShape
        if (e.getSource() == shapeChoice) {
            if (shapeChoice.getSelectedItem().equals("Circle"))
                aShape = firstCircle;
            else if (shapeChoice.getSelectedItem().equals("Square"))
                aShape = firstSquare;
            else if (shapeChoice.getSelectedItem().equals("Point"))
                aShape = firstPoint;
            else if (shapeChoice.getSelectedItem().equals("Doughnut"))
                aShape = firstDoughnut;
            else if (shapeChoice.getSelectedItem().equals("Triangle"))
                aShape = firstTriangle;
            else if (shapeChoice.getSelectedItem().equals("Pentagon"))
                aShape = firstPentagon;
        }


        // Assigns color to shape
        else if (e.getSource() == colorChoice) {
            if (colorChoice.getSelectedItem().equals("Black")) {
                shapeColor = Color.black;
                repaint();
            }
            else if (colorChoice.getSelectedItem().equals("Red")) {
                shapeColor = Color.red;
                repaint();
            }
            else if (colorChoice.getSelectedItem().equals("Green")) {
                shapeColor = Color.green;
                repaint();
            }
            else if (colorChoice.getSelectedItem().equals("Blue")) {
                shapeColor = Color.blue;
                repaint();
            }
            else if (colorChoice.getSelectedItem().equals("Yellow")) {
                shapeColor = Color.yellow;
                repaint();
            }
            else if (colorChoice.getSelectedItem().equals("Purple")) {
                shapeColor = Color.decode("#9B30FF"); //Assignment said purple, but purple isn't defined in the Java api, so I used the hex code. The closest color in the API is Magenta.
                repaint();
            }
            else if (colorChoice.getSelectedItem().equals("Turquoise")) {
                shapeColor = Color.decode("#40E0D0"); //Turquoise hex code
                repaint();
            }
        }

        // Ask Java to repaint the window to reflect the updates made
        repaint();
    }

    // Provide this method to instruct Java what to do when repainting the window
    public void paintComponent(Graphics g) {

        super.paintComponent(g);

        g.setColor(shapeColor);

        // Call the respective methods from respective class to print the new co-ordinate values
        aShape.outputXYCoords(g);

        // Call the respective methods from respective class to redraw the shape
        aShape.display(g);
    }


    // Create a window frame

    public void makeFrame() {

        // Instantiate a window frame using Swing class JFrame
        JFrame frame = new JFrame("Winter Assignment");

        // When the window is closed terminate the application
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        // set initial size of window
        frame.setSize(800, 600);

        // add the current object to the centre of the frame and make visible
        frame.getContentPane().add(this, BorderLayout.CENTER);
        frame.setVisible(true);
    }   
}

三角形.java

其中一个shape文件,它们都具有相同的结构:

三角形.java

import java.awt.*;

public class Triangle extends Point {
    protected int size;
    private int p1x, p2x, p3x, p1y, p2y, p3y;

    //Create a new triangle
    public Triangle()
    {
        super();
        size = 50;
        yPos = 100;
    }


    public void reSize(int newSize) {
        size = size + newSize;
    }

    //Draw the triangle with current specifications on screen.
    public void display(Graphics g) {
        p1x = xPos;
        p2x = xPos + size/2;
        p3x = xPos + size;
        p1y = yPos + size;
        p2y = yPos;
        p3y = yPos + size;
        int[] xPoints = { p1x, p2x, p3x };
        int[] yPoints = { p1y, p2y, p3y };
        int npoints = 3;
        g.fillPolygon(xPoints, yPoints, npoints);
    } 
}
  • 我希望发生的事情: slider 会将形状的大小调整为它设置的值。
  • 实际发生了什么: aShape.reSize(val); 通过 slider 值的增加来增加形状的大小。

我不确定如何解决它。那里也有一些垃圾代码,但我只是用它来引用发生的事情。

最佳答案

What I was hoping would happen: The slider would resize the shape to the value it's put on.

这是我制作的一个简短示例,它会将正方形的宽度和高度增加/减少到 slider 上的数量,即在 50 时,正方形的宽度和高度为 50,在 60 时,它们为 60,依此类推。

这是通过允许访问实例字段的 getter 和 setter 完成的,然后我们将 ChangeListener 添加到 JSlider 以检测更改的值(value),在那里我们使用我们的 setter 设置实例的值并调用 repaint() 调用 JPanelpaintComponent 它将调用draw(Graphcis2D g2d) 形状以反射(reflect)容器上的变化:

enter image description here

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class ShapeAndSliderTest {

    public ShapeAndSliderTest() {
        createAndShowGui();
    }

    private void createAndShowGui() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        final MyRectangle myRectangle = new MyRectangle(10, 10, 50,50, Color.RED);

        JSlider jslider = new JSlider();
        jslider.setValue(50);
        jslider.setMaximum(250);
        jslider.setMinorTickSpacing(5);
        jslider.setMajorTickSpacing(10);
        jslider.setPaintTicks(true);
        jslider.setPaintLabels(true);

        // We'll just use the standard numeric labels for now...
        jslider.setLabelTable(jslider.createStandardLabels(50));

        final JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics grphcs) {
                super.paintComponent(grphcs);

                Graphics2D g2d = (Graphics2D) grphcs;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

                myRectangle.draw(g2d);
            }

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

        jslider.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent ce) {
                JSlider slider = (JSlider) ce.getSource();

                if (!slider.getValueIsAdjusting()) {
                    int newW = slider.getValue();
                    int newH = slider.getValue();

                    myRectangle.setWidth(newW);
                    myRectangle.setHeight(newH);

                    System.out.println(newW + "," + newH);

                    panel.repaint();
                }
            }
        });

        frame.add(jslider, BorderLayout.SOUTH);
        frame.add(panel, BorderLayout.CENTER);

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

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

class MyRectangle {

    private int x, y, width, height;
    private final Color color;

    public MyRectangle(int x, int y, int w, int h, Color color) {
        this.x = x;
        this.y = y;
        this.width = w;
        this.height = h;
        this.color = color;
    }

    void draw(Graphics2D g2d) {
        Color prevState = g2d.getColor();

        g2d.setColor(color);

        g2d.drawRect(x, y, width, height);

        g2d.setColor(prevState);

    }

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }

    public void setWidth(int w) {
        this.width = w;
    }

    public void setHeight(int h) {
        this.height = h;
    }

    public int getHeight() {
        return height;
    }

    public int getWidth() {
        return width;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
}

关于Java 使用 slider 调整形状大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14540212/

相关文章:

resize - 防止抽动标签在 gnuplot 中调整图形大小

javascript - 如何为可调整大小的 jQuery UI 元素启动调整大小功能(触发句柄拖动)

java - 为什么 java 要求我阻止可能不安全的组件 - 所有 jar 都已签名

java - 如何在javafx和webview中创建或获取输入的xpath

java - 如果 Itunes :Keep iTunes Folder Organized is set programmatically on Windows,我该如何解决

java - Swing 组件不显示

css - 带有图像(作为链接)的透明框(div)——可按比例调整大小?

java - 从 JSNI 类创建 GWT jar

java - 使用 DbUtils 从 SQL 添加列到现有表

java - JTextArea 在父缩小时不换行