Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to simplify things in my Java program

Tags:

java

swing

awt

I made a game using NetBeans design tool, called WordHunt. It looks like this:

enter image description here

I need to make a class that will apply a mouseover effect to those 16 labels I have. This is the code that changes the icon B when enter the mouse:

private void b1MouseEntered(java.awt.event.MouseEvent evt) {                                
        b1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ip/imag/" +B+ ".png")));

    }                               

I had applied a default icon to the label. After making that class, instead of writing:

b1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ip/imag/" +B+ ".png")));

to write className(b1 ,B); For the next label, the same thing className(b2 ,C);

Observation: b1 is a label and I have all letters icon in .png format from A to Z.

Can anybody give me an idea of how I can do that?

like image 754
Dan Avatar asked May 20 '26 05:05

Dan


1 Answers

If I understand what you want to do, you can use this method:

public void setRolloverIcon(Icon rolloverIcon)

defined in the class JButton to configure the rollover icon.

Just create a simple class like this:

class HoverEffectButton extends JButton{

  HoverEffectButton(Image img1, Image img2) {
    super(new ImageIcon(img1));
    this.setRolloverIcon(new ImageIcon(img2));
  }

}

Hope this will help. And of course you can create a helper class that permits to load an image according to the image name

   class AssetsHelper{
   private static final String DEFAULT_ASSETS_ROOT = "assets/";
   private static final String DEFAULT_IMAGE_SUBFIX = ".png";

   public static Image loadImage(String name){
      BufferedImage img = null;
      try {
        img = ImageIO.read(new File(DEFAULT_ASSETS_ROOT + name + DEFAULT_IMAGE_SUBFIX));
      } catch (IOException e) {
         .... 
      }
      return img;
   }

}

like image 53
Jiji TANG Avatar answered May 22 '26 19:05

Jiji TANG