简体   繁体   中英

How to change JButton Color while pressed

I'm trying to make a Login / Register system. I'm trying to make it so while a button is Pressed it has a different colour instead of it being the default aqua colour.

Here is one of my JButtons

login = new JButton("Login");
login.setFont(f2);
Dimension size2 = login.getPreferredSize();
login.setBounds(105, 85, size2.width, size2.height);
login.addActionListener(new LoginSystem());
login.setBackground(Color.WHITE);
login.setForeground(Color.BLACK);

Any way for me to make it so it look different while pressed?

You have to add a MouseAdapter you button's MouseListener. For example:

login.addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
        // do stuff here, change button background for example ...
        login.setBackground(Color.BLACK);
    }
});

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