If Statement

This applet demonstrates the use of an If statement. The If statement is used to respond differently, depending on which button is clicked.

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class IfDemo extends Applet implements ActionListener
{

Button button1, button2;
boolean button1Click=false, button2Click=false;
public void init()
{

// Instantiate buttons and listeners
button1 = new Button ("button 1");
add(button1);
button1.addActionListener(this);
button2 = new Button ("button 2");
add(button2);
button2.addActionListener(this);

}
public void paint(Graphics g)
{

// Paint the text on the screen
g.drawString("Click one of the buttons",50,50);
if (button1Click)
g.drawString("You have clicked button 1",50,100);
else if (button2Click)
g.drawString("You have clicked button 2",50,100);

}
public void actionPerformed(ActionEvent e)
{

// Wait to see which button is clicked
// set the other button to false

if (e.getSource() == button1)
{

button1Click=true;
button2Click=false;

}
if (e.getSource() == button2)
{

button2Click=true;
button1Click =false;

}
//Repaint the screen after the button is clicked
repaint();

}

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License