News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

[Java tutorial] A simple if else..

Started by automatic_poster, May 19, 2006, 11:42:13 PM

Previous topic - Next topic

0 Members and 2 Guests are viewing this topic.

automatic_poster

 
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 You are not allowed to view links. Register or Login
All my posts are from You are not allowed to view links. Register or Login

MojoFighter

You are not allowed to view links. Register or Login