如何在另一个按钮上创建此按钮?

时间:2019-01-28 10:09:45

标签: java swing

作为标题,我想在java swing中创建两个按钮,并且这两个按钮可以彼此重叠(作为图像)。我搜索了互联网,但找不到。

image

非常感谢

3 个答案:

答案 0 :(得分:0)

您只需将JFrame的布局设置为Absolute Layout,然后在另一个JButton的顶部添加一个JButton,就可以轻松地做到这一点。确保小按钮位于导航器中另一个按钮的顶部。


enter image description here

enter image description here

答案 1 :(得分:0)

您可以在此处使用OverlayLayout

SSCCE(内部带有注释)为:

import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.OverlayLayout;
import javax.swing.SwingUtilities;

public class OverlayLayoutExample extends JFrame {
    JPanel overlayoutPanel;
    JButton jButton2, jButton1;

    public OverlayLayoutExample() {

        overlayoutPanel = new JPanel() {
            @Override
            public boolean isOptimizedDrawingEnabled() {
                //Required to have always visible both components
                return false;
            }
        };

        OverlayLayout overlay = new OverlayLayout(overlayoutPanel);
        overlayoutPanel.setLayout(overlay);
        jButton1 = new JButton("jButton");
        Dimension d1 = new Dimension(350, 100);
        jButton1.setMaximumSize(d1);
        jButton1.setAlignmentX(0.7f); //Some X-Y values, play with them
        jButton1.setAlignmentY(0.65f); //Some X-Y values, play with them

        jButton2 = new JButton("jButton2");
        Dimension d2 = new Dimension(100, 25);
        jButton2.setMaximumSize(d2);
        jButton2.setAlignmentX(0.01f); //Some X-Y values, play with them
        jButton2.setAlignmentY(0.01f); //Some X-Y values, play with them

        overlayoutPanel.add(jButton2); //First the top component
        overlayoutPanel.add(jButton1); //Then the above component

        getContentPane().add(overlayoutPanel);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 300);
    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(() -> new OverlayLayoutExample().setVisible(true));
    }
}
关于isOptimizedDrawingEnabled()

更多可以找到here.

预览:

enter image description here

答案 2 :(得分:0)

您可以使用JFrame的分层窗格来做到这一点:

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;

public class ButtonOnTop
{
  public static void main(String[] args)
  {
    JButton button1 = new JButton("jButton1");
    button1.setBounds(30, 50, 260, 160);

    JButton button2 = new JButton("jButton2");
    button2.setBounds(150, 150, 100, 40);

    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JLayeredPane layeredPane = f.getLayeredPane();
    layeredPane.add(button1, Integer.valueOf(0));
    layeredPane.add(button2, Integer.valueOf(1));

    f.setBounds(300, 200, 400, 300);
    f.setVisible(true);
  }
}