Java Queries Here..

Sudhir

Broken In
guys i'm having problem with ActionListener can anyone please tell me some solution!!!
i want to make a calculator using swing!!!

Code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

/**
 *
 * @author SudhiR
 */
class Calci implements ActionListener 
{
char op;
    String value="",cv="";
    int ctr=0;
    Double v1,v2,ans;
Frame fr;
MenuBar mBar;
Menu f,e;
MenuItem q,c,p;
JButton num0,num1,num2,num3,num4,num5,num6,num7,num8,num9,bDot,bAdd,bSub,bDiv,bMul,bSqrt,bPer,clear,bCE,back,equals,inv;
TextField txt;
Panel p1,p2,p3,p4,p5;
    
    
Calci(){
    
fr=new Frame("Calculator");
fr.setDefaultCloseOperation(Frame.EXIT_ON_CLOSE);
txt=new TextField(35);
txt.setText("0");
txt.setEnabled(false);
mBar=new MenuBar();
f=new Menu("File");
e=new Menu("Edit");
q=new MenuItem("Quit");
c=new MenuItem("Copy");
p=new MenuItem("Paste");
num0=new JButton("0");
num1=new JButton("1");
num2=new JButton("2");
num3=new JButton("3");
num4=new JButton("4");
num5=new JButton("5");
num6=new JButton("6");
num7=new JButton("7");
num8=new JButton("8");
num9 =new JButton("9");
bAdd=new JButton("+");
bSub=new JButton("-");
bDiv=new JButton("/");
bMul=new JButton("*");
bSqrt=new JButton("Sqrt");
bPer=new JButton("%");
clear=new JButton("C");
bCE=new JButton("CE");
back=new JButton("BackSpace");
equals=new JButton("=");
bDot=new JButton(".");
inv=new JButton("+/-");
p1=new Panel();
p2=new Panel();
p3=new Panel();
p4=new Panel();
p5=new Panel();
mBar.add(f);
mBar.add(e);
f.add(q);
e.add(c);
e.add(p);

p1.add(back);
p1.add(clear);
p1.add(bCE);

p2.add(num7);
p2.add(num8);
p2.add(num9);
p2.add(bAdd);
p2.add(bMul);

p3.add(num4);
p3.add(num5);
p3.add(num6);
p3.add(bSub);
p3.add(bDiv);

p4.add(num1);
p4.add(num2);
p4.add(num3);
p4.add(bDot);
p4.add(inv);

p5.add(num0);
p5.add(equals);
p5.add(bSqrt);
p5.add(bPer);

p1.setLayout(new GridLayout(1,3,2,2));
p2.setLayout(new GridLayout(1,5,2,2));
p3.setLayout(new GridLayout(1,5,2,2));
p4.setLayout(new GridLayout(1,5,2,2));
p5.setLayout(new GridLayout(1,4,2,2));

fr.setLayout(new GridLayout(6,1));
fr.setMenuBar(mBar);
fr.setResizable(false);
fr.setSize(300,300);

fr.add(txt);
fr.add(p1);
fr.add(p2);
fr.add(p3);
fr.add(p4);
fr.add(p5);
fr.setVisible(true);

}



public void op()
{
num0.addActionlistener(new ActionListener());
num0.addActionlistener(this);
num1.addActionlistener(this);
num2.addActionlistener(this);
num3.addActionlistener(this);
num4.addActionlistener(this);
num5.addActionlistener(this);
num6.addActionlistener(this);
num7.addActionlistener(this);
num8.addActionlistener(this);
num9.addActionlistener(this);
bAdd.addActionlistener(this);
bSub.addActionlistener(this);
bMul.addActionlistener(this);
bDiv.addActionlistener(this);
bSqrt.addActionlistener(this);
bPer.addActionlistener(this);
equals.addActionlistener(this);
clear.addActionlistener(this);
back.addActionlistener(this);
bCE.addActionlistener(this);
inv.addActionlistener(this);
bDot.addActionlistener(this);

q.addActionlistener(this);
c.addActionlistener(this);
p.addActionlistener(this);

}
//Menu Items//

if(ae.getSource()==q)
{
System.exit(0);
}
else if(ae.getSource()==c)
{
cv+=value;
}
else if(ae.getSource()==p)
{
value+=cv;
}

}


m using netbeans 7.2 for this program it'll give an error that class is not abstract so you cannot implements abstract ActionListener!!

after that i'll use notepad to edit it and then wen i'l compile it it'll give 25 ERRORS

cannot find symbol
.addActionListener(this);

please help me !! i'm new to java and m unable to assign actions the GUI i've made!!! please solve my problem!! ASAP!!!
 

dead.night7

Journeyman
Did you use an IDE for making this?
Have a look at my program, Simple basic java... May help you in understanding ActionListener

Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class EventDemo {
JLabel jlab;
EventDemo() {

// Create a new JFrame container.
JFrame jfrm = new JFrame("An Event Example");

// Specify FlowLayout for the layout manager.
jfrm.setLayout(new FlowLayout());

// Give the frame an initial size.
jfrm.setSize(220, 90);

// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Make two buttons.
JButton jbtnAlpha = new JButton("Alpha");
JButton jbtnBeta = new JButton("Beta");

// Add action listener for Alpha.
jbtnAlpha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Alpha was pressed.");
}
});

// Add action listener for Beta.
jbtnBeta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Beta was pressed.");
}
});

// Add the buttons to the content pane.
jfrm.add(jbtnAlpha);
jfrm.add(jbtnBeta);

// Create a text-based label.
jlab = new JLabel("Press a button.");

// Add the label to the content pane.
jfrm.add(jlab);

// Display the frame.

do u understand this>? Try it by yourself, this is just an elementary program in Swing now there are ways to solve this
 

Anbarasu

Right off the assembly line
Check this code out:
Code:
import java.io.*;

public class FileOps {
public static void main(String args[])
{
    File file = new File(args[0]);
    try
    {
        BufferedReader in = new BufferedReader(new FileReader(file));
        String s;
        s = in.readLine();
        while(s!=null)
        {
            System.out.println("Read " + s);
            s = in.readLine();
        }
        in.close();
    }
    catch(FileNotFoundException e1)
    {
        System.err.println("File Not Found" + file);
    }
    catch(IOException e2)
    {
        e2.printStackTrace();
    }
}
}
Now I'm getting this error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at FileOps.main(FileOps.java:13)
Java Result: 1
"
What's the solution? :confused:
try below program execution
java FileOps filename
 

utkarsh73

Journeyman
I see these two very different ways of creating a new thread in Java:

1) We 'extend' the 'Thread' class and override its 'run()' method in the subclass:

Code:
class NewThread extends Thread{
     public void run(){
          System.out.println("Child Thread!");
     }
}
class ThreadTest{
     public static void main(String args[]){
          NewThread nt = new NewThread();
          nt.start();
          System.out.println("Main Thread!");
      }
}

2) And this one 'implements' the 'Runnable' interface and I cannot understand what is actually happening in the first two lines of 'main' method. Please explain this.

Code:
class NewThread implements Runnable{
		public void run(){
			System.out.println("Child Thread!");
		}
}
public class ThreadTest {
	public static void main(String args[]){
		[I]Runnable threadJob = new NewThread();
		Thread nt = new Thread(threadJob);[/I]
		nt.start();
		System.out.println("Main thread");
	}

}

Now, which method is recommended from the above two?? And why??
 
OP
furious_gamer

furious_gamer

Excessive happiness
^^

# If you extends Thread class, after that you can’t extend any other class.
# If you implements Runnable, you can extend any other class, which is quite neat.

But on the other hand,

# If you extends Thread class, each of your thread creates unique object and associate with it.
# If you implements Runnable, it shares the same object to multiple threads.

So it is upto you to choose between the two.
 

utkarsh73

Journeyman
Ok, I get it.
But this part I don't understand.
^^
But on the other hand,

# If you extends Thread class, each of your thread creates unique object and associate with it.
# If you implements Runnable, it shares the same object to multiple threads.

what unique objects are u saying?? I have no idea what this means.
 

vickybat

I am the night...I am...
I see these two very different ways of creating a new thread in Java:

1) We 'extend' the 'Thread' class and override its 'run()' method in the subclass:

Code:
class NewThread extends Thread{
     public void run(){
          System.out.println("Child Thread!");
     }
}
class ThreadTest{
     public static void main(String args[]){
          NewThread nt = new NewThread();
          nt.start();
          System.out.println("Main Thread!");
      }
}

2) And this one 'implements' the 'Runnable' interface and I cannot understand what is actually happening in the first two lines of 'main' method. Please explain this.

Code:
class NewThread implements Runnable{
		public void run(){
			System.out.println("Child Thread!");
		}
}
public class ThreadTest {
	public static void main(String args[]){
		[I]Runnable threadJob = new NewThread();
		Thread nt = new Thread(threadJob);[/I]
		nt.start();
		System.out.println("Main thread");
	}

}

Now, which method is recommended from the above two?? And why??

Now read the following carefully mate:

1.
In the first code, NewThread is the subclass of Thread. Since you haven't described the thread class and its methods, i assume it contains the run method which
you're overriding. You can also declare the concrete run method in NewThread even if its not present in Thread class. In ThreadTest class, you declare the main method, create Newthread object with a reference nt and at the same time, invoking the NewThread() constructor ( default or self defined).

Since you have extended Thread class with NewThread, the reference, nt can be used to invoke methods from Thread class which i assume to be start(). It then finally prints "MainThread!".

2.

Second code brings multiple inheritance to the picture and this is where interface is needed. If you want the subclass to contain specific methods which you do not need to inherit from a parent class, you define interface which contains abstract methods unique to a particular functionality. You have to override these methods in the subclass that implements the interface.

In the code, the same NewThread subclass that extends Thread also implements Runnable. It actually overrides the run() method defined as abstract in Runnable interface and should not be present in Thread class. In the main method of Threadtest class, two objects are created with references instantiating the respective constructors. Reference thread job is passed as an argument to the Thread constructor ( why it's so hasn't been described in your code but it clears that the Thread constructor is not default but self defined).

Finally nt object reference invokes the start() method ( what this does hasn't been defined in the code) and then finally prints "Main Thread!".




If you don't understand any specific part, do let us know mate. And if possible, post the entire code.

You need to have a fair idea on constructors, polymorphism and multiple inheritance to understand interfaces. :)
 
OP
furious_gamer

furious_gamer

Excessive happiness
Ok, I get it.
But this part I don't understand.


what unique objects are u saying?? I have no idea what this means.

It explains clearly, that if you create new Thread, it means it is creating unique object for that. But for Runnable, this is not the case, It may share same instance for multiple threads.
 

vickybat

I am the night...I am...
Runnable has no constructor as its an interface. It can't be instantiated and thus has no unique instances.
 

utkarsh73

Journeyman
In the code, the same NewThread subclass that extends Thread also implements Runnable. It actually overrides the run() method defined as abstract in Runnable interface and should not be present in Thread class.

The two codes are completely separate from each other. The 'run()' method in the second code actually provides the definition of the abstract method 'run()' declared in the Runnable interface(Inbuilt interface java.lang.Runnable).

Reference thread job is passed as an argument to the Thread constructor ( why it's so hasn't been described in your code but it clears that the Thread constructor is not default but self defined).

threadJob reference is passed as an argument to the java.lang.Thread class's constructor of type "Thread(<Runnable target>)". Its predefined constructor.

Finally nt object reference invokes the start() method ( what this does hasn't been defined in the code) and then finally prints "Main Thread!".

Again, start() method is predefined in the Thread class(java.lang.Thread) which invokes the run() method as per its definition.

Runnable has no constructor as its an interface. It can't be instantiated and thus has no unique instances.

Yeah, Runnable interface does not have any constructor but in the statement "Runnable threadJob = new NewThread();" NewThread class's constructor is invoked not Runnable's.

I understand polymorphism and interfaces, I only wanted to understand the concept behind thread creation in the second code.

It explains clearly, that if you create new Thread, it means it is creating unique object for that. But for Runnable, this is not the case, It may share same instance for multiple threads.

Ok. Now I get it. By extending Thread, each new thread creates a different object of NewThread. But if we use Runnable, only one instance of NewThread is created and shared.
Thanks.
 
OP
furious_gamer

furious_gamer

Excessive happiness
1. You need to learn Java
2. You need to learn J2EE Architecture
3. Google "How to run JSP/Servlet in Windows/Linux machine"
 

vickybat

I am the night...I am...
Guys facing a bit of problem implementing listener. In my case, i'm invoking ActionListener and adding it to the list through a button reference variable and passing (this) as argument.
But the compiler throws an error in the listener segment. Posting the code below. Need a bit of help here guys.

Code:
 import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class GuiTest {

	JFrame frame;
	
    public static void main (String [] args){
    	GuiTest gui = new GuiTest() ;
    	try {
    	gui.go();
    	}catch (ClassCastException ex){
        	ex.printStackTrace();
        }
    }
    
    public void go (){
    	frame = new JFrame ();
    	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	
    	JButton button = new JButton ("Test Colour");
    	[B]button.addActionListener(this);[/B]
    	
    	DrawPanel panel = new DrawPanel();
    	
    	frame.getContentPane().add(BorderLayout.SOUTH,button);
    	frame.getContentPane().add(BorderLayout.CENTER,panel);
    	frame. setSize(300,300);
    	frame.setVisible(true);
    }
    
    public void actionPerformed(ActionEvent event){
    	frame.repaint();
    }
}

class DrawPanel extends JPanel{
	
	public void PaintComponent(Graphics g){
		
		g.fillRect (0,0,this.getWidth(),this.getHeight());
		int red = (int)(Math.random()*255);
		int blue= (int)(Math.random()*255);
		int green = (int)Math.random()*255;
		
		Color randomColor = new Color(red,green,blue);
		g.setColor(randomColor);
		g.fillOval(70, 70, 100, 100);
	}
}

Guys need a quick help on this. Though i find the syntax for registering the listener with a widget correct, the compiler throws an error.
I'm using eclipse juno. Need a quick help guys!!!!

Found the problem. I forget to implement the ActionListener interface in GuiTest class. Its working now. :)
 

bijay_ps

Broken In
Q1) why in this case when I am declaring a static variable as final also in Hello class then the static block is not getting processed?
class Hello{
static int a=10;
static{
System.out.println("SB in Hello class");
}
{
System.out.println("IB in Hello class");
}
}
class Test32{
public static void main(String[] args){
System.out.println(Hello.a);
}
}
And if I don't declare it as final, but only static then the static block is getting processed. Can anyone explain why is it happening??

Q2) what is the difference between following two programs? (Both will compile fine, but difference comes when you try to run it. Plz explain)
1)
class Test31{
Test31 obj1=new Test31();
public static void main(String[] args){
Test31 obj2=new Test31();
}
}
2)
class Test31{
static Test31 obj1=new Test31();
public static void main(String[] args){
Test31 obj2=new Test31();
}
}
 
I Used Core Servlets and JSP by Marty Hall and Larry Brown for AJAVA (for first Internal exam),
any good book for java rmi ?
 

vickybat

I am the night...I am...
Any good book for advanced java ?

Are you comfortable with all fundamentals? If not, then head first java period.
Read Bruce Eckell's "Thinking In Java" as a 2nd text book.

Complete reference (java) by Herbert Schildt as reference.

For advanced java, read "SCJP Sun Certified Programmer for Java 5" by Kathy Sierra and Bert Bates ( writers of head first java and head first series creators).
 

dashing.sujay

Moving
Staff member
Are you comfortable with all fundamentals? If not, then head first java period.
Read Bruce Eckell's "Thinking In Java" as a 2nd text book.

Complete reference (java) by Herbert Schildt as reference.

For advanced java, read "SCJP Sun Certified Programmer for Java 5" by Kathy Sierra and Bert Bates ( writers of head first java and head first series creators).

Actually it was for a friend and since I've no idea about java, so I asked. He mainly wants to cover EE topics namely servlet, and whatever they are. Anyways thanks for suggestions, I'll let him know.
 

vickybat

I am the night...I am...
Actually it was for a friend and since I've no idea about java, so I asked. He mainly wants to cover EE topics namely servlet, and whatever they are. Anyways thanks for suggestions, I'll let him know.

If he wants to know about servlets and jsp, then get the following:

Head First Labs from O'Reilly Media, Inc. :: Head First Servlets & JSP, Second Edition
 
Last edited:
Top Bottom