0

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

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

}
4

2 回答 2

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. 

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

于 2012-10-31T11:32:23.440 回答
1

您还可以将您的图像Icon设置为按钮,如此处和此处所示

于 2012-10-31T12:59:57.663 回答