如何使用图像在叠加布局上添加按钮 [英] How to add buttons on an overlay layout with an image

查看:109
本文介绍了如何使用图像在叠加布局上添加按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将图像设置为背景,以便将按钮放在它上面,所以我使用了Overlay图层。 Ι只是想改变按钮的位置并将它们放在图片上方,但我找不到方法。

I wanted to set an image as background in order to put buttons above it, so I used the Overlay layer. Ι just wanted to change the position of the buttons and put them above the picture, but I cannot find a way.

public static void main(String[] args){

    Menu program = new Menu();
    SwingUtilities.invokeLater(program);

}


public void run() {

    JFrame frame = new JFrame () ;
    Get_size get_size = new Get_size() ;
    get_size.Size_screen() ;
    int h = (int)height ;
    int w = (int) width;
    frame.setSize(w , h );

    JPanel panel = new JPanel();

    //Create the first  button
    JButton appointment = new JButton("Appointment menu & Diary");
    appointment.setPreferredSize(new Dimension(500,32));
    appointment.setFont(new Font("Algerian", Font.PLAIN , 24));
    panel.add(appointment) ;

    //Create the second  button
    JButton patient_profile = new JButton("Patient Profile");
    patient_profile.setPreferredSize(new Dimension(300, 32));
    patient_profile.setFont(new Font("Algerian", Font.PLAIN , 24));
    panel.add(patient_profile) ;


    JPanel over = new JPanel();
    LayoutManager overlay = new OverlayLayout(over);
    over.setLayout(overlay);

    JPanel imagen1 = new JPanel();
    ImageIcon image = new ImageIcon("menu.jpg") ;



    imagen1.add(new JLabel(image));

    over.add(imagen1);
    over.add(panel);
    frame.add(over);



    //sets the size of the frame
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //makes it so you can close
    frame.setVisible(true);

   // Set the frame of the size non-resizable
   frame.setResizable(false);
}


推荐答案

over.add(imagen1);
over.add(panel);

Swing按照添加的相反顺序绘制组件。因此,上面的代码将绘制面板,然后在面板顶部绘制图像,这样您才能看到图像。

Swing paints components in the reverse order they are added. So the above code will paint the panel and then the image on top of the panel so you will only see the image.

代码应该颠倒过来:

over.add(panel);
over.add(imagen1);

现在,面板将绘制在图像的顶部。但是,由于面板是不透明的,您将看不到图像,因此您还需要使面板不透明:

Now the panel will be painted on top of the image. However, since a panel is opaque, you will not see the image, so you also need to make the panel non-opaque:

JPanel panel = new JPanel();
panel.setOpaque(false);

这篇关于如何使用图像在叠加布局上添加按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆