如何将一个按钮放在另一个按钮内 (java)

How to place a button within another button (java)

有人问我:

  1. 如果可以将一个按钮放在框架中的另一个按钮内(JFrame
  2. 当我尝试这样做时会发生什么(他们要求测试是否会发生什么)

我试过了,但我不知道怎么做。我唯一成功的是把两个按钮放在 BorderLayout 的同一个地方(例如 "center" 位置的两个按钮,但我不认为它和 "one button within a button".

如果有人知道是否可以做到或如何做到,那就太好了!

是的,一个按钮可以添加到另一个按钮。第二个问题留给你调查。

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.net.*;

public class ButtonQuestion {

    private JComponent ui = null;
    JButton button1;
    JButton button2;

    ButtonQuestion() {
        try {
            initUI();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
    }

    public void initUI() throws MalformedURLException {
        if (ui!=null) return;

        ui = new JPanel(new BorderLayout(4,4));
        ui.setBorder(new EmptyBorder(4,4,4,4));

        button1 = new JButton("button 1", new ImageIcon(
                new URL("https://i.stack.imgur.com/in9g1.png")));
        button2 = new JButton("button 2", new ImageIcon(
                new URL("https://i.stack.imgur.com/wCF8S.png")));
        ui.add(button1);
        // Yep. One button can indeed be added to another..
        button1.add(button2);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception useDefault) {
                }
                ButtonQuestion o = new ButtonQuestion();

                JFrame f = new JFrame(o.getClass().getSimpleName());
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);

                f.setContentPane(o.getUI());
                f.pack();
                f.setMinimumSize(f.getSize());

                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}