简体   繁体   English

使用小程序单击按钮时是否打印图像?

[英]Printing images when a Button is clicked using Applets?

So I need to display images when the button is clicked upon. 因此,我需要在单击按钮时显示图像。 When I click on the button it displays nothing. 当我单击按钮时,它什么也不显示。 Is it possible to pass a parameter into void paint method so that I can check the condition using if condition? 是否可以将参数传递给void paint方法,以便可以使用if条件检查条件? If square button is clicked it should print square and if circle button is clicked it should print circle 如果单击方形按钮,则应打印正方形,如果单击圆形按钮,则应打印圆圈

import java.applet.Applet;
import java.awt.Button;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class Jungle extends Applet implements ActionListener{
    Button n;
    Button o;
    public void init()

    {
        n=new Button("Square");
        add(n);
        n.addActionListener(this);
         o = new Button("circle");
        add(o);
        o.addActionListener(this);



    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==n)
        {
            repaint();
        };


    }
    class Delta
    {
        void graphics(Graphics g)
        {
            g.drawRect(40, 40, 20, 20);
            g.fillRect(40, 40, 20, 20);
        }
    }

}

..so that I can check the condition using if condition.. ..以便我可以使用if条件检查条件。

Declare an image as a class attribute and set its value to null : 将图像声明为类属性,并将其值设置为null

Image img = null;

When the button is clicked, set the image to equal the image to display. 单击该按钮时,将图像设置为等于要显示的图像。

In the paint(Graphics) method, check for null before painting the image. paint(Graphics)方法中,在绘制图像之前检查是否为null。 EG: 例如:

if (img!=null) {
    g.drawImage(img, 0, 0, this);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM