Affichage des articles dont le libellé est Button With Background Image In Java. Afficher tous les articles
Affichage des articles dont le libellé est Button With Background Image In Java. Afficher tous les articles

Java - Button With Background Image

How to Create a Button with specified text and background image In Java Netbeans



In this Java Tutorial we will see How To Create a Buttons with background image In Java Using Netbeans.


What We're Building
Our custom button includes:
    - Background Images: Any image as button background with automatic scaling.
    - Hover Animations: Shadow effects that animate on mouse interaction.
    - Press Effects: Visual feedback when buttons are clicked.
    - Rounded Corners: Modern button appearance with customizable corner radius

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code:





public class ButtonWithImage extends  JFrame{

    public ButtonWithImage(){
        
        setTitle("Button Image");
        setSize(600, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        
        JPanel mainPanel = new JPanel(new GridBagLayout());
        mainPanel.setBackground(Color.WHITE);
        
        String imagePath = ButtonWithImage.class.getResource("pic_sport.jpg").getPath();
        ButtonImage button = new ButtonImage("Click", imagePath);
        button.setPreferredSize(new Dimension(250, 100));
        
        String imagePath2 = ButtonWithImage.class.getResource("pic_taxi.png").getPath();
        ButtonImage button2 = new ButtonImage("Click", imagePath2);
        button2.setPreferredSize(new Dimension(250, 100));
        
        button.addActionListener(e -> {
            JOptionPane.showMessageDialog(this, "Button 1 Clicked!",
                    "Action", JOptionPane.PLAIN_MESSAGE);
        });
        
         button2.addActionListener(e -> {
            JOptionPane.showMessageDialog(this, "Button 2 Clicked!",
                    "Action", JOptionPane.PLAIN_MESSAGE);
        });
        
        
        mainPanel.add(button);
        mainPanel.add(button2);
        
        
        setContentPane(mainPanel);
        
    }
    
    public static void main(String[] args) {
        
        new ButtonWithImage().setVisible(true);
        
    }
    
}

/**
 * Custom button implementation with modern visual effects
 */
class ButtonImage extends JButton{
    
    private BufferedImage backgroundImage;
    private boolean isHovered = false;
    private boolean isPressed = false;
    private float shadowOpacity = 0.0f;
    private Timer shadowTimer;
    
    private static final int CORNER_RADIUS = 12;
    private static final int SHADOW_SIZE = 20;
    private static final float SHADOW_MAX_OPACITY = 0.3f;
    
    public ButtonImage(String text, String imagePath){
        
        super(text);
        initializeButton();
        loadBackgroundImage(imagePath);
        setupAnimation();
        
    }
    
    
    private void initializeButton(){
         // Turn off the default button background
        setContentAreaFilled(false);
        // Turn off the focus border
        setFocusPainted(false);
        // Turn off the default button border
        setBorderPainted(false);
        // Set the text color to white
        setForeground(Color.WHITE);
        // Set the text font
        setFont(new Font("Arial", Font.BOLD, 26));
        // Change the mouse cursor to a hand when hovering over the button
        setCursor(new Cursor(Cursor.HAND_CURSOR));
        
         // Add code to detect mouse interactions
         addMouseListener(new MouseAdapter() {
             
             @Override
             public void mouseEntered(MouseEvent e){
                 // Mouse has moved onto the button
                 isHovered = true;
                 // Start the shadow animation
                 shadowTimer.start();
                 // Redraw the button with the new state
                 repaint();
             }
             
             @Override
             public void mouseExited(MouseEvent e){
                 // Mouse has moved away from the button
                 isHovered = false;
                 isPressed = false;
                 // Start the shadow animation
                 shadowTimer.start();
                 // Redraw the button with the new state
                 repaint();
             }
             
             @Override
             public void mousePressed(MouseEvent e){
                // Button is being pressed down
                isPressed = true;
                // Redraw the button with the new state
                repaint();
             }
             
             @Override
             public void mouseReleased(MouseEvent e){
                // Button is being pressed down
                isPressed = false;
                // Redraw the button with the new state
                repaint();
             }
             
         });
        
    }
    
    private void loadBackgroundImage(String imagePath){
        
        try {
            backgroundImage = ImageIO.read(new File(imagePath));
        } catch (IOException ex) {
            backgroundImage = createGradientBackground(250, 100);
        }
        
    }
    
    
    private BufferedImage createGradientBackground( int width, int height ){
        BufferedImage gradientImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        Graphics2D g2d = gradientImage.createGraphics();
        
        GradientPaint  gradientPaint =  new GradientPaint(0, 0, Color.BLACK,
                                                                         width, height, Color.BLUE);
        
        g2d.setPaint(gradientPaint);
        g2d.fillRect(0, 0, width, height);
        g2d.dispose();
        
        return gradientImage;
    }
    
    
    private void setupAnimation(){
        // Create a timer that fires every 15 milliseconds
        shadowTimer = new Timer(15, e ->{
            // Determine target opacity based on hover state
            float targetOpacity = isHovered ? SHADOW_MAX_OPACITY : 0.0f;
            // Gradually change the current opacity toward the target
            shadowOpacity += (targetOpacity - shadowOpacity) * 0.2f;
            // If we're very close to the target, just set it exactly and stop the timer
            if(Math.abs(targetOpacity - shadowOpacity) < 0.01f){
                shadowOpacity = targetOpacity;
                ((Timer) e.getSource()).stop();
            }
            
            // Redraw the button with the new shadow opacity
            repaint();
        
        });
    }
    
    
    @Override
    protected void paintComponent(Graphics g){
        // Create a copy of the graphics object that we can modify
        Graphics2D g2d = (Graphics2D)g.create();
        
        // Set up graphics quality settings
        configureGraphics(g2d);
        
        // Create the rounded rectangle shape for our button
        RoundRectangle2D.Float buttonShape = new RoundRectangle2D.Float(
                SHADOW_SIZE / 2,  SHADOW_SIZE / 2, getWidth() -  SHADOW_SIZE, getHeight() -  SHADOW_SIZE,
                CORNER_RADIUS, CORNER_RADIUS
        );
        
        // Draw the shadow if it should be visible
        if(shadowOpacity > 0){ drawShadow(g2d, buttonShape);  }
        
        // Only draw inside the button shape
        g2d.setClip(buttonShape);
        
        // Draw the background image
        drawBackground(g2d);
        
        // Draw the button text
        drawText(g2d);
        
        // Draw hover and press effects
        drawOverlayEffects(g2d, buttonShape);
        
        g2d.dispose();
        
    }
    
    private void drawBackground(Graphics2D g2d){
        // If we have a background image, draw it stretched to the button size
        if(backgroundImage != null){
            g2d.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), null);
        }
    }
    
    
    private void configureGraphics(Graphics2D g2d){
        // Turn on anti-aliasing for smoother edges
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // Turn on high quality text rendering
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        // Use better image scaling
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        
    }
    
    
   private void drawShadow(Graphics2D g2d, RoundRectangle2D.Float buttonShape){
        // Draw multiple lines with decreasing thickness to create a shadow effect
       for(int i = SHADOW_SIZE; i > 0; i--){
           // Calculate alpha based on distance from button and overall shadow opacity
           float alpha = shadowOpacity * (1.0f - (float) i / SHADOW_SIZE);
           // Set the shadow color (black with varying transparency)
           g2d.setColor(new Color(0,0,0, (int)(alpha * 60)));
           // Set the line thickness
           g2d.setStroke(new BasicStroke(i));
           // Draw the outline of the button
           g2d.draw(buttonShape);
           
       }
       
    }
    
    
  private void drawOverlayEffects(Graphics2D g2d, Shape buttonShape){

        if(isPressed){
            g2d.setColor(new Color(0, 0, 0, 40));
            g2d.fill(buttonShape);
        }
        else if(isHovered){
            g2d.setColor(new Color(255, 255, 255, 30));
            g2d.fill(buttonShape);
        }
      
    }
    
    
   private void drawText(Graphics2D g2d){
       
        // Get information about the size of the text
        FontMetrics metrics = g2d.getFontMetrics(getFont());
        String text = getText();
         // Calculate position to center the text horizontally
        int x = (getWidth() - metrics.stringWidth(text)) / 2;
        // Calculate position to center the text vertically
        int y = ((getHeight() - metrics.getHeight()) / 2 ) + metrics.getAscent();
        // Set the text color
        g2d.setColor(getForeground());
        // Draw the text on the button
       g2d.drawString(getText(), x, y);
       

    }
    
}
  


The Final Result: