Java 鼠标进入按钮时的jLabel幻灯片显示

Java 鼠标进入按钮时的jLabel幻灯片显示,java,multithreading,swing,slideshow,thread-sleep,Java,Multithreading,Swing,Slideshow,Thread Sleep,我无法让它工作: 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().get

我无法让它工作:

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将返回到空状态。(没有更多的东西)这可能吗?请帮忙。我也试着使用
for
语句,但效果不佳。顺便说一下,我正在使用netbeans。

您想在
JLabel
中添加一个
MouseAdapter
,并使用其
mouseenterned()
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"
                    }
                });

您希望将一个
MouseAdapter
添加到
JLabel
中,并使用其
mouseenterned()
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"
                    }
                });

您希望将一个
MouseAdapter
添加到
JLabel
中,并使用其
mouseenterned()
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"
                    }
                });

您希望将一个
MouseAdapter
添加到
JLabel
中,并使用其
mouseenterned()
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"
                    }
                });

首先需要实现一个
javax.swing.Timer
。尝试调用
Thread.sleep()
将阻止该进程。看见这是基本结构

Timer(int delay, ActionListener listener) 
其中,
delay
是您希望延迟的时间,以毫秒为单位,
侦听器将侦听每隔
delay
毫秒触发的
计时器
事件

所以你想要这样的东西

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]);
               }
           }
       });
   }
}
对于按钮,您需要使用
mouseEntered
mouseExited
,然后只需调用
timer.start()
timer.stop()

如果您不知道如何添加
鼠标侦听器
,只需在设计视图中右键单击按钮,然后选择
事件->鼠标->鼠标设置
。对已退出的
鼠标执行相同操作。您应该会看到上面自动生成的方法


更新

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                   
}
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.awt.event.MouseAdapter;
导入java.awt.event.MouseEvent;
导入java.net.MalformedURLException;
导入java.net.URL;
导入java.util.logging.Level;
导入java.util.logging.Logger;
导入javax.swing.GroupLayout;
导入javax.swing.ImageIcon;
导入javax.swing.JButton;
导入javax.swing.JLabel;
导入javax.swing.Timer;
导入javax.swing.WindowConstants;
公共类ImageViewer扩展了javax.swing.JFrame{
专用定时器=空;
ImageIcon[]图标=新的ImageIcon[5];
int指数=-1;
公共图像查看器(){
初始化组件();
试一试{
图标[0]=新图像图标(新URL(“http://www.iconsdb.com/icons/preview/orange/stackoverflow-4-xxl.png"));
图标[1]=新图像图标(新URL(“http://www.iconsdb.com/icons/preview/caribbean-blue/stackoverflow-4-xxl.png"));
图标[2]=新图像图标(新URL(“http://www.iconsdb.com/icons/preview/royal-blue/stackoverflow-4-xxl.png"));
图标[3]=新图像图标(新URL(“http://www.iconsdb.com/icons/preview/moth-green/stackoverflow-4-xxl.png"));
图标[4]=新图像图标(新URL(“http://www.iconsdb.com/icons/preview/soylent-red/stackoverflow-4-xxl.png"));
}捕获(格式错误){
Logger.getLogger(ImageViewer.class.getName()).log(Level.SEVERE,null,ex);
}
计时器=新计时器(1000,新ActionListener(){
已执行的公共无效操作(操作事件e){
如果(索引+1>4){
指数=0;
jLabel1.setIcon(图标[索引]);
}否则{
索引++;
jLabel1.setIcon(图标[索引]);
}
}
});
}
/**
*从构造函数中调用此方法来初始化表单。
*警告:不要修改此代码。此方法的内容始终为
*由表单编辑器重新生成。
*/
@抑制警告(“未选中”)
//                           
私有组件(){
jButton1=新JButton();
jLabel1=新的JLabel();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setText(“jButton1”);
jButton1.addMouseListener(新的MouseAdapter(){
公共无效mouseenterned(MouseEvent evt){
JButton1Mouseintered(evt);
}
公共无效mouseExited(MouseEvent evt){
jButton1MouseExited(evt);
}
});
GroupLayout=newgrouplayout(getContentPane());
getContentPane().setLayout(布局);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING,layout.createSequentialGroup()
.addContainerGap(GroupLayout.DEFAULT\u大小,简称.MAX\u值)
.addComponent(jButton1)
.addGap(127、127、127))
.addGroup(layout.createSequentialGroup()
.addGap(27,27,27)
.addComponent(jLabel1,GroupLayout.PREFERRED\u大小,285,GroupLayout.PREFERRED\u大小)
.addContainerGap(29,简称最大值))
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING,layout.createSequentialGroup()
.addGap(22,22,22)
.addComponent(jLabel1,GroupLayout.DEFAULT\u SIZE,321,Short.MAX\u值)
.addGap(18,18,18)
.addComponent(jButton1)
.addGap(16,16,16))
);
包装();
}//                         
私有void jbutton1mouseintered(MouseEvent evt){
timer.start();
}                                     
私有void jButton1MouseExited(MouseEven