How to add buttons on an overlay layout with an im

2019-09-22 18:41发布

问题:

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);
}

回答1:

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

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.

The code should be reversed:

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);


回答2:

you have to define layout. Wheather it is null or frame layout or border etc.

look it up here https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html