如何在图像上显示JButton?

时间:2012-10-31 11:07:50

标签: java swing graphics jbutton paint

我使用以下代码在图像上显示一个jbutton。但是,在我将光标放在按钮位置之前,他的按钮不会显示。代码中的修正是什么?

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

}

2 个答案:

答案 0 :(得分:1)

您还必须重新绘制按钮。但我建议你使用JPanel并在其上绘制图像。然后绘制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);
   }
}

然后:

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

现在,图像顶部有一个按钮。

答案 1 :(得分:1)

您还可以制作图片,Icon为按钮,如herehere所示。