我使用以下代码在图像上显示jbutton。但是直到我将光标放在按钮位置上,他才显示他的按钮。代码中的校正是什么?p>文件 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);
}
}
文件 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);
}
}
您也必须重新粉刷按钮。但是我建议您使用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.
现在您的图像顶部有一个按钮。
您还可以使yout image成为按钮的 Icon
,如下所示。