Java Swing中的悬停效果

huangapple go评论62阅读模式
英文:

Hover Effects with Java Swing

问题

在我的主窗口中,我有两个面板。它们分别是leftPanelrightPanel。在leftPanel中,我有两个按钮:matchButtonsimulatorButton。在rightPanel中,我有一个绘制的图像。我尝试为这两个按钮添加悬停效果。当鼠标悬停在matchButton上时,rightPanel中的图像将更改为新的图像。当鼠标从matchButton移开时,rightPanel上的图像将恢复为默认图像。对于simulatorButton也是同样的情况。为此,我创建了一个单独的类,并添加了以下代码:

public class ImgPanelStart extends JPanel {
    private Image backgroundImage;
    private BufferedImage imgBg;

    public ImgPanelStart() {
        try {
            backgroundImage = ImageIO.read(new File("./apsProject/assets/img0.jpg"));
        } catch (IOException ex) {
            System.out.println("Falha ao carregar imagem de fundo");
        }
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (backgroundImage != null) {
            g.drawImage(imgBg, 0, 0, null);
        }
        Dimension dim = this.getSize();
        int dWidth = (int) dim.getWidth();
        int dHeight = (int) dim.getHeight();
        imgBg = new BufferedImage(dWidth, dHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = imgBg.createGraphics();
        g2.drawImage(backgroundImage, 0, 0, dWidth, dHeight, null);
        g2.dispose();
        g.drawImage(imgBg, 0, 0, null);
    }

    private void setImgBackground(Image img) {
        backgroundImage = img;
        if (imgBg == null) {
            imgBg = new BufferedImage(850, 600, BufferedImage.TYPE_INT_RGB);
        }
        Graphics2D g2 = imgBg.createGraphics();
        g2.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), null);
        g2.dispose();
        repaint();
    }

    public void addHoverEffect(JButton button, JButton button2) {
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                try {
                    setImgBackground(ImageIO.read(new File("./apsProject/assets/wall.jpg"));
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

            @Override
            public void mouseExited(MouseEvent e) {
                try {
                    setImgBackground(ImageIO.read(new File("./apsProject/assets/img0.jpg"));
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });

        button2.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                try {
                    setImgBackground(ImageIO.read(new File("./apsProject/assets/img2.jpg"));
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

            @Override
            public void mouseExited(MouseEvent e) {
                try {
                    setImgBackground(ImageIO.read(new File("./apsProject/assets/img0.jpg"));
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
    }
}

我在主类中像这样调用我的方法:

ImgPanelStart effects = new ImgPanelStart();
effects.addHoverEffect(matchButton, simulationButton);

然而,当鼠标悬停在面板上时,绘制在面板上的图像未更新。

这就像,当我将鼠标悬停在按钮上时,它会将rightPanel中的图像更改为wall.jpg。当我移开鼠标时,它会返回到图像img0.jpg

当我将鼠标悬停在button2按钮上时,它会将rightPanel中的图像更改为img2.jpg。当我移开鼠标时,它会返回到图像img0.jpg

有人知道可能出了什么问题,或者可以给我一些建议,帮我解决这个问题吗?

英文:

In my main window I have two panels. They are leftPanel and rightPanel. In the leftPanel I have two buttons: matchButton and simulatorButton. In my rightPanel I have an image drawn on it. I tried to add a hover effect to both buttons. When hovering the mouse over the matchButton the image contained in the rightPanel would change to a new image. When removing the mouse from the matchButton the image on the rightPanel would revert to the default image. It would be the same with simulatorButton. For that I created a separate class and added the following code:

public class ImgPanelStart extends JPanel {
    private Image backgroundImage;
    private BufferedImage imgBg;

    public ImgPanelStart() {
        try {
            backgroundImage = ImageIO.read(new File("./apsProject/assets/img0.jpg"));
        } catch (IOException ex) {
            System.out.println("Falha ao carregar imagem de fundo");
        }
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (backgroundImage != null) {
            g.drawImage(imgBg, 0, 0, null);
        }
        Dimension dim = this.getSize();
        int dWidth = (int) dim.getWidth();
        int dHeight = (int) dim.getHeight();
        imgBg = new BufferedImage(dWidth, dHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = imgBg.createGraphics();
        g2.drawImage(backgroundImage, 0, 0, dWidth, dHeight, null);
        g2.dispose();
        g.drawImage(imgBg, 0, 0, null);
    }

    private void setImgBackground(Image img) {
        backgroundImage = img;
        if (imgBg == null) {
            imgBg = new BufferedImage(850, 600, BufferedImage.TYPE_INT_RGB);
        }
        Graphics2D g2 = imgBg.createGraphics();
        g2.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), null);
        g2.dispose();
        repaint();
    }

    public void addHoverEffect(JButton button, JButton button2) {
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                try {
                    setImgBackground(ImageIO.read(new File("./apsProject/assets/wall.jpg")));
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

            @Override
            public void mouseExited(MouseEvent e) {
                try {
                    setImgBackground(ImageIO.read(new File("./apsProject/assets/img0.jpg")));
                } catch (IOException e1) {
                    e1.printStackTrace();
                };
            }
        });

        button2.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                try {
                    setImgBackground(ImageIO.read(new File("./apsProject/assets/img2.jpg")));
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

            @Override
            public void mouseExited(MouseEvent e) {
                try {
                    setImgBackground(ImageIO.read(new File("./apsProject/assets/img0.jpg")));
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
    }
}

I call my method in the main class like this:

ImgPanelStart effects = new ImgPanelStart();
effects.addHoverEffect(matchButton, simulationButton);

However, the drawing made on the panel is not updated when hovering the mouse over it.

It would be something like, I hovered the mouse over the button button it would change the image in my rightPanel to wall.jpg. I removed the mouse and it would return to the image img0.jpg.

I hovered the mouse over the button2 button, it would change the image in my rightPanel to img2.jpg. When I removed the mouse it would return to the image img0.jpg.

Does anyone know what could be wrong, or give me a tip on what I can do to fix this problem?

答案1

得分: 1

由于您的代码不是一个完整的可运行示例,我已经创建了以下GUI。

这是当您悬停在模拟按钮上时的相同GUI。

Oracle有一个有用的教程,名为使用Swing创建GUI。请跳过使用NetBeans IDE学习Swing部分。

在构建GUI之前,我读取了我想要使用的图像。这样,我只读取图像一次。

以下是完整的可运行代码。我将附加类作为内部类,以便可以将代码发布为一个块。

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class HoverEffects implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new HoverEffects());
    }

    private final DrawingPanel drawingPanel;

    private final LoadImages loadImages;

    public HoverEffects() {
        this.loadImages = new LoadImages();
        this.drawingPanel = new DrawingPanel(loadImages.getWallpaper());
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("Hover Effects");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(createButtonPanel(), BorderLayout.WEST);
        frame.add(drawingPanel, BorderLayout.CENTER);

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

    private JPanel createButtonPanel() {
        JPanel outerPanel = new JPanel();

        JPanel panel = new JPanel(new GridLayout(0, 1, 5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5);

        JButton matchButton = new JButton("Match");
        matchButton.addMouseListener(
                new HoverListener(this, loadImages, matchButton));
        panel.add(matchButton);

        JButton simulatorButton = new JButton("Simulation");
        simulatorButton.addMouseListener(
                new HoverListener(this, loadImages, simulatorButton));
        panel add(simulatorButton);

        outerPanel.add(panel);

        return outerPanel;
    }

    public void setImage(Image image) {
        drawingPanel.setImage(image);
        drawingPanel.repaint();
    }

    public class DrawingPanel extends JPanel {

        private static final long serialVersionUID = 1L;

        private Image image;

        public DrawingPanel(Image image) {
            setImage(image);
            this.setPreferredSize(new Dimension(800, 600));
        }

        public void setImage(Image image) {
            this.image = image;
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image, 0, 0, this);
        }
    }

    public class HoverListener extends MouseAdapter {

        private final HoverEffects view;

        private final LoadImages model;

        private final JButton button;

        public HoverListener(HoverEffects view, LoadImages model, JButton button) {
            this.view = view;
            this.model = model;
            this.button = button;
        }

        @Override
        public void mouseEntered(MouseEvent event) {
            String text = button.getText();
            if (text.equals("Match")) {
                view.setImage(model.getNature1());
            } else {
                view.setImage(model.getNature2());
            }
        }

        @Override
        public void mouseExited(MouseEvent event) {
            view.setImage(model.getWallpaper());
        }
    }

    public class LoadImages {

        private Image nature1, nature2, wallpaper;

        public LoadImages() {
            try {
                URL url = new URL(
                        "http://www.thewowstyle.com/wp-content/uploads/"
                                + "2015/01/nature-wallpaper-27.jpg");
                Image image = ImageIO.read(url);
                wallpaper = image.getScaledInstance(800, 600,
                        Image.SCALE_SMOOTH);
                url = new URL("http://www.thewowstyle.com/wp-content/uploads/"
                        + "2015/01/nature-images..jpg");
                image = ImageIO.read(url);
                nature1 = image.getScaledInstance(800, 600, Image.SCALE_SMOOTH);
                url = new URL("http://www.thewowstyle.com/wp-content/uploads/"
                        + "2015/01/nature-images.jpg");
                image = ImageIO.read(url);
                nature2 = image.getScaledInstance(800, 600, Image.SCALE_SMOOTH);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public Image getNature1() {
            return nature1;
        }

        public Image getNature2() {
            return nature2;
        }

        public Image getWallpaper() {
            return wallpaper;
        }
    }
}

<details>
<summary>英文:</summary>
Since your code was not a complete runnable example, I went ahead and created the following GUI.
[![Example][1]][1]
Here&#39;s the same GUI when you hover over the simulation button.
[![Example][2]][2]
Oracle has a helpful tutorial, [Creating a GUI With Swing](https://docs.oracle.com/javase/tutorial/uiswing/index.html).  Skip the Learning Swing with the NetBeans IDE section.  
I read the images I wanted to use before I constructed the GUI.  That way, I only read the images one time.
Here&#39;s the complete runnable code.  I made the additional classes inner classes so I could post the code as one block.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class HoverEffects implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new HoverEffects());
}
private final DrawingPanel drawingPanel;
private final LoadImages loadImages;
public HoverEffects() {
this.loadImages = new LoadImages();
this.drawingPanel = new DrawingPanel(loadImages.getWallpaper());
}
@Override
public void run() {
JFrame frame = new JFrame(&quot;Hover Effects&quot;);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createButtonPanel(), BorderLayout.WEST);
frame.add(drawingPanel, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtonPanel() {
JPanel outerPanel = new JPanel();
JPanel panel = new JPanel(new GridLayout(0, 1, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JButton matchButton = new JButton(&quot;Match&quot;);
matchButton.addMouseListener(
new HoverListener(this, loadImages, matchButton));
panel.add(matchButton);
JButton simulatorButton = new JButton(&quot;Simulation&quot;);
simulatorButton.addMouseListener(
new HoverListener(this, loadImages, simulatorButton));
panel.add(simulatorButton);
outerPanel.add(panel);
return outerPanel;
}
public void setImage(Image image) {
drawingPanel.setImage(image);
drawingPanel.repaint();
}
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = 1L;
private Image image;
public DrawingPanel(Image image) {
setImage(image);
this.setPreferredSize(new Dimension(800, 600));
}
public void setImage(Image image) {
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
public class HoverListener extends MouseAdapter {
private final HoverEffects view;
private final LoadImages model;
private final JButton button;
public HoverListener(HoverEffects view, LoadImages model,
JButton button) {
this.view = view;
this.model = model;
this.button = button;
}
@Override
public void mouseEntered(MouseEvent event) {
String text = button.getText();
if (text.equals(&quot;Match&quot;)) {
view.setImage(model.getNature1());
} else {
view.setImage(model.getNature2());
}
}
@Override
public void mouseExited(MouseEvent event) {
view.setImage(model.getWallpaper());
}
}
public class LoadImages {
private Image nature1, nature2, wallpaper;
public LoadImages() {
try {
URL url = new URL(
&quot;http://www.thewowstyle.com/wp-content/uploads/&quot;
+ &quot;2015/01/nature-wallpaper-27.jpg&quot;);
Image image = ImageIO.read(url);
wallpaper = image.getScaledInstance(800, 600,
Image.SCALE_SMOOTH);
url = new URL(&quot;http://www.thewowstyle.com/wp-content/uploads/&quot;
+ &quot;2015/01/nature-images..jpg&quot;);
image = ImageIO.read(url);
nature1 = image.getScaledInstance(800, 600, Image.SCALE_SMOOTH);
url = new URL(&quot;http://www.thewowstyle.com/wp-content/uploads/&quot;
+ &quot;2015/01/nature-images.jpg&quot;);
image = ImageIO.read(url);
nature2 = image.getScaledInstance(800, 600, Image.SCALE_SMOOTH);
} catch (IOException e) {
e.printStackTrace();
}
}
public Image getNature1() {
return nature1;
}
public Image getNature2() {
return nature2;
}
public Image getWallpaper() {
return wallpaper;
}
}
}
[1]: https://i.stack.imgur.com/XFKiQ.jpg
[2]: https://i.stack.imgur.com/NadRS.jpg
</details>
# 答案2
**得分**: 0
```java
我不确定我是不是用最好的方法解决了它,但它起作用了,我将尝试更多地学习Java Swing及其组件。
代码:
public class ImgPanelStart extends JPanel{
private Image backgroundImage;
private BufferedImage imgBg;
private LoadImages images;
public ImgPanelStart() {
images = new LoadImages();
backgroundImage = images.getWallpaper();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (backgroundImage != null) {
Dimension dim = this.getSize();
int dWidth = (int) dim.getWidth();
int dHeight = (int) dim.getHeight();
imgBg = new BufferedImage(dWidth, dHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = imgBg.createGraphics();
g2.drawImage(backgroundImage, 0, 0, dWidth, dHeight, null);
g2.dispose();
g.drawImage(imgBg, 0, 0, null);
}
}
private void setImgBackground(int imageIndex) {
switch (imageIndex) {
case 1:
backgroundImage = images.getMatchImg();
break;
case 2:
backgroundImage = images.getSimuImg();
break;
case 3:
backgroundImage = images.getWallpaper();
break;
default:
break;
}
repaint();
}
public class HoverEffects extends MouseAdapter {
private final JButton button;
public HoverEffects(JButton button) {
this.button = button;
}
@Override
public void mouseEntered(MouseEvent event) {
String text = button.getText();
if (text.equals("Match")) {
setImgBackground(1);
} else {
setImgBackground(2);
}
}
@Override
public void mouseExited(MouseEvent event) {
setImgBackground(3);
}
}
public class LoadImages {
private Image matchImg, simuImg, wallpaper;
public LoadImages() {
try {
Image image = ImageIO.read(new File("./ApsProject/src/assets/img0.jpg"));
wallpaper = image.getScaledInstance(850, 600, Image.SCALE_SMOOTH);
image = ImageIO.read(new File("./ApsProject/src/assets/SimuScreenRightPanel.png"));
matchImg = image.getScaledInstance(850, 600, Image.SCALE_SMOOTH);
image = ImageIO.read(new File("./ApsProject/src/assets/MatchScreenRightPanel.png"));
simuImg = image.getScaledInstance(850, 600, Image.SCALE_SMOOTH);
} catch (IOException e) {
e.printStackTrace();
}
}
public Image getMatchImg() {
return matchImg;
}
public Image getSimuImg() {
return simuImg;
}
public Image getWallpaper() {
return wallpaper;
}
}
}
英文:

I don't know, if I solved it the best way but it worked, I'm going to try to study more about Java Swing and its components.

Code:

public class ImgPanelStart extends JPanel{
private Image backgroundImage;
private BufferedImage imgBg;
private LoadImages images;
public ImgPanelStart() {
images = new LoadImages();
backgroundImage = images.getWallpaper();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (backgroundImage != null) {
Dimension dim = this.getSize();
int dWidth = (int) dim.getWidth();
int dHeight = (int) dim.getHeight();
imgBg = new BufferedImage(dWidth, dHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = imgBg.createGraphics();
g2.drawImage(backgroundImage, 0, 0, dWidth, dHeight, null);
g2.dispose();
g.drawImage(imgBg, 0, 0, null);
}
}
private void setImgBackground(int imageIndex) {
switch (imageIndex) {
case 1:
backgroundImage = images.getMatchImg();
break;
case 2:
backgroundImage = images.getSimuImg();
break;
case 3:
backgroundImage = images.getWallpaper();
break;
default:
break;
}
repaint();
}
public class HoverEffects extends MouseAdapter {
private final JButton button;
public HoverEffects(JButton button) {
this.button = button;
}
@Override
public void mouseEntered(MouseEvent event) {
String text = button.getText();
if (text.equals(&quot;Match&quot;)) {
setImgBackground(1);
} else {
setImgBackground(2);
}
}
@Override
public void mouseExited(MouseEvent event) {
setImgBackground(3);
}
}
public class LoadImages {
private Image matchImg, simuImg, wallpaper;
public LoadImages() {
try {
Image image = ImageIO.read(new File(&quot;./ApsProject/src/assets/img0.jpg&quot;));
wallpaper = image.getScaledInstance(850, 600, Image.SCALE_SMOOTH);
image = ImageIO.read(new File(&quot;./ApsProject/src/assets/SimuScreenRightPanel.png&quot;));
matchImg = image.getScaledInstance(850, 600, Image.SCALE_SMOOTH);
image = ImageIO.read(new File(&quot;./ApsProject/src/assets/MatchScreenRightPanel.png&quot;));
simuImg = image.getScaledInstance(850, 600, Image.SCALE_SMOOTH);
} catch (IOException e) {
e.printStackTrace();
}
}
public Image getMatchImg() {
return matchImg;
}
public Image getSimuImg() {
return simuImg;
}
public Image getWallpaper() {
return wallpaper;
}
}

}

huangapple
  • 本文由 发表于 2023年3月31日 21:04:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75898892.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定