how can i put a JButton on an image?

拟墨画扇 提交于 2019-11-29 07:43:32

You need to change the content pane to get a background for your Frame.

public static void main(String[] args) throws IOException {

    JFrame frame = new JFrame("Test");

    frame.setContentPane(new JPanel() {
        BufferedImage image = ImageIO.read(new URL("http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png"));
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image, 0, 0, 300, 300, this);
        }
    });

    frame.add(new JButton("Test Button"));

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 300);
    frame.setVisible(true);
}

Output:

Have you tried using a JLabel with HTML in the label? Something like this:

import javax.swing.*;

public class SwingImage1
{
  public static void main( String args[] )
  {
    JFrame  frm = new JFrame( "Swing Image 1" );
    JLabel  lbl = new JLabel( "<html><body><img src=\"http://liv.liviutudor.com/images/liv.gif\"></body></html>" );
    frm.getContentPane().add( lbl );
    frm.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frm.pack();
    frm.setVisible( true );
  }
}

then on top of your label you can add your button?

You should swap those two lines:

super.paintComponents(g);  //paints the children, like the button
g.drawImage(background, 0, 25, null); // draw background later possibly overwriting the button

Thus it should be this order:

g.drawImage(background, 0, 25, null);
super.paintComponents(g); 

Additionally, note that the content pane's default layout is BorderLayout. Thus you'd set the layout of your content pane to null explicitly.

/*it is simple to put button on image first set image by making object then make button object & add the button object direct to image object rather then add to frame.*/

package frame;



import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class frame 
{

    public frame() 
    {
        JFrame obj = new JFrame("Banking Software");
        JButton b1 = new JButton("Opening Account");
        JLabel image = new JLabel(new ImageIcon("money.jpg"));
        image.setBounds(0,0, 1600, 1400);
        obj.setExtendedState(JFrame.MAXIMIZED_BOTH);
        obj.add(image);
        b1.setBounds(500,400, 100, 40);
        image.add(b1);
        obj.setVisible(true);
    }

    public static void main(String args[]) 
    {
        new frame();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!