Ryan's District Boards

Computer, programming, and webmaster help , support , tips and tricks => Tutorials Zone! => Internet webmaster computer programming technology tips and tricks => Java Tutorials => Topic started by: automatic_poster on May 19, 2006, 11:42:13 PM

Title: [Java tutorial] A simple if else..
Post by: automatic_poster on May 19, 2006, 11:42:13 PM
 
If else? What are "if elses" and why do you use it?

Example:

When coding a java application you often use awt or swing components like a Button, Label etc
Assume you have two buttons in your GUI and want to know which one you have pressed on. With the use of the ActionListener you can define what the button does after you clicked it.

I'm now going to show you some code so you see how it works, let's write a simple java application shall we?

First we need to declare two buttons for the if else later on the guide:
Code

GeSHi (java):
Private JButton b1,b2;
Created by GeSHI 1.0.7.5


After this we must add  an actionlister for each button:

Code

GeSHi (java):
b1.addActionListener(this);
b1.addActionListener(this));
Created by GeSHI 1.0.7.5


We have 2 JButtons now. So how do we tell the computer on which button we clicked?
Well.. this is the part we use the "if else" statement.

Let's say you clicked on b1, and you want a message that tells you that you clicked the button, same goes for b2. We do this with the following code:

Code

GeSHi (java):
public actionPerformed(ActionEvent e) {
if (e.getSource() ==b1) {
//do b1
System.out.println("Button1");
}
if (e.getSource() == b2) {
//do b2
System.out.println("Button2");
}
else {
//do something else
}
Created by GeSHI 1.0.7.5


I Assume the code shouldn't be too hard to understand. "If" you have a question, just post it here, i can code you a working if else application if you want so you can test it our yourself.


Credit : by www.happyserver.be
Title: Re: [Java tutorial] A simple if else..
Post by: MojoFighter on March 27, 2010, 06:14:23 AM
oh no what happened to happyserver