How to change JLabel background when I click the JLabel in Java - java

I want to change my JLabel background to blue using mouseClicked. The name of my JLabel is lblKembali. I tried this code and when I tried to click the label it didnt change the background. Please help. Thank you.
lblKembali = new JLabel("Kembali");
lblKembali.setPreferredSize(new Dimension(400,30));
lblKembali.setMaximumSize(getPreferredSize());
lblKembali.addMouseListener(new java.awt.event.MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
lblKembali.setBackground(Color.BLUE);
}
});

By default a JLabel is non-opaque so its background is not painted. You need to make the label opaque when you create it:
lblKembali = new JLabel("Kembali");
lblKembali.setOpaque( true );
Also you can make your listener more generic so it can be shared by multiple components by doing:
public void mouseClicked(MouseEvent e)
{
Component c = e.getComponent();
c.setBackground(Color.BLUE);
}

Related

How to add mouse listener to JOptionPane button?

I want to change appearance of Button on JOptionPane.ShowMessageDialog.
I have managed to change Button caption with
UIManager.put("OptionPane.okButtonText", "Text I want");
Now, my next goal is to make Button work same as buttons in rest of my app. That is, when hovering mouse over it, it changes background and font color.
On rest of my buttons I added mouse listener like this one:
//setting change color on hover
private final MouseListener mouseAction = new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
JButton rollOver = (JButton)e.getSource();
if (rollOver.isEnabled()) {
rollOver.setBackground(new Color(163, 184, 204));
rollOver.setForeground(Color.WHITE);
rollOver.setFont(b);
}
};
#Override
public void mouseExited(MouseEvent e) {
JButton rollOver = (JButton)e.getSource();
if (rollOver.isEnabled()) {
rollOver.setBackground(new Color(230, 230, 230));
rollOver.setForeground(Color.BLACK);
rollOver.setFont(f);
}
};
};
Previously in code I have Font varibles set:
Font f = new Font("System", Font.PLAIN, 12);
Font b = new Font("System", Font.BOLD, 12);
I could make new dialogs from scratch and implent this behaviour but that would be overkill.
Is there some way to access Button on JOptionPane and add mouse listener
to it?
UIManager.put("OptionPane.okButtonText", "Text I want");
The above will change the text for all "Ok" buttons on all JOptionPanes that you create.
If you want to change the text on an individual button on a specific JOptionPane then
read the section from the Swing tutorial on Customizing Button Text.
Is there some way to access Button on JOptionPane and add mouse listener to it?
When you use the static showXXX(...) methods a modal JDialog is created so you don't have access to the dialog or its components until the dialog is closed which is too late.
So instead you need to manually create the JOptionPane and add it to a JDialog. The basics of doing this can be found by reading the JOptionPane API and looking at the section titled "Direct Use".
Once you have created the JOptionPane (and before you make the dialog visible) you can then search the option pane for the buttons and add a MouseListener to each button. To help you with this you can use the Swing Utils class. It will do a recursive search of the option pane and return the buttons to you in a List. You can then iterate through the List and add the MouseListener.
The basic code using this helper class would be:
JOptionPane optionPane = new JOptionPane(
"Are you sure you want to exit the application",
JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_CANCEL_OPTION);
List<JButton> buttons = SwingUtils.getDescendantsOfType(JButton.class, optionPane, true);
for (JButton button: buttons)
{
System.out.println( button.getText() );
}
If you want to see the same effect inside all OptionPanels, I think the override BasicOptionPaneUI is a good solution
This is a minimal example
public class MyOptionPaneUI extends BasicOptionPaneUI {
#SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"})
public static ComponentUI createUI(JComponent c) {
return new MyOptionPaneUI();
}
private static final MyMouseListener m = new MyMouseListener();
#Override
public void update(Graphics g, JComponent c) {
super.update(g, c);
}
#Override
protected void installListeners() {
JButton button = (JButton) getButtons()[0];
button.addMouseListener(m);
super.installListeners();
}
#Override
protected void uninstallListeners() {
JButton button = (JButton) getButtons()[0];
button.removeMouseListener(m);
super.uninstallListeners();
}
public static class MyMouseListener extends MouseAdapter{
#Override
public void mouseEntered(MouseEvent e) {
JButton rollOver = (JButton)e.getSource();
if (rollOver.isEnabled()) {
rollOver.setBackground(new Color(163, 184, 204));
rollOver.setForeground(Color.WHITE);
}
};
#Override
public void mouseExited(MouseEvent e) {
JButton rollOver = (JButton)e.getSource();
if (rollOver.isEnabled()) {
rollOver.setBackground(new Color(230, 230, 230));
rollOver.setForeground(Color.BLACK);
}
};
}
}
inside your frame your main class you can add this code for load the class inside the UIDefoult
static{
UIManager.put("OptionPaneUI", MyOptionPaneUI.getClass().getCanonicalName());
}
Because getButtons()[0], because I see this code inside the BasicOptionPaneUI
else if (type == JOptionPane.OK_CANCEL_OPTION) {
defaultOptions = new ButtonFactory[2];
defaultOptions[0] = new ButtonFactory(
UIManager.getString("OptionPane.okButtonText",l),
getMnemonic("OptionPane.okButtonMnemonic", l),
(Icon)DefaultLookup.get(optionPane, this,
"OptionPane.okIcon"), minimumWidth);
defaultOptions[1] = new ButtonFactory(
UIManager.getString("OptionPane.cancelButtonText",l),
getMnemonic("OptionPane.cancelButtonMnemonic", l),
(Icon)DefaultLookup.get(optionPane, this,
"OptionPane.cancelIcon"), minimumWidth);
} else {
defaultOptions = new ButtonFactory[1];
defaultOptions[0] = new ButtonFactory(
UIManager.getString("OptionPane.okButtonText",l),
getMnemonic("OptionPane.okButtonMnemonic", l),
(Icon)DefaultLookup.get(optionPane, this,
"OptionPane.okIcon"), minimumWidth);
}
inside the method protected Object[] getButtons()
If you want the effect mouse hover on the button I'm working on this library and have the solution for the mouse over.
If you have a possibility to personalize the DefaoultButton inside the library with this constant
UIManager.put("Button[Default].background", new Color(163, 184, 204));
UIManager.put("Button[Default].foreground", Color.WHITE);
UIManager.put("Button[Default].mouseHoverColor", new Color(230, 230, 230));
ps: this is only information if you need to add the mouse hover inside the you project

Change tab look for JTabbedpane

How can I remove OR change colour of the border surrounding these tabs?
ALSO, is it possible to have the tab text change colour when the mouse is hovering over it?
Is it possible to have the tab text change colour when the mouse is
hovering over it?
As stated in this answer you can set a custom component for rendering the tab title, through JTabbedPane.setTabComponentAt(int index, Component component) method. So you can do something like this:
final JTabbedPane tabbedPane = new JTabbedPane();
MouseListener mouseListener = new MouseAdapter() {
Color defaultColor;
#Override
public void mouseEntered(MouseEvent e) {
JLabel label = (JLabel)e.getSource();
defaultColor = label.getForeground();
label.setForeground(Color.BLUE);
}
#Override
public void mouseExited(MouseEvent e) {
JLabel label = (JLabel)e.getSource();
label.setForeground(defaultColor);
}
#Override
public void mouseClicked(MouseEvent e) {
JLabel label = (JLabel)e.getSource();
Point point = SwingUtilities.convertPoint(label, e.getPoint(), tabbedPane);
int selectedTab = tabbedPane.getUI().tabForCoordinate(tabbedPane, point.x, point.y);
switch(e.getButton()){
case MouseEvent.BUTTON2: tabbedPane.removeTabAt(selectedTab); break;
default: tabbedPane.setSelectedIndex(selectedTab);
}
}
};
JLabel tab1 = new JLabel("Tab1");
tab1.addMouseListener(mouseListener);
tabbedPane.addTab(null, new JPanel());
tabbedPane.setTabComponentAt(0, tab1);
How can I remove OR change colour of the border surrounding these
tabs?
It's up to the Look and Feel decide the border color in this case. You should look into the L&F default properties and see if it's allowed change this color. For instance you could execute the following code to see L&F default properties (of course after setting the L&F):
for(Object key : UIManager.getLookAndFeelDefaults().keySet()){
System.out.println(key + " = " + UIManager.get(key));
}

Mouse over events with JButton

I'm trying to create a custom mouse over event on a JButton. The reason being that my JButton is currently an image, so I had to remove all the borders and animations and what not. so I did this:
btnSinglePlayer.setOpaque(false);
btnSinglePlayer.setContentAreaFilled(false);
btnSinglePlayer.setBorderPainted(false);
And that works perfect to only display the image, and the button does in fact work. I want to know if there's any pre-built methods perhaps that can do this, or how I would go about learning to do what I want.
More specifically, what I want the image to do when I mouse over is for it to get just a bit bigger.
I have tried these so far, and did nothing:
btnSinglePlayer.setRolloverIcon(singlePlayerButton);
btnSinglePlayer.setPressedIcon(singlePlayerButton);
for Icon to use implemented methods in API
you can to use ButtonModel with ChangeListener
(by default) for JButtons JComponents there no reason to use Mouse(Xxx)Listener or its MouseEvent, all those events are implemented and correctly
As an alternative You can achieve this by registering MouseListener to the JButton and override mouseEntered() ,mouseExited() , mousePressed() and mouseReleased() method.For Example:
final ImageIcon icon1 = new ImageIcon("tray.gif");
final JButton button = new JButton(icon1);
final int width = icon1.getIconWidth();
final int height = icon1.getIconHeight();
button.addMouseListener(new MouseAdapter()
{
public void mouseEntered(MouseEvent evt)
{
icon1.setImage((icon1.getImage().getScaledInstance(width + 10, height,Image.SCALE_SMOOTH)));
//button.setIcon(icon1);
}
public void mouseExited(MouseEvent evt)
{
icon1.setImage((icon1.getImage().getScaledInstance(width , height,Image.SCALE_SMOOTH)));
}
public void mousePressed(MouseEvent evt)
{
icon1.setImage((icon1.getImage().getScaledInstance(width + 5, height,Image.SCALE_SMOOTH)));
}
public void mouseReleased(MouseEvent evt)
{
icon1.setImage((icon1.getImage().getScaledInstance(width + 10, height,Image.SCALE_SMOOTH)));
}
});
button.setOpaque(false);
button.setContentAreaFilled(false);
button.setBorderPainted(false);

Swing : Setting JButton's background

I want to set the background color of JButton. For that I use
setBackground() method.
This method jsut sets the border color of the button and not the whole button of the specified color. Why so ? This is the only method to set background color of a button. Where am I making a mistake due to which it sets just the border of the button of specified color and not actual button ?
Code :
account_btn.setAction(actionMap.get("AccountingClicked")); // NOI18N
account_btn.setBackground(Utility.getBackgroundColor());
account_btn.setFont(Utility.getButtonFont());
account_btn.setForeground(Utility.getTextColor());
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(cashaccountingapp.CashAccountingApp.class).getContext().getResourceMap(MainPanel.class);
account_btn.setText(resourceMap.getString("account_btn.text")); // NOI18N
account_btn.setBorderPainted(false);
account_btn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
account_btn.setName("account_btn"); // NOI18N
account_btn.setOpaque(true);
add(account_btn);
Result :
Have tried setting setOpaque(true) also. But you can see the results of account_btn i.e. "Accounting". setOpaque seems to have no effects.
Any idea.
SOLUTION :
Setting L&F
private void initLookandFeel() {
try {
System.out.println("DEFAULT Look & Feel = " + UIManager.getLookAndFeelDefaults().toString());
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
javax.swing.SwingUtilities.updateComponentTreeUI(this.mainPanel);
System.out.println("Look & Feel = " + UIManager.getLookAndFeel().toString());
} catch(Exception e) { ..... }
}
I call initLookandFeel() after initComponents() and also update my mainPanel. Also needed to update my dynamically added panel at initial stage then no need to set anything more.
import java.awt.*;
import javax.swing.*;
class ColoredButtons {
ColoredButtons() {
JPanel gui = new JPanel(new GridLayout(1,0,5,5));
JButton one = new JButton("One");
one.setBackground(Color.RED);
JButton two = new JButton("Two");
two.setBackground(Color.RED);
gui.add(one);
gui.add(two);
JOptionPane.showMessageDialog(null, gui);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ColoredButtons();
}
});
}
}
There is my SSCCE. The buttons are red. The PLAF is metal.
Which brings me back to: Where is your SSCCE? What PLAF are you using?
I believe the Jbutton background is controlled by the particular look-and-feel you are using. To change the background you may need to modify the
setUI(ComponentUI newUI)
with your own one.
Try setting border painted to false and opaque true
account_btn.setBorderPainted(false);
account_btn.setOpaque(true);

adding components in applet

I am making an applet and as part of my applet, I want this to happen: When the user presses "OK", the old components (some radio buttons) are removed, and a new JPanel is added, with a bunch of textfields.
However, I cannot figure out how to add a new component to the applet after it has started. I made the problem simpler by ignoring the removal part (Which I know how to do) and just adding a simple JLabel instead, but even that won't add!
Here is my code so far:
// imports omitted
public class Class extends Applet implements ActionListener
{
Button okButton;
CheckboxGroup radioGroup;
Checkbox radio1;
Checkbox radio2;
Checkbox radio3;
JLabel j;
public void init()
{
setLayout(new FlowLayout());
okButton = new Button("OK");
j = new JLabel("hello");
radioGroup = new CheckboxGroup();
radio1 = new Checkbox("Red", radioGroup,false);
radio2 = new Checkbox("Blue", radioGroup,true);
radio3 = new Checkbox("Green", radioGroup,false);
add(okButton);
add(radio1);
add(radio2);
add(radio3);
okButton.addActionListener(this);
}
public void repaint(Graphics g)
{
if (radio1.getState()) add(j);
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == okButton) repaint();
}
}
What am I doing wrong?
You shouldn't override the repaint method, and certainly not add a component in this method. Just remove the radio buttons from the applet (using its remove method) and add the label in the applet in your actionPerformed method, the same way you add them in the init method.
You might have to call validate after.
Add components and then call validate() of your container. In this case yourApplet.validate(). This will trigger repainting and rearranging of all elements.
you could do something like
JFrame fr= new JFrame(); // global variables
JPanel panelToBeAdded = new JPanel();
JPanel initialPanel = new JPanel();
JTextField fieldToBeAdded = new JTextField();
panelToBeAdded.setPreferredSize( new Dimension(400,400));
initialPanel.setPreferredSize( new Dimension(400,400));
initialPanel.setVisible(true);
fr.add(initialPanel);
fr.setVisible(true);
fr.pack();
public void actionPerformed(ActionEvent ae) {
initialPanel.setVisible(false);
//radiobuttons.setVisible(false);---> hide the radio buttons
panelToBeAddedd.add(fieldToBeAddedd);
panelToBeAddedd.setVisible(true);
fr.add(panelToBeAddedd);
}
public void repaint( Graphics g ) {
// do something
}
What am I doing wrong?
Your repaint(Graphics) method is not the same method you are calling in your actionPerformed method.
Also, repaint is a pretty bad name for a method which is adding a new component.
public void swapComponents()
{
if (radio1.getState()) {
remove(radio1);
remove(radio2);
remove(radio3);
add(j);
validate();
}
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == okButton) {
swapComponents();
}
}
When the user presses "OK", the old components (some radio buttons) are removed, and a new JPanel is added, with a bunch of textfields.
Use a CardLayout, as shown here. It is perfect for situations like this.

Categories