0

I used the following code to display a jbutton over an image.But he button is not displayed until i put my cursor over the button position.What is the correction in the code?

file Project31.java

package project31;

import javax.swing.JFrame;
import java.awt.*;

public class Project31 {


    public static void main(String[] args) {

        studentinfo studentinfo=new studentinfo();
        studentinfo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        studentinfo.setSize(1368,768);
        studentinfo.setVisible(true);
    }
}

file studentinfo.java

package project31;


import java.io.*;
import javax.sound.sampled.*;
import sun.audio.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class studentinfo extends JFrame{

    private JButton plainJButton;
    Image stuinfo=Toolkit.getDefaultToolkit().getImage("stuinfo.png");

    public studentinfo(){
            setLayout(new FlowLayout());
            plainJButton=new JButton("Search");
            add (plainJButton);
            ButtonHandler handler=new ButtonHandler();
            plainJButton.addActionListener(handler);
    }

    private class ButtonHandler implements ActionListener{

        public void actionPerformed(ActionEvent event){

        }
    }

    public void paint(Graphics g){
        g.drawImage(stuinfo,16,10,this);
    }

}
mKorbel
  • 109,525
  • 20
  • 134
  • 319

2 Answers2

1

You have to repaint the button as well. But I'll suggest you to use a JPanel and draw the image on it. Then draw the JButton:

class ImagePanel extends JPanel{
   private Image stuinfo;
   public ImagePanel() {
      stuinfo = Toolkit.getDefaultToolkit().getImage("stuinfo.png");
   }
   public void paintComponent(Graphics g){ 
      super.paintComponent(g);
      g.drawImage(stuinfo,16,10,this);
   }
}

Then:

1. Create your JFrame
2. Add an object of ImagePanel to the JFrame with `setContentPane()`
3. Add your button. 

Now you have a button on top of the image.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
1

You can also make yout image an Icon for the button, as shown here and here.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045