Change JToggleButton selected color

C

Chris

I would like to change the color of a selected JToggleButton (in a
ButtonGroup) to red from grey. About the only solution I can find online
is to put this in my main program:

UIManager.put("ToggleButton.select", Color.red);

However this doesn't change anything for me. Strangely if I change my
JToggleButton class to JButton this line indeed does work:

UIManager.put("Button.select", Color.red);

By the way, all my buttons are actually from a derived class called
SymbolButton that extends JToggleButton. I'm running 1.4.2 on Linux.

Thanks,
Chris
 
I

Ike

Hi Chris,

Try this, it will get you started anyhow, from some code I have here....Ike

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

public class JTASToggleButton extends JToggleButton {
public boolean pressed;
/** Creates a new instance of JTASToggleButton */
public JTASToggleButton() {
super();
addMouseListener(new MouseAdapter(){
//the following functions not needed since this is an adapter
class:
public void mousePressed(MouseEvent Me){
pressed=!pressed;
if(pressed)
setForeground(Color.MAGENTA);
else
setForeground(Color.BLACK);
}
});
}


}
 
C

Chris

Thanks Ike. I tried adding a MouseListener to my JToggleButton class but
found that:
1. setForeground doesn't do anything, but setBackground does
2. setBackground changes the color of the non-selected buttons, not the
selected button

So I'm still looking for something to change just the color of the
selected button and nothing else.

Thanks,
Chris
 

s1w

Joined
Jan 27, 2010
Messages
1
Reaction score
0
Code:
class myToggleBtn extends JToggleButton {
  String s;

  public myToggleBtn(String str, Boolean sel) {
    super(str, sel);
    s = str;
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (this.isSelected()) {
	    int w = getWidth();
	    int h = getHeight();
	    g.setColor(Color.green); // selected color
	    g.fillRect(0, 0, w, h);
	    g.setColor(Color.darkGray); // selected foreground color
	    g.drawString(s, (w - g.getFontMetrics().stringWidth(s))/2 + 1, (h + g.getFontMetrics().getAscent())/2 - 1);
	}
  }
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,262
Messages
2,571,045
Members
48,769
Latest member
Clifft

Latest Threads

Top