Home Tutorial Java Swing Find Array element from index using GUI

 
 

Share on Google+Share on Google+
Find Array element from index using GUI
Posted on: December 4, 2012 at 12:00 AM
Advertisement
In this tutorial, you will learn how to create an GUI application to find an array element from its index.

Find Array element from index using GUI

In this tutorial, you will learn how to create an GUI application to find an array element from its index. For this, we have created an an array of 100 randomly chosen integers and allow the user to enter an array index in the textfield. The another textfield is defined to display the element at that specific index. A button 'Show Element' is defined for an action to cause the array element to be displayed. If the specified index is out of bounds, display the message "Out of Bounds"

Example:

import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;

class ShowElement extends JFrame{
JButton ADD;
JPanel panel;
JLabel label1,label2;
final JTextField text1,text2;
ShowElement(){
label1 = new JLabel();
label1.setText("Enter Index:");
text1 = new JTextField(20);

label2 = new JLabel();
label2.setText("Element at specific Index:");
text2 = new JTextField(20);

ADD=new JButton("Show Element");

panel=new JPanel(new GridLayout(3,2));
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(ADD);
add(panel,BorderLayout.CENTER);
Random r=new Random(); 

final int arr[]=new int[100];
for(int i=0;i<arr.length;i++){
int x=r.nextInt(100)+1;
arr[i]=x;
}
ADD.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
try{
String value=text1.getText();
int in=Integer.parseInt(value);
if(in>=100){
JOptionPane.showMessageDialog(null,"Out of Bounds");
}
else{
int ele=0;
for(int i=0;i<arr.length;i++){
if(i==in){
ele=arr[i];
}
}

text2.setText(Integer.toString(ele));
}
}
catch(Exception e){}
}
});
}

public static void main(String arg[])
{
try
{
ShowElement frame=new ShowElement();
frame.setSize(300,300);
frame.setVisible(true);
}
catch(Exception e){
}
}
}
Advertisement

Related Tags for Find Array element from index using GUI:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 4, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com