如何在另一个按钮中放置一个按钮(java)

Ano*_*aud 1 java swing jbutton

我被问到:

  1. 如果可以将一个按钮放置在框架中的另一个按钮内(使用JFrame
  2. 当我尝试执行此操作时会发生什么(他们要求测试是否告诉发生了什么)

我已经尝试过了,但是我不知道怎么做。我唯一成功完成的事情就是将两个按钮放在同一位置BorderLayout(例如,两个按钮位于“中心”位置,但我认为这与“一个按钮中的一个按钮”不是同一件事)。

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

And*_*son 5

是的,一个按钮可以添加到另一按钮。我将让您调查第二个问题。

在此处输入图片说明

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);
    }
}
Run Code Online (Sandbox Code Playgroud)