Creating a Interactive GUI for a java game

[亡魂溺海] 提交于 2019-12-04 15:44:47

You can use JButton, just override the paint function. and draw what ever you want there. It takes a while until you get it at the first time how this works. I recommend you to read a little about the event-dispatching thread (here is java's explanation)

And here is some code that I wrote so you have a simple reference.

import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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


public class Test extends JButton implements ActionListener{

    private static final long serialVersionUID = 1L;
    Image img;

        /**  constuctor     **/
    public Test(String tImg, JFrame parent){
        this.img = new ImageIcon(tImg).getImage();
        this.addActionListener(this);

    }


           /***********    this is the function you want to learn  ***********/
    @Override
    public void paint(Graphics g){
        g.drawImage(this.img, 0, 0, null);
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        // TODO do some stuff when its clicked
        JOptionPane.showMessageDialog(null, "you clicked the button");
    }




    public static void main(String[] args) {
        JFrame f = new JFrame();
        Test t = new Test("pics.gif", f);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLayout(new GridLayout(1, 1));
        f.add(t);
        f.setSize(400,600);
        f.setVisible(true);
    }

}
Stealth Rabbi

Do you really not want to use Swing, or do you just not want the default look and feel of a JButton and other swing controls? What does " (generic windows looky likey objects), " mean?

There are many sources out there that describe customizing buttons to include images on top of them: Creating a custom button in Java

JButton and other controls have all the events and methods associated with adding click listeners, etc. You probably don't want to create your own control. We do not have enough information to go off of, for example what does "interactive objects" mean?

If you simply want to add an icon to a JButton, use the constructor that takes an Icon.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!