在点击JButton时显示图像 [英] Displaying image on clicking JButton

查看:167
本文介绍了在点击JButton时显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在点击JButton时显示图片,但执行时点击按钮时不显示图片。

Im trying to display an image upon clicking a JButton but upon execution the image is not displayed when button is clicked.

    import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import java.awt.*;

public class new2 extends JFrame implements ActionListener
{
private boolean b1,b2;  

Container contentPane= getContentPane();
JButton awar=new JButton("@war");
JButton arrow=new JButton("arrow");
private Image image1,image2;

public new2()
    {
    setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        contentPane.setLayout(new FlowLayout());

        awar.addActionListener(this);
        contentPane.add(awar).setVisible(true);

        arrow.addActionListener(this);
        contentPane.add(arrow).setVisible(true);

        }

public void init()
    {


    image1=Toolkit.getDefaultToolkit().getImage("@war.jpeg");
    image2=Toolkit.getDefaultToolkit().getImage("arrow.gif");
    }


public void paint(Graphics g)
{

    if(b1==true)
    {
    g.drawImage(image1,0,0,this);
    }
    else if(b2==true)
    {
    g.drawImage(image2,0,0,this);
    }

}

public void actionPerformed(ActionEvent event)
{

        String actionCommand = event.getActionCommand();

    if(actionCommand.equals("@war"))
    {
    b1=true;
    }
    else if(actionCommand.equals("arrow"))
    {
    b2=true;
    }
}

public static void main(String args[])
{
new2 m=new new2();
m.setVisible(true);
}

}

推荐答案

您应该覆盖 JFrame.paint(Graphics g)方法。
每当你想刷新JFrame实例的内容时调用 JFrame.repaint()方法。

You should override the JFrame.paint(Graphics g) method. Whenever you want to refresh the content of the JFrame instance call the JFrame.repaint() method.

这篇关于在点击JButton时显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆