Home > Mobile >  Put a Jbutton On a Jbutton on java Swing
Put a Jbutton On a Jbutton on java Swing

Time:01-06

import java.awt.EventQueue;
import java.awt.GridLayout;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;



public class ButtonOnButton extends JFrame {

    private JPanel contentPane;
    private JButton firstButton; // first Button
    private JButton secondButton; // second Button
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ButtonOnButton frame = new ButtonOnButton();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public ButtonOnButton() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
         GridLayout gl = new GridLayout(1,0); // the button is in entire screen now and i want to put the "secondButton" on this red button.
        contentPane.setLayout(gl);
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        firstButton = new JButton(""); // 
        secondButton = new JButton("");
        firstButton.setDisabledIcon(new ImageIcon(getClass().getResource("meeple.jpg"))); // disabled icon
        firstButton.setEnabled(false);
        secondButton.setBackground(Color.blue);
        
        contentPane.add(firstButton);
        firstButton.add(secondButton);
        setContentPane(contentPane);
// it work with button enabled, but diswork with button disabled and setDisabledIcon 
//sorry for my english bad i hope sincerly you understand( here decipher ).
    }

}

https://img.codepudding.com/202301/3fbdfa0f149747f28bc9883d48bd922e.png

I want to put a Jbutton on a Jbutton i.e The JButton is setEnabledFalse and have a DisabledIcon and has another button on top (in the link it is blue)

// I want to put a Jbutton on a Jbutton 
//  i.e The JButton is setEnabledFalse and have a DisabledIcon and has another button on top (in //the link it is blue)

CodePudding user response:

This seems to be a quirk of the button. In order to display a disabled icon you also need to provide the button with a regular icon.

In your example you only care about the disabled state so you can share the Icon:

    ImageIcon icon = new ImageIcon(getClass().getResource("meeple.jpg"));
    firstButton.setIcon(icon); 
    firstButton.setDisabledIcon(icon); 
  • Related