当鼠标输入按钮时,jlabel幻灯片

发布于 2025-01-29 05:27:14 字数 782 浏览 9 评论 0原文

我无法工作:

public void ru() throws InterruptedException {
    jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/room.jpg")));
    setVisible(true);
    Thread.sleep(400);
    jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/ROOMS.jpg")));
    setVisible(true);
    Thread.sleep(400);
    jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/background.jpg")));
    setVisible(true);
}

private void BtnRoomsMouseEntered(java.awt.event.MouseEvent evt) {
    try {
        ru();
    } catch (InterruptedException ex) {
    }
}               

有什么解决方案吗? 当鼠标输入特定按钮时,只要鼠标仍在按钮中,我希望Jlabel显示出幻灯片显示。如果鼠标碰巧退出按钮,则jlabel将返回到空状态。 (不再有任何东西。)可能吗?请帮忙。我还尝试使用语句使用,但没有好处。顺便说一句,我正在使用Netbeans。

I can't get this to work:

public void ru() throws InterruptedException {
    jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/room.jpg")));
    setVisible(true);
    Thread.sleep(400);
    jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/ROOMS.jpg")));
    setVisible(true);
    Thread.sleep(400);
    jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/background.jpg")));
    setVisible(true);
}

private void BtnRoomsMouseEntered(java.awt.event.MouseEvent evt) {
    try {
        ru();
    } catch (InterruptedException ex) {
    }
}               

Any solutions?
I want a jLabel to show a slide show when a mouse enters a certain button and stays like that as long as the mouse is still in a button. If the mouse happens to exit the button, the jlabel will return to a null state. (no more anything.) Is that possible? Please help. I also tried using for statement but no good. I'm using netbeans by the way.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

对你而言 2025-02-05 05:27:14

首先,您需要实现javax.swing.timer。尝试调用thread.sleep()将阻止事件调度线程。参见如何使用摇摆计时器。这是

Timer(int delay, ActionListener listener) 

delay是您想要延迟的时间,是侦听器将收听Timer action> actionevent 触发了每个延迟毫秒。

因此,您需要这样的

public class MyFrame extends javax.swing.JFrame {

   private Timer timer = null;
   ImageIcon[] icons = new ImageIcon[3];
   int index = -1;

   public MyFrame() {
       initComponents();
       icons[0] = new ImageIcon(...);
       icons[1] = new ImageIcon(...);
       icons[2] = new ImageIcon(...);

       timer = new Timer(2000, new ActionListener(){
           public void actionPerformed(ActionEvent e) {
               if (index + 1 > 2) {
                   index = 0;
                   jLabel3.setIcon(icons[index]);
               } else {
                   index++;
                   jLabel3.setIcon(icons[index]);
               }
           }
       });
   }
}

按钮,您需要使用鼠标录制 mouseexited,然后您只需调用timer.start。 ()timer.stop()

private void jButton1MouseExited(MouseEvent e) {
    timer.stop();
}

private void jButton1MouseEntered(MouseEvent e) {
    timer.start();
}

如果您不知道如何添加mouselistener右键单击“设计视图”的按钮,然后选择<代码>事件 - &GT;鼠标 - &gt;鼠标的。对于Mouseexited做同样的事情。您应该看到上述为您自动生成的方法。


更新

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.WindowConstants;

public class ImageViewer extends javax.swing.JFrame {

    private Timer timer = null;
    ImageIcon[] icons = new ImageIcon[5];
    int index = -1;

    public ImageViewer() {
        initComponents();
        try {

            icons[0] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/orange/stackoverflow-4-xxl.png"));
            icons[1] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/caribbean-blue/stackoverflow-4-xxl.png"));
            icons[2] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/royal-blue/stackoverflow-4-xxl.png"));
            icons[3] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/moth-green/stackoverflow-4-xxl.png"));
            icons[4] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/soylent-red/stackoverflow-4-xxl.png"));
        } catch (MalformedURLException ex) {
            Logger.getLogger(ImageViewer.class.getName()).log(Level.SEVERE, null, ex);
        }

        timer = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (index + 1 > 4) {
                    index = 0;
                    jLabel1.setIcon(icons[index]);
                } else {
                    index++;
                    jLabel1.setIcon(icons[index]);
                }
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new JButton();
        jLabel1 = new JLabel();

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");
        jButton1.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent evt) {
                jButton1MouseEntered(evt);
            }
            public void mouseExited(MouseEvent evt) {
                jButton1MouseExited(evt);
            }
        });

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(127, 127, 127))
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 285, GroupLayout.PREFERRED_SIZE)
                .addContainerGap(29, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jLabel1, GroupLayout.DEFAULT_SIZE, 321, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addGap(16, 16, 16))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1MouseEntered(MouseEvent evt) {                                      
        timer.start();
    }                                     

    private void jButton1MouseExited(MouseEvent evt) {                                     
        timer.stop();
    }                                    

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ImageViewer().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private JButton jButton1;
    private JLabel jLabel1;
    // End of variables declaration                   
}

First thing you need to implement a javax.swing.Timer. Trying to call Thread.sleep() will block the Event Dispatch Thread. See How to use Swing Timers. Here is the basic construct

Timer(int delay, ActionListener listener) 

where delay is the time in milliseconds you want delayed and the listener will listen for the Timer ActionEvent fired every delay milliseconds.

So you want something like this

public class MyFrame extends javax.swing.JFrame {

   private Timer timer = null;
   ImageIcon[] icons = new ImageIcon[3];
   int index = -1;

   public MyFrame() {
       initComponents();
       icons[0] = new ImageIcon(...);
       icons[1] = new ImageIcon(...);
       icons[2] = new ImageIcon(...);

       timer = new Timer(2000, new ActionListener(){
           public void actionPerformed(ActionEvent e) {
               if (index + 1 > 2) {
                   index = 0;
                   jLabel3.setIcon(icons[index]);
               } else {
                   index++;
                   jLabel3.setIcon(icons[index]);
               }
           }
       });
   }
}

For your button, you need to use mouseEntered and mouseExited, then you can just call timer.start() or timer.stop()

private void jButton1MouseExited(MouseEvent e) {
    timer.stop();
}

private void jButton1MouseEntered(MouseEvent e) {
    timer.start();
}

If you don't know how to add the MouseListener just right click on the button from the design view and select Event -> Mouse -> mouseEntered. Do the same for mouseExited. You should see the above methods auto-generated for you.


UPDATE

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.WindowConstants;

public class ImageViewer extends javax.swing.JFrame {

    private Timer timer = null;
    ImageIcon[] icons = new ImageIcon[5];
    int index = -1;

    public ImageViewer() {
        initComponents();
        try {

            icons[0] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/orange/stackoverflow-4-xxl.png"));
            icons[1] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/caribbean-blue/stackoverflow-4-xxl.png"));
            icons[2] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/royal-blue/stackoverflow-4-xxl.png"));
            icons[3] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/moth-green/stackoverflow-4-xxl.png"));
            icons[4] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/soylent-red/stackoverflow-4-xxl.png"));
        } catch (MalformedURLException ex) {
            Logger.getLogger(ImageViewer.class.getName()).log(Level.SEVERE, null, ex);
        }

        timer = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (index + 1 > 4) {
                    index = 0;
                    jLabel1.setIcon(icons[index]);
                } else {
                    index++;
                    jLabel1.setIcon(icons[index]);
                }
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new JButton();
        jLabel1 = new JLabel();

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");
        jButton1.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent evt) {
                jButton1MouseEntered(evt);
            }
            public void mouseExited(MouseEvent evt) {
                jButton1MouseExited(evt);
            }
        });

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(127, 127, 127))
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 285, GroupLayout.PREFERRED_SIZE)
                .addContainerGap(29, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jLabel1, GroupLayout.DEFAULT_SIZE, 321, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addGap(16, 16, 16))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1MouseEntered(MouseEvent evt) {                                      
        timer.start();
    }                                     

    private void jButton1MouseExited(MouseEvent evt) {                                     
        timer.stop();
    }                                    

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ImageViewer().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private JButton jButton1;
    private JLabel jLabel1;
    // End of variables declaration                   
}
旧情别恋 2025-02-05 05:27:14

您需要将mouseadapter添加到jlabel 并使用其mouseTentered()mouseexited(),如下:

        jLabel3.addMouseListener(new MouseAdapter() {

                   @Override
                   public void mouseEntered(java.awt.event.MouseEvent evt) {      
                   try {
                        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/room.jpg")));
                        setVisible(true);
                        Thread.sleep(400);
                        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/ROOMS.jpg")));
                        setVisible(true);
                        Thread.sleep(400);
                        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/background.jpg")));
                        setVisible(true);
                    } catch(InterruptedException e) {

                    }

                    @Override
                    public void mouseExited(java.awt.event.MouseEvent evt) {
                        //whatever you mean by "null state"
                    }
                });

You want to add a MouseAdapter to the JLabel and use its mouseEntered() and mouseExited() as follows:

        jLabel3.addMouseListener(new MouseAdapter() {

                   @Override
                   public void mouseEntered(java.awt.event.MouseEvent evt) {      
                   try {
                        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/room.jpg")));
                        setVisible(true);
                        Thread.sleep(400);
                        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/ROOMS.jpg")));
                        setVisible(true);
                        Thread.sleep(400);
                        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/background.jpg")));
                        setVisible(true);
                    } catch(InterruptedException e) {

                    }

                    @Override
                    public void mouseExited(java.awt.event.MouseEvent evt) {
                        //whatever you mean by "null state"
                    }
                });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文