简体   繁体   中英

How to change the background color of a Jbutton on click

I'm trying to change the color of a JButton when you click on it, but a blue color appears instead of the one I wrote about.

Goal : The goal is that when you click on the button the color change

I did several searches, but each time a blue font appeared.

I tried overide paintComponent, several alternatives such as this.getModel, but nothing works.

My button class:

package com.tralamy.lancherX.display;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TButton extends JButton {

    private Color hoverColor = Display.LIGHT_GRAY;
    private Color pressColor = Display.LIGHT_DARK;
    private Color firstColor;
    private Color basic;

    private MouseAdapter hoverAdapter = new MouseAdapter() {
        @Override
        public void mouseEntered(MouseEvent e) {
            basic = firstColor;
            TButton.this.setBackground(hoverColor);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            TButton.this.setBackground(basic);
        }
    };

    private MouseAdapter pressAdapter = new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            TButton.this.setBackground(pressColor);
            super.mousePressed(e);
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            TButton.this.setBackground(basic);
            super.mouseReleased(e);
        }
    };

    public TButton (String text){
        super(text);
        init();
    }

    public TButton (Icon icon){
        super(icon);
        init();
    }

    public TButton (){
        super();
        init();
    }

    private void init()
    {
        firstColor = this.getBackground();
        setBorder(null);
        setBorderPainted(false);
        setContentAreaFilled(false);
        setOpaque(false);
        setFocusPainted(false);
        setPressedIcon(new ImageIcon());
    }

    @Override
    public void setBackground(Color bg) {
        super.setBackground(bg);
        firstColor = bg;
    }

    public void setHover()
    {
        this.addMouseListener(hoverAdapter);
    }

    public void removeHover()
    {
        this.removeMouseListener(hoverAdapter);
    }

    public void setPress()
    {
        this.addMouseListener(pressAdapter);
    }

    public void removePress()
    {
        this.removeMouseListener(pressAdapter);
    }

    public void setHoverColor(Color color)
    {
        hoverColor = color;
    }

    public Color getHoverColor()
    {
        return hoverColor;
    }

    public Color getPressColor() {
        return pressColor;
    }

    public void setPressColor(Color pressColor) {
        this.pressColor = pressColor;
    }
}

Main menu panel:

private JPanel menuPanel() {
        mp = new JPanel();
        setPercentWidth(mp, 25);

        mp.setBackground(LIGHT_GRAY);
        mp.setLayout(new BorderLayout());

        JPanel userSection = new JPanel();
        userSection.setLayout(new GridBagLayout());

        setPercentHeight(userSection, 5);
        userSection.setPreferredSize(new Dimension(userSection.getWidth(), 0));
        userSection.setBackground(LIGHT_DARK);

        userIconButton.setHorizontalAlignment(SwingConstants.CENTER);
        userName.setHorizontalAlignment(SwingConstants.CENTER);
        userIconButton.setBorder(new EmptyBorder(0,0,0,10));

        userSection.add(userIconButton);
        userSection.add(userName);

        menuButtons.add(new TButton("Library"));
        menuButtons.add(new TButton("Store"));
        menuButtons.add(new TButton("Friends"));
        menuButtons.add(new TButton("News"));


        JPanel menuSection = new JPanel();
        menuSection.setLayout(new BoxLayout(menuSection, BoxLayout.Y_AXIS));
        menuSection.setOpaque(false);

        for (TButton button : menuButtons) {
            button.setAlignmentX(TButton.CENTER_ALIGNMENT);

            button.setFont(App.setSemiBoldNunito(48));

            button.setForeground(SUPER_SUPER_LIGHT_GRAY);

            button.setBackground(SUPER_LIGHT_GRAY);

            button.setBorder(null);
            button.setBorderPainted(true);
            button.setContentAreaFilled(true);
            button.setOpaque(true);

            button.setHoverColor(DARK_GRAY);
            button.setHover();

            button.setPressColor(LIGHT_DARK);
            button.setPress();

            TButton marginLabel = new TButton();

            marginLabel.setSize(MAIN_MENU_MARGIN, MAIN_MENU_MARGIN);
            marginLabel.setMaximumSize(new Dimension(MAIN_MENU_MARGIN, MAIN_MENU_MARGIN));
            marginLabel.setMinimumSize(new Dimension(MAIN_MENU_MARGIN, MAIN_MENU_MARGIN));

            setPercentWidth(button, 20);

            menuSection.add(marginLabel);
            
            menuSection.add(button);

        }

        mp.add(menuSection);
        mp.add(userSection, BorderLayout.SOUTH);
        return mp;
    }

And then some image: My bug

And thank you in advance

If you want to change the background of the button with a persistent color when the user clicks on the button, then you can use setContentAreaFilled(false) on it. Then it is required to reset the opaque property to true because according to the docs of setContentAreaFilled : " This function may cause the component's opaque property to change. ", for example:

import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class MainPersist {
    
    private static void createAndShowGUI() {
        final JButton button = new JButton("Click to change color");
        button.addActionListener(e -> {
            button.setContentAreaFilled(false);
            button.setOpaque(true); //Reset the opacity.
            button.setBackground(Color.CYAN.darker()); //Set your desired color as the background.
        });
        
        final JFrame frame = new JFrame("Button bg on click");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(button);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    
    public static void main(final String[] args) {
        SwingUtilities.invokeLater(MainPersist::createAndShowGUI);
    }
}

Otherwise, if you want the button to only change its color when clicked and then return back to normal when released, then take a look at this question which is about exactly that. It has no accepted answers yet (it is very recent as of the time this answer itself is posted), but there is at least one/my answer (which suggests to modify the ButtonUI of the button) and there should be more answers coming I guess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM