将 JLabel 移动到其他 JLabel - GUI

2024-02-28

我正在尝试使 JLabel 跨其他 JLabel 移动,目前只有 1 个计时器在工作。它的运行方式应该像火车穿过铁轨一样,绕着铁轨一路行驶,最终回到起点。我不知道如何让它一路顺利,任何帮助都是值得赞赏的。

谢谢。

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.JTextField;

import java.awt.Color;

import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.border.BevelBorder;

public class MoveLabel {
    private JTextField textField;
    private JTextField tf;
    private JTextField textField_1;
    private JTextField textField_2;
    private JTextField textField_3;
    private JTextField textField_5;
    private JTextField textField_6;
    private JTextField textField_7;
    private JTextField textField_8;
    private JTextField textField_9;
    private JTextField textField_10;
    private JTextField textField_11;
    private JTextField textField_12;
    private JTextField textField_13;
    private JTextField textField_14;
    private JTextField textField_15;
    private JTextField textField_16;
    private JTextField textField_17;
    private JTextField textField_18;
    private JTextField textField_19;
    private JTextField textField_20;
    private JTextField textField_21;
    private JTextField textField_22;
    private JTextField textField_23;
    private JTextField textField_24;
    private JTextField textField_25;
    private JTextField textField_26;
    private JSlider slider;
    private JSlider slider_1;
    private JSlider slider_2;

    public static void main(String[] args) {
        new MoveLabel();
    }

    public MoveLabel() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.getContentPane().setLayout(new BorderLayout());
                TestPane testPane = new TestPane();
                testPane.setBackground(Color.WHITE);
                frame.getContentPane().add(testPane);

                textField = new JTextField();
                textField.setBounds(100, 138, 20, 20);
                testPane.add(textField);
                textField.setColumns(10);


                textField_1 = new JTextField();
                textField_1.setColumns(10);
                textField_1.setBounds(80, 44, 20, 20);
                testPane.add(textField_1);

                textField_2 = new JTextField();
                textField_2.setColumns(10);
                textField_2.setBounds(120, 44, 20, 20);
                testPane.add(textField_2);

                textField_3 = new JTextField();
                textField_3.setColumns(10);
                textField_3.setBounds(160, 44, 20, 20);
                testPane.add(textField_3);

                textField_5 = new JTextField();
                textField_5.setColumns(10);
                textField_5.setBounds(140, 138, 20, 20);
                testPane.add(textField_5);

                textField_6 = new JTextField();
                textField_6.setColumns(10);
                textField_6.setBounds(160, 138, 20, 20);
                testPane.add(textField_6);

                textField_7 = new JTextField();
                textField_7.setColumns(10);
                textField_7.setBounds(120, 138, 20, 20);
                testPane.add(textField_7);

                textField_8 = new JTextField();
                textField_8.setColumns(10);
                textField_8.setBounds(80, 59, 20, 20);
                testPane.add(textField_8);

                textField_9 = new JTextField();
                textField_9.setColumns(10);
                textField_9.setBounds(80, 75, 20, 20);
                testPane.add(textField_9);

                textField_10 = new JTextField();
                textField_10.setColumns(10);
                textField_10.setBounds(80, 90, 20, 20);
                testPane.add(textField_10);

                textField_11 = new JTextField();
                textField_11.setColumns(10);
                textField_11.setBounds(80, 106, 20, 20);
                testPane.add(textField_11);

                textField_12 = new JTextField();
                textField_12.setColumns(10);
                textField_12.setBounds(80, 123, 20, 20);
                testPane.add(textField_12);

                textField_13 = new JTextField();
                textField_13.setColumns(10);
                textField_13.setBounds(179, 44, 20, 20);
                testPane.add(textField_13);

                textField_14 = new JTextField();
                textField_14.setColumns(10);
                textField_14.setBounds(199, 44, 20, 20);
                testPane.add(textField_14);

                textField_15 = new JTextField();
                textField_15.setColumns(10);
                textField_15.setBounds(80, 138, 20, 20);
                testPane.add(textField_15);

                textField_16 = new JTextField();
                textField_16.setColumns(10);
                textField_16.setBounds(100, 44, 20, 20);
                testPane.add(textField_16);

                textField_17 = new JTextField();
                textField_17.setColumns(10);
                textField_17.setBounds(140, 44, 20, 20);
                testPane.add(textField_17);

                textField_18 = new JTextField();
                textField_18.setColumns(10);
                textField_18.setBounds(179, 138, 20, 20);
                testPane.add(textField_18);

                textField_19 = new JTextField();
                textField_19.setColumns(10);
                textField_19.setBounds(199, 138, 20, 20);
                testPane.add(textField_19);

                textField_20 = new JTextField();
                textField_20.setColumns(10);
                textField_20.setBounds(219, 63, 20, 20);
                testPane.add(textField_20);

                textField_21 = new JTextField();
                textField_21.setColumns(10);
                textField_21.setBounds(219, 138, 20, 20);
                testPane.add(textField_21);

                textField_22 = new JTextField();
                textField_22.setBackground(Color.WHITE);
                textField_22.setColumns(10);
                textField_22.setBounds(219, 44, 20, 20);
                testPane.add(textField_22);

                textField_23 = new JTextField();
                textField_23.setColumns(10);
                textField_23.setBounds(219, 123, 20, 20);
                testPane.add(textField_23);

                textField_24 = new JTextField();
                textField_24.setColumns(10);
                textField_24.setBounds(219, 99, 20, 27);
                testPane.add(textField_24);

                textField_25 = new JTextField();
                textField_25.setColumns(10);
                textField_25.setBounds(219, 83, 20, 20);
                testPane.add(textField_25);

                textField_26 = new JTextField();
                textField_26.setColumns(10);
                textField_26.setBounds(219, 90, 20, 20);
                testPane.add(textField_26);

                slider_2 = new JSlider();
                slider_2.setMaximum(3);
                slider_2.setPaintTicks(true);
                slider_2.setSnapToTicks(true);
                slider_2.setOrientation(SwingConstants.VERTICAL);
                slider_2.setBounds(533, 260, 57, 229);
                testPane.add(slider_2);




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

    public static class TestPane extends JPanel {

        protected static final int PLAY_TIME = 4000;

        private JLabel label;
        private JTextField tf;
        private int targetX;
        private int targetY;
        private int targetX2;
        private int targetY2;
        private long startTime;
        private long startTime2;
        private final int startX;
        private final int startY;
        private final int startX2;
        private final int startY2;



        public TestPane() {
            setLayout(null);
            tf = new JTextField("");
            tf.setSize(20,20);
            tf.setBackground(Color.red);
            add(tf);



            Dimension size = getPreferredSize();

            startX = 80;
            startY = 44;

          /*  targetX = (size.width - label.getSize().width) / 2;
            targetY = (size.height - label.getSize().height) / 2;
            */
            targetX = 140;
            targetY = 44;



            Timer timer = new Timer(40, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    int x = tf.getX();
                    int y = tf.getY();
                    long duration = System.currentTimeMillis() - startTime;
                    float progress = (float)duration / (float)PLAY_TIME;
                    if (progress > 1f) {
                        progress = 1f;
                        ((Timer)(e.getSource())).stop();
                    }

                    x = startX + (int)Math.round((targetX - startX) * progress);
                    y = startY + (int)Math.round((targetY - startY) * progress);

                    tf.setLocation(x, y);

                }
            });
            startTime = System.currentTimeMillis();
            timer.start();
           /* try {
                Thread.sleep(10);
            }
            catch (InterruptedException ie) {
                ie.printStackTrace();
            }
            if (timer.isRunning() != true)
            {
            timer.stop();
            }*/

            startX2 = targetX;
            startY2 = targetY;

            tf.setLocation(startX,startY);

          /*  targetX = (size.width - label.getSize().width) / 2;
            targetY = (size.height - label.getSize().height) / 2;
            */
            targetX2 = 219;
            targetY2 = 44;


            Timer timer2 = new Timer(40, new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    int x2 = tf.getX();
                    int y2 = tf.getY();
                    long duration = System.currentTimeMillis() - startTime2;
                    float progress = (float)duration / (float)PLAY_TIME;
                    if (progress > 1f) 
                    {
                        progress = 1f;
                        ((Timer)(e.getSource())).stop();
                    }

                    x2 = startX2 + (int)Math.round((targetX2 - startX2) * progress);
                    y2 = startY2 + (int)Math.round((targetY2 - startY2) * progress);

                    tf.setLocation(x2, y2);
                    tf.getLocation();


                }
            });
            startTime2 = System.currentTimeMillis();


            if (timer.isRunning() == false)
            {
            //
            timer2.start();
            }
            else 
            {
                timer2.setDelay(10);
            }

        }   

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(600, 500);

    }

  }
}

注:我不喜欢null布局,我不容忍null布局,我更愿意使用自定义绘画,但这是很多与问题无关的工作。这个例子的目的是重点关注一个Timeline and KeyFrame动画片

因为您必须在同一时间段内将对象移动到两个 x/y 位置,但方向不同,所以这成为一个非常复杂的问题...

你可以尝试设置四个,用链子拴起来Timers,触发下一个Timer当它们完成时,它们都执行动画的不同部分……但坦率地说,这很快就会变得一团糟……

更好的想法是使用时间线和关键帧的概念。这个想法是,在时间线(0-1)内,某些事件在规定的时间(关键帧)发生。然后时间线将在这些关键帧之间混合......

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MoveLabel {

    public static void main(String[] args) {
        new MoveLabel();
    }

    public MoveLabel() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.getContentPane().setLayout(new BorderLayout());
                TestPane testPane = new TestPane();
                testPane.setBackground(Color.WHITE);
                frame.getContentPane().add(testPane);

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

    public static class TestPane extends JPanel {

        private JTextField tf;
        private List<JTextField> tracks;

        protected static final int PLAY_TIME = 4000;

        private Timeline timeline;
        private long startTime;

        public TestPane() {
            setLayout(null);

            tracks = new ArrayList<JTextField>(20);

            int x = 20;
            int y = 20;

            for (int index = 0; index < 6; index++) {
                x += 20;
                tracks.add(createTrack(x, y, 20, 20));
            }
            for (int index = 0; index < 6; index++) {
                y += 20;
                tracks.add(createTrack(x, y, 20, 20));
            }
            for (int index = 0; index < 6; index++) {
                x -= 20;
                tracks.add(createTrack(x, y, 20, 20));
            }
            for (int index = 0; index < 6; index++) {
                y -= 20;
                tracks.add(createTrack(x, y, 20, 20));
            }

            for (JTextField track : tracks) {
                add(track);
            }

            tf = new JTextField("");
            tf.setSize(20, 20);
            tf.setBackground(Color.red);
            add(tf);
            setComponentZOrder(tf, 0);

            timeline = new Timeline();
            timeline.add(0, new Point(20, 20));
            timeline.add(0.25f, new Point(20 * 7, 20));
            timeline.add(0.5f, new Point(20 * 7, 20 * 7));
            timeline.add(0.75f, new Point(20, 20 * 7));
            timeline.add(1f, new Point(20, 20));

            Timer timer = new Timer(40, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    long duration = System.currentTimeMillis() - startTime;
                    float progress = (float) duration / (float) PLAY_TIME;
                    if (progress > 1f) {
                        startTime = System.currentTimeMillis();
                        progress = 0;
//                      ((Timer) (e.getSource())).stop();
                    }

                    Point p = timeline.getPointAt(progress);
                    tf.setLocation(p);

                }
            });
            startTime = System.currentTimeMillis();
            timer.start();

        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(600, 500);

        }

        protected JTextField createTrack(int x, int y, int width, int height) {
            JTextField field = new JTextField();
            field.setBounds(x, y, width, height);
            field.setEditable(false);
            field.setFocusable(false);
            return field;
        }

    }

    public static class Timeline {

        private Map<Float, KeyFrame> mapEvents;

        public Timeline() {
            mapEvents = new TreeMap<>();
        }

        public void add(float progress, Point p) {
            mapEvents.put(progress, new KeyFrame(progress, p));
        }

        public Point getPointAt(float progress) {

            if (progress < 0) {
                progress = 0;
            } else if (progress > 1) {
                progress = 1;
            }

            KeyFrame[] keyFrames = getKeyFramesBetween(progress);

            float max = keyFrames[1].progress - keyFrames[0].progress;
            float value = progress - keyFrames[0].progress;
            float weight = value / max;

            return blend(keyFrames[0].getPoint(), keyFrames[1].getPoint(), 1f - weight);

        }

        public KeyFrame[] getKeyFramesBetween(float progress) {

            KeyFrame[] frames = new KeyFrame[2];
            int startAt = 0;
            Float[] keyFrames = mapEvents.keySet().toArray(new Float[mapEvents.size()]);
            while (startAt < keyFrames.length && keyFrames[startAt] <= progress) {
                startAt++;
            }

            if (startAt >= keyFrames.length) {
                startAt = keyFrames.length - 1;
            }

            frames[0] = mapEvents.get(keyFrames[startAt - 1]);
            frames[1] = mapEvents.get(keyFrames[startAt]);

            return frames;

        }

        protected  Point blend(Point start, Point end, float ratio) {
            Point blend = new Point();

            float ir = (float) 1.0 - ratio;

            blend.x = (int)(start.x * ratio + end.x * ir);
            blend.y = (int)(start.y * ratio + end.y * ir);

            return blend;
        }

        public class KeyFrame {

            private float progress;
            private Point point;

            public KeyFrame(float progress, Point point) {
                this.progress = progress;
                this.point = point;
            }

            public float getProgress() {
                return progress;
            }

            public Point getPoint() {
                return point;
            }

        }

    }
}

然后你可以做一些愚蠢的事情,比如改变部分之间的速度......

timeline = new Timeline();
timeline.add(0, new Point(20, 20));
timeline.add(0.1f, new Point(20 * 7, 20));
timeline.add(0.5f, new Point(20 * 7, 20 * 7));
timeline.add(0.6f, new Point(20, 20 * 7));
timeline.add(1f, new Point(20, 20));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 JLabel 移动到其他 JLabel - GUI 的相关文章

  • 配置 Eclipse 将 App Engine 类预先捆绑到单个 JAR 中以加快预热速度

    在与另一家同样使用 App Engine 的公司的同事进行讨论后 他告诉我 他通过以下步骤成功地将应用程序预热时间从约 15 秒缩短到约 5 秒 配置 Eclipse 将编译过程中生成的类捆绑到单个 JAR 文件中 配置 Eclipse 以
  • 使用 s:select 标签在下拉菜单中使用 i18n [重复]

    这个问题在这里已经有答案了 我的 JSP 页面中有一个下拉菜单 它是通过
  • Java 8 可选

    我想检查特定对象大小是否大于 0 如果它大于 0 那么我想创建一个可选对象 如果不是 那么我想返回一个可选的空对象 这是java代码的长版本 if fooA size gt 0 return Optional of new Foo else
  • 如何将参数传递给Workmanager DoWork方法

    我想安排任务在 24 小时后从数据库中删除 public class WorkManager extends Worker public WorkManager NonNull Context context NonNull WorkerP
  • 将 java 方法参数设置为最终参数

    那有什么区别final在下面的代码之间进行 将参数声明为有什么好处final public String changeTimezone Timestamp stamp Timezone fTz Timezone toTz return pu
  • 在 JList 中写一些东西

    嘿 我还有另一个问题 我创建JList在我的主窗口中 现在我想向其中添加一些内容 我这样做 private void jButton2ActionPerformed java awt event ActionEvent evt Dodaj
  • 如何知道内存中是否已经存在类的实例?

    如何知道内存中是否已经存在类的实例 我的问题是 如果存在类实例 则不想读取方法 这是我的代码 private void jButton java awt event ActionEvent evt PNLSpcMaster pnlSpc n
  • Jboss EAP 7 - 如何从部署中排除隐式模块(javax.jms)?

    我没想到我会来到这里 但经过大量 Google 和 StackOverflow 搜索后 我来到了这里 这就是我的确切问题 https www linkedin com pulse tale two jars marco antonio al
  • 如何在 Android 中签署 AAR Artifacts?

    我目前正在开发一个 AAR android 库 我想用我自己的密钥对已发布的工件进行签名 以便我可以确定我是否发布了具有相同名称和功能的假 aar 注意事项1 我希望能够以编程方式检查我的库的真实性 即使是一个伪造的库 只是伪造了我的 aa
  • TableModel setCellEditable 并自动将值设置回 false

    我目前正在尝试在 JTable 中实现 JPopupMenu 它允许解锁单元格以进行编辑 Override public void actionPerformed ActionEvent e if e getActionCommand Un
  • 简单的Java程序插入USB热点后速度慢100倍

    我有以下Java程序 class Main public static void main String args throws java io IOException long start System nanoTime java io
  • 如何注册 org.springframework.integration.monitor.IntegrationMBeanExporter

    根据http www ibm com support knowledgecenter en SS7K4U 8 5 5 com ibm websphere nd multiplatform doc ae cspr data access tr
  • 如何在 SpringBoot v3.0.0 中使用嵌入式 MongoDB?

    我正在尝试连接嵌入式 mongodb 并使用 MongoDbSpringIntegrationTest 对其进行测试 问题是相同的代码在 2 7 7 中适用于 spring boot 但在 3 0 0 中不适用于 spring boot 问
  • Hibernate更新查询问题

    对于此更新查询 update TestDB dbo MyEmp set empname where empid 我在 DAO 课上写的 MyEmployee myEmployee new MyEmployee MyEmployee myEm
  • org.apache.poi 中的异常

    我试图编写一个可以读取和写入的程序 xlsx文件中 下面提供的代码旨在能够编写其第一个 Excel 程序 package excel reader import java io FileOutputStream import java io
  • Java 日期和 MySQL 时间戳时区

    我正在编辑一段代码 其基本功能是 timestamp new Date 然后坚持下去timestamp中的变量TIMESTAMPMySQL 表列 然而 通过调试我看到Date显示在正确时区的对象 GMT 1 当持久化在数据库上时 它是GMT
  • 致命异常:OkHttp 调度程序

    我在 Android 应用程序中使用 OkHttp 库向天气 API 发出 Web 请求 我已经实现了我的代码 但在执行请求时遇到了致命异常 我也已经在我的清单中添加了互联网权限 MainActivity java private Curr
  • 不鼓励在Web应用程序中使用线程吗?

    我们与同事就在 Java 的 Web 应用程序中使用线程进行了激烈的讨论 他们的观点是 不建议在 Java Web 应用程序中使用线程 因为它们不受容器管理 一般来说 我对此表示同意 因为线程可能会干扰容器 但是 如果它不是 Java EE
  • 如何将元素添加到通用集合

    我想知道如何将专用对象添加到通用集合中 我正在使用以下代码 Collection
  • Android NDK - 仅用 C/C++ 编写

    有没有一种可能的方法可以使用 C C 编写整个 NDK 应用程序 而无需像 hello jni 示例项目 HelloJni java 中那样的 Java 入门 类 以某种方式创建一个 HelloJni c 来执行相同的操作 从 Androi

随机推荐