开发者社区> 问答> 正文

动画问题/画布切换问题

我正在开发一个程序,该程序应实质上使用户能够创建新画布,并能够通过单击下一个或上一个按钮在各种画布之间切换。按下此类按钮时,应立即出现动画。动画应复制翻书的页面。单击下一步时,页面应从右转到左,并显示下一个画布,反之亦然。我面临的问题是,当黑屏弹出并且没有切换时,我所拥有的程序无法正确显示动画,它应该显示当前页面以及下一页/上一页的某些屏幕。最重要的是,下一个和上一个按钮无法正确显示下一个或上一个画布。

package javaSwing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.awt.geom.*;
import java.util.List;
import java.awt.geom.RectangularShape;

import javax.swing.JTextArea;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;

public class guiInterface {
    static int shapeChecker = 0;
    static int currentCard = 0;
    static int size = 0;
    static JLabel status;
    static ArrayList<ContentArea> canvasPages;
    static JPanel cardPanel;
    static Container contain;
    static JMenuItem previous;
    static JMenuItem delete;
    static int numofCanvas = 0;
    static JMenuItem next;
    static JToggleButton color1;
    static ContentArea page;
    static Color newColor;
    static ContentArea canvasArea;

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

    private static void createAndShowGUI() {
        // create a new JFrame, which is a top-level window
        JFrame frame = new JFrame("Canvas Painter");
        cardPanel = new JPanel();

        // $1 Gesture Recognizer
        cardPanel.setPreferredSize(new Dimension(800, 600));
        JScrollPane scrollPane = new JScrollPane((cardPanel), JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollPane.getViewport().setPreferredSize(new Dimension(900, 700));
//      cardLayout = new RXCardLayout();
//      cardPanel.setLayout(cardLayout);
        cardPanel.setLayout(new BorderLayout());
        //cardPanel.add(new ContentArea(shapeChecker), BorderLayout.CENTER);
        canvasPages = new ArrayList<>();
        ContentArea initialContent = new ContentArea(shapeChecker);
        canvasPages.add(initialContent);
        cardPanel.add(initialContent, BorderLayout.CENTER);


        canvasArea = canvasPages.get(numofCanvas);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // sets up a menu bar
        JMenuBar menuBar = new JMenuBar();
        frame.setJMenuBar(menuBar);
        // setus up the file aspect of the menu bar
        JMenu file = new JMenu("File");
        menuBar.add(file);
        // adds the items for the file aspect
        JMenuItem newButton = new JMenuItem("New");
        file.add(newButton);
        delete = new JMenuItem("Delete");
        file.add(delete);
        JMenuItem quitButton = new JMenuItem("Quit");
        file.add(quitButton);
        // when clicked it will exit out of the program
        quitButton.addActionListener(e -> System.exit(0));
        // sets up the edit aspect of the menu bar
        JMenu edit = new JMenu("Edit");
        menuBar.add(edit);
        // sets up the view aspect of the menu bar
        JMenu view = new JMenu("View");
        menuBar.add(view);
        // adds the aspects to the view part of the program.
        next = new JMenuItem("Next");
        view.add(next);
        previous = new JMenuItem("Previous");
        view.add(previous);
        // Left Hand Side tool pallette
        // if possible add the toggle buttons to a group
        JPanel buttons = new JPanel(new GridLayout(0, 1));
        ButtonGroup group = new ButtonGroup();
        JToggleButton select = new JToggleButton();
        group.add(select);
        JToggleButton line = new JToggleButton();
        group.add(line);
        JToggleButton rectangle = new JToggleButton();
        group.add(rectangle);
        JToggleButton oval = new JToggleButton();
        group.add(oval);
        JToggleButton pen = new JToggleButton();
        group.add(pen);
        JToggleButton text = new JToggleButton();
        group.add(text);

        // adds the button to a JPanel called buttons
        buttons.add(select);
        buttons.add(line);
        buttons.add(rectangle);
        buttons.add(oval);
        buttons.add(pen);
        buttons.add(text);

        // main content area
        // Container content = frame.getContentPane();
        // content.setLayout(new BorderLayout());
        // final ContentArea canvas = new ContentArea(shapeChecker);
        // content.add(canvas, BorderLayout.CENTER);

        // status bar
        status = new JLabel();
        status.setText(" Status Bar");

        // This creates actions when each specific button is clicked.
        newButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                status.setText(" New button has been clicked");
                // Essentially create a new Content Area
                // when new button is pressed each time
                canvasPages.add(new ContentArea(shapeChecker));
                numofCanvas = canvasPages.size() - 1;
                cardPanel.add(canvasPages.get(numofCanvas), BorderLayout.CENTER);
            }
        });
        // should add a new canvas
        delete.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                delGest();
            }
        });

        // should delete the current tab
        next.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                nextGest();
            }
        });
        // should go to the next tab
        previous.addActionListener(new ActionListener() {
            // if the list gets to the beginning, disable button
            public void actionPerformed(ActionEvent e) {
                prevGest();
            }
        });
        // should go to the previous tab
        select.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                status.setText(" Select button has been clicked");
                shapeChecker = 0;
            }
        });
        line.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                status.setText(" Line button has been clicked");
                shapeChecker = 1;
            }
        });
        rectangle.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                status.setText(" Rectangle button has been clicked");
                shapeChecker = 2;
            }
        });
        oval.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                status.setText(" Ellipse button has been clicked");
                shapeChecker = 3;
            }
        });
        pen.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                status.setText(" Pen button has been clicked");
                shapeChecker = 4;
            }
        });
        text.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                status.setText(" Text button has been clicked");
                shapeChecker = 5;
            }
        });
        // Extra Credit
        // Color chooser
        color1 = new JToggleButton();
        color1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                chooseColor();
            }
        });

        // this pretty much says that a color has been chosen
        color1.addActionListener(e -> status.setText(" Color 1 Button has been clicked"));
        // adds the color button to the group
        // which is then added to the buttons JPanel
        group.add(color1);
        buttons.add(color1);
        // creates a pannel of the buttons, and other things
        JPanel left = new JPanel(new BorderLayout());
        left.add(buttons, BorderLayout.NORTH);
        frame.add(left, BorderLayout.WEST);
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
        frame.add(status, BorderLayout.SOUTH);
        frame.setSize(300, 300);

        // pack() causes the size of the frame to be set just large enough to contain
        // its
        // children; setVisible(true) puts it on the screen
        frame.revalidate();
        frame.pack();
        frame.setVisible(true);
    }

    public static void nextGest() {
        status.setText(" Next Canvas");
        if (numofCanvas != canvasPages.size() - 1) {
            canvasArea.pageFlipping(canvasPages.get(numofCanvas + 1) , true, 25);
            next.setEnabled(true);
        } else {
            next.setEnabled(false);
        }
    }

    public static void prevGest() {
        status.setText(" Previous Canvas");
        if (numofCanvas > 0) {
            canvasArea.pageFlipping(canvasPages.get(numofCanvas - 1) , false, 25);
        }
    }

    public static void delGest() {
        status.setText(" Deleting Canvas");
        if (canvasPages.size() == 1) {

        } else if (numofCanvas == 0) {
            cardPanel.remove(canvasPages.get(numofCanvas));
            canvasPages.remove(numofCanvas);
        } else {
            cardPanel.remove(canvasPages.get(numofCanvas));
            canvasPages.remove(numofCanvas);
            numofCanvas = -1;
        }
    }

    public static void chooseColor() {
        newColor = JColorChooser.showDialog(null, "Choose", color1.getBackground());
        if (newColor != null) {
            color1.setBackground(newColor);
        }
    }

}

// creates the content area and places it in the text area
class ContentArea extends JComponent {
    int x = 0;
    int y = 0;
    int width = 0;
    int height = 0;
    int oldX = 0;
    int oldY = 0;
    int currentX = 0;
    int currentY = 0;
    int mpShapeX = 0;
    int mpShapeY = 0;
    int mpShapeX2 = 0;
    int mpShapeY2 = 0;
    Rectangle2D rect;
    int prevX = 0;
    int prevY = 0;
    int directionDiffX = 0;
    int directionDiffY = 0;
    int threshold = 20;
    int xDirection = 0;
    int yDirection = 0;
    int initialptX = 0;
    int initialptY = 0;

    Timer timer;
    BufferedImage offScreenImage;
    int flipPageX = 0;
    int iterations = 0;
    int flipPageY = 0;
    boolean flag = false;
    boolean forwards = false;
    double dx;
    double dy;
    Point startPoint;
    Point prevPoint;
    ArrayList<Shape> variousShapes = new ArrayList<Shape>();
    ArrayList<Shape> shapestoDel = new ArrayList<Shape>();
    Shape theShape;
    Shape shapetoDrag;
    Shape clearer;
    boolean selected = false;
    boolean clear = false;
    boolean dragging = false;
    boolean goingNorth = false;
    boolean goingSouth = false;
    boolean goingEast = false;
    boolean goingWest = false;
    boolean snappedN = false;
    boolean snappedS = false;
    boolean snapped = false;
    boolean snappedE = false;
    boolean snappedW = false;
    boolean resizable = true;

    private int pos = -1;
    ArrayList<Point2D> points = null;
    ContentArea area;
    private Point2D.Double offset;

    public ContentArea(int shapeChecker) {
        int shapeNum = shapeChecker;
        // setDoubleBuffered(false);
        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                if (SwingUtilities.isLeftMouseButton(e)) {
                    // search through arraylist that finds a shape that contains the mouse
                    // if found then selected variable will be true
                    // save shape into a variable
                    oldX = e.getX();
                    oldY = e.getY();
                    initialptX = e.getX();
                    initialptY = e.getY();
                    currentX = oldX;
                    currentY = oldY;
                    Point p = e.getPoint();
                    startPoint = new Point(e.getX(), e.getY());
                    if (guiInterface.shapeChecker == 0) {
                        for (Shape mpShapes : variousShapes) {
                            if (mpShapes.contains(startPoint)) {
                                if (mpShapes instanceof Rectangle2D || mpShapes instanceof Ellipse2D
                                        || mpShapes instanceof Line2D) {
                                    selected = true;
                                    shapetoDrag = mpShapes;
                                    offset = new Point2D.Double(oldX - shapetoDrag.getBounds2D().getX(),
                                            oldY - shapetoDrag.getBounds2D().getY());
                                }
                            }
                        }
                    }
                } else {
                    points = new ArrayList<Point2D>();
                    // translate to canvas coordinate system
                    Point p = e.getPoint();
                    points.add(p);

                     if (e.getX() < 10) {
                         if (guiInterface.numofCanvas > 0) {
                             flag = true;
                             forwards = false;
                             offScreenImage = ImageRender.makeOffscreenImage(guiInterface.canvasPages.get(guiInterface.numofCanvas - 1));
                             flipPageX = e.getX();
                         }
                     } else if (e.getX() > guiInterface.cardPanel.getWidth() - 10) {
                         if (guiInterface.numofCanvas != guiInterface.canvasPages.size() - 1) {
                             flag = true;
                             forwards = true;
                             offScreenImage = ImageRender.makeOffscreenImage(guiInterface.canvasPages.get(guiInterface.numofCanvas - 1));
                         }

                     } else {

                     }
                }
                repaint();
            }

            public void mouseReleased(MouseEvent e) {
                if (SwingUtilities.isLeftMouseButton(e)) {

                } else {
                    if (flag) {
                        if (forwards) {
                            if (e.getX() > guiInterface.cardPanel.getWidth() / 2) {
                                pageflipStops(e.getX());
                            } else if (e.getX() < guiInterface.cardPanel.getWidth() / 2 && e.getX() > 40) {
                                animationComplete(e.getX());
                            } else {
                                flag = false;
                                repaint();
                                revalidate();
                                guiInterface.numofCanvas += 1;
                            }
                        } else {
                            if (e.getX() < guiInterface.cardPanel.getWidth() / 2) {
                                pageflipStops(e.getX());
                            } else if (e.getX() > guiInterface.cardPanel.getWidth() / 2 && e.getX() < guiInterface.cardPanel.getWidth() - 40) {
                                animationComplete(e.getX());
                            } else {
                                flag = false;
                                repaint();
                                revalidate();
                                guiInterface.numofCanvas -= 1;
                            }
                        }
                    }
                    repaint();
                }
                if (theShape != null) {
                    variousShapes.add(theShape);
                }
            }
        });
        addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                // check if selected shape, if so, then adjust the shapes
                // location and repaint.
                if (SwingUtilities.isLeftMouseButton(e)) {

                    // in this case, the drawing points should be recognized
                    if (guiInterface.shapeChecker == 4) {
                        selected = false;
                        oldX = e.getX();
                        oldY = e.getY();
                        repaint();
                    }
                } else {
                    Point p = e.getPoint();
                    points.add(p);
                    repaint();
                }
            }
        });
    }

    public void pageFlipping(ContentArea change, boolean forwards, int n) {
        offScreenImage = ImageRender.makeOffscreenImage(change);
        flag = true;
        this.forwards = forwards;
        timer = new Timer(75, new ActionListener() {
            public void actionPerformed(ActionEvent ev) {
                if (iterations < n) {
                    if (forwards) {
                        flipPageX = change.getWidth() - (iterations + 1) * (change.getWidth()) / n;
                    } else {
                        flipPageX = (iterations) * (change.getWidth() / n);
                    }
                    flipPageY = 0;
                    repaint();
                    revalidate();
                    iterations++;
                } else {
                    timer.stop();
                    flag = false;
                    iterations = 0;
                    repaint();
                    revalidate();
                    if (forwards) {
                        guiInterface.numofCanvas += 1;
                    } else {
                        guiInterface.numofCanvas -= 1;

                    }
                    // Display the next or previous page after the last iteration
                    // Should go to the next page


                    //
                }
            }
        });
        timer.start();
    }

    public void pageflipStops(int a) {
        iterations = 0;
        int goingforward = offScreenImage.getWidth() - a;
        timer = new Timer(75, new ActionListener() {
            public void actionPerformed(ActionEvent ev) {
                if (iterations < 10) {
                    if (forwards) {
                        flipPageX = a - (iterations + 1) * (a / 12);
                    } else {
                        flipPageX = a + (iterations) * (goingforward / 12);
                    }
                    repaint();
                    revalidate();
                    iterations++;
                } else {
                    timer.stop();
                    flag = false;
                    iterations = 0;
                    repaint();
                    revalidate();
                }
            }
        });
        timer.start();
    }

    public void animationComplete(int a) {
        iterations = 0;
        int goingforward = offScreenImage.getWidth() - a;
        timer = new Timer(75, new ActionListener() {
            public void actionPerformed(ActionEvent ev) {
                if (iterations < 12) {
                    if (forwards) {
                        flipPageX = a - (iterations + 1) * (12 / 10);
                    } else {
                        flipPageX = a + (iterations) * (goingforward / 12);
                    }
                    repaint();
                    revalidate();
                    iterations++;
                } else {
                    timer.stop();
                    flag = false;
                    iterations = 0;
                    repaint();
                    revalidate();
                }
                if (forwards) {
                    guiInterface.nextGest();
                } else {
                    guiInterface.prevGest();
                }
            }
        });
        timer.start();
    }

    public void paintComponent(Graphics g) {
        if (dragging) {
            Graphics2D g2d = (Graphics2D) g.create();
            Stroke dashed = new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 9 }, 0);
            g2d.setStroke(dashed);
            g2d.setColor(Color.GRAY);
            for (int x = 100; x < getWidth(); x += 100)
                g2d.drawLine(x, 0, x, getHeight());
            for (int y = 100; y < getHeight(); y += 100)
                g2d.drawLine(0, y, getWidth(), y);
        }

        Graphics2D graphics1 = (Graphics2D) g;
        Graphics2D graphics2 = (Graphics2D) g;
        Graphics2D graphics3 = (Graphics2D) g;
        ArrayList<Point2D> points = getPoints();

        super.paintComponent(g);
        graphics1.setStroke(new BasicStroke(4));
        graphics1.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics1.setColor(guiInterface.newColor);
        for (Shape s : variousShapes) {
            graphics1.draw(s);
        }
        // gesture line
        if (points != null) {
            for (int i = 0; i < points.size() - 1; i++) {
                Point2D p1 = points.get(i);
                Point2D p2 = points.get(i + 1);
                graphics2.setStroke(new BasicStroke(3));
                graphics2.setPaint(Color.red);
                graphics2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                graphics1.drawLine((int) p1.getX(), (int) p1.getY(), (int) p2.getX(), (int) p2.getY());
            }
        }
        // check to see if page is flipping
        // if so it draws it
        if (flag) {
            if (forwards) {
                BufferedImage portion = offScreenImage.getSubimage(flipPageX, flipPageY, this.getWidth() - flipPageX,
                        this.getHeight());
                graphics3.drawImage(portion, flipPageX, flipPageY, this);
            } else {
                BufferedImage portion = offScreenImage.getSubimage(0, 0, flipPageX,
                        this.getHeight());
                graphics3.drawImage(portion, 0, 0, this);
            }
            graphics3.drawRoundRect(flipPageX, flipPageY, 30, this.getHeight(), 5, 5);
            graphics3.setColor(new Color(250, 242, 173));
            graphics3.fillRoundRect(flipPageX, flipPageY, 30, this.getHeight(), 5, 5);
            graphics3.setColor(Color.BLACK);
        }
        repaint();
    }

    public void paintChildren(Graphics g) {
        //Only allow the current page to be visible in "normal" mode
            super.paintChildren(g);
            int index = 0;
            for (Component comp: guiInterface.canvasPages) {
                if (index != guiInterface.numofCanvas) {
                    comp.setVisible(false);
                } else {
                    comp.setVisible(true);
                }
                index++;

        }
    }
    public ArrayList<Point2D> getPoints() {
        return points;
    }

    private void updateStatus(Result r) {
        if (r == null) {
            guiInterface.status.setText("null result");
        } else if (r.getName().equals("No match")) {
            guiInterface.status.setText("No match");
        } else {
            Rectangle rect = r.getBoundingBox();
            guiInterface.status.setText(r.getName() + " (score=" + r.getScore() + ") " + " bbox: x=" + rect.getX()
                    + " y=" + rect.getY() + " w=" + rect.getWidth() + " h=" + rect.getHeight());
        }
    }
}

展开
收起
垚tutu 2019-12-04 16:19:11 620 0
0 条回答
写回答
取消 提交回答
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载