tong1 22 Posting Whiz

The line 23 should be replaced by

if ((suit !='C') || (suit !='D') || (suit !='H') || (suit !='S'))

If your intention is logical OR.
Probably, your intention is logical AND as javaAddict indicated(?).

tong1 22 Posting Whiz

prem2,
Thank you for your quick response. Do you mean in my code, I can not place abstract method show() in it. If so I agree with you.
How do we say:
For the interface MouseListener there are 5 abstract methods declared:
void mouseClicked(MouseEvent e)
void mouseEntered(MouseEvent e)
void mouseExited(MouseEvent e)
void mousePressed(MouseEvent e)
void mouseReleased(MouseEvent e)
I wounder if the word "declared" used here is valid or not.
You may define an interface or abstract class where an abstract method void show() exists. If you are going to declare an abstract method void show() , for example, in an abstract class, you have to place the keyword abstract at first. Of course, in this case one may not have any instance from it. That's why in your/mine program, if an abstract method is declared, it cann't have object from it, i.e. it doen't work.

tong1 22 Posting Whiz

One thing you have to remember:
If you have defined some non-default constructors, the compiler will not implicitly provide a default constructor. If you need a default one you'd better define one. Otherwise it wouldn't pass compiling. For example, the following code leads to an error message for line 10:unsolved symbol

import java.io.*;

public class DefaultConstructor {

    public DefaultConstructor(String s) {
    	System.out.println("I am Not Default with no arguments. " + s );
    	}      

    public static void main(String[] args) {
        DefaultConstructor d = new DefaultConstructor();
    }
}
prem2 commented: Nice Example +1
tong1 22 Posting Whiz

Default constructor is the constructor with no arguments requested. It is called implicitly when creating an instance.

import java.io.*;

public class DefaultConstructor {
    
    public DefaultConstructor() {
    	System.out.println("I am Default with no arguments.");
    	}      

    public static void main(String[] args) {
        DefaultConstructor d = new DefaultConstructor();
    }
}

output:
I am Default with no arguments.

tong1 22 Posting Whiz

You may declare a method (in java we call function as method) as abstract which means no definition is given, e.g.

void show();

You may declare a method with empty body, which isn't an abstract method anymore.

void show(){};

but do nothing when calling it.
Or you may define a method with its body

public void show(){ //method Definition		
System.out.println("Sample Method ");	
}
tong1 22 Posting Whiz

It is impossible by Java applet class itself to store data at the client computer due to the restriction of Java security.
However, applet class may communicate with its own server. Any demon program runs in the server may receive any information sent by the applet class at the client's computer. In this way the demon program at the server may store the data at server since the demon program does not extend Applet. Also the demon program may pass any information from one client's computer to another client's computer at different location.

tong1 22 Posting Whiz

jemz, it works correctly. However, it works only for one line input. IOException would be more concrete/precise than Exception. I have modified your code so that client may type in several lines of strings. Type in "end" to finish typing.

import java.io.*;
class Writefile{		
  public static void main(String []args)throws IOException{
String name;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	BufferedWriter bw = new BufferedWriter(new FileWriter("write.txt"));  	
	System.out.println("Write into the file write.txt. To finish typing input \"end\".");
	while(true){ 			//loop continues unless typing in the "end" line
	name = br.readLine(); 	// read each line of strings you typed in
	if (name.equals("end")) // check the content of input. If it is "end" 
	break;   				// then jump out of the while loop
	bw.write(name + (char)10); // Add the ASCII code 10 for the character new line
	}
	bw.close(); 		
     }
 }
tong1 22 Posting Whiz

"Node" is just a class name you have given. It is not a reserved word.

tong1 22 Posting Whiz

No. It is the security rule: Applet cann't do any operation associated with files, such as create, open, read, delete, and alter in your computer.

tong1 22 Posting Whiz

Thank you , jon, for your quick response and correction. Should we call it "Same Type of Reference" or "Self-Type Reference" rather than self- referencing ?
A linked list contains several Node's objects, which are connected linearly (one by another) via the attribute "next". The "next" is a reference to its next Node' instance. The type of the "next" is also Node: itself Type. Therefore, they are of not only the same type but also itself type (the type as same as itself). The relationship for linked list is one to one.

class Node{
String value; //data member
Node next;    // self-Type reference, Node type reference
}

For the Linkedlist class we may call it as self-referencial class
http://www.cplusplus.com/forum/beginner/3311/

tong1 22 Posting Whiz
class Node {  // The definition of the class Node
String value; // data member
Node next;  // self referencing: referring to itself
}

Self-reference occurs in natural or formal languages when a sentence or formula refers to itself.
http://en.wikipedia.org/wiki/Self-reference

tong1 22 Posting Whiz

"Terminate" means cann't restart. One cann't use Applet method void start() to restart. One has to use init() to start a new run.

tong1 22 Posting Whiz

Due to Java security reason if a class extends Applet it cann't:
save any records on a file
open and read a file, and
alter a file.
However it may record scores in an array. As long as the program runs, one may access the data. If the program terminates all the scores recorded are lost.

tong1 22 Posting Whiz
import java.io.*;
import javax.swing.JOptionPane;
 public class PalindromeCouplet{   


 static boolean palindromeCouplet (String s)   {
 	StringBuffer s1 = new StringBuffer(s);
 return ((s.compareTo(new String(s1.reverse()))==0) ? true :false)  ;
 	}	

 public static void main(String[] args) {	
 	while(true){
    String str=JOptionPane.showInputDialog( null,  
	"Type in a string!\nPress Cancel to terminate the program",
	"Palindrome or Not?",
	JOptionPane.QUESTION_MESSAGE);    
    
	if (str == null) {
    	System.out.println("Bye for now!");
    	break;
    	} 

System.out.println("Palindrome? " + palindromeCouplet(str));
          }
      }   
}
tong1 22 Posting Whiz
double num = 1001.27124;
System.out.printf("%8.2f\n", num);
tong1 22 Posting Whiz
  1. Animation in Java
  2. Data Structure in Java
  3. JDBC
  4. Natworking programing in Java
  5. Statistics on words in text file by Java
tong1 22 Posting Whiz

I added a main method so that the program runs.

public static void main(String args[]){
   	Display dis=new Display();
   	dis.setVisible(true);
   	dis.setSize(500,150);
         dis.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
   }

I put an icon.png in the same folder.
both the program and the button works. The problem is that the icon will be located before the text rather than after the text.
So the question has become: How to make icon inserted after the text? I think, adams161 has quoted the answer:"....the icon is effectively inserted at the current position of the caret. ". So "before inserting, put the cursor after the text" is the solution.

The output is shown in the image: icon.gif

tong1 22 Posting Whiz

It works in my machine. For example, you put the Main.java in the folder "forum"
Via DOS window do the following cammands:

E:\forum>javac Main.java

E:\forum>java Main
Hello everyone on the forum DaniWeb
end

so that a text file "MyFile.txt" is created where the "Hello everyone on the forum DaniWeb " is stored.

tong1 22 Posting Whiz

Match in size (the same width and height) or Match in the ratio of width over height, or by other criteria?

tong1 22 Posting Whiz

code line 17 is not correct:
BufferedReader br = new BufferedReader(new BufferedWriter((System.in)));
The argument should be a Writer object.

I have modified the program by Java source code example for your reference.
http://www.javadb.com/write-to-file-using-bufferedwriter
The data you typed in will be stored in myFile.txt
In one line type in "end" only to terminate the program.

import java.io.*;
import java.util.Scanner;

public class Main {
    
    /**
     * Type in some data to a file using a BufferedWriter via DOS
     */
    public void writeToFile() {
        
        BufferedWriter bufferedWriter = null;
        BufferedReader br=null;
        Scanner in = new Scanner(System.in);       
        try {            
          //Construct the BufferedWriter object
            bufferedWriter = new BufferedWriter(new FileWriter("MyFile.txt"));
            while(true){
            	String s = in.nextLine();
            	if (s.equals("end"))
            	break;
            	bufferedWriter.write(s);
            }     
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            //Close the BufferedWriter
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.flush();
                    bufferedWriter.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    

    public static void main(String[] args) {
        new Main().writeToFile();
    }
}
tong1 22 Posting Whiz

Thank you for your "Why". I found I sent you a wrong version. In line code 11 if you put:

FileDialog fd = new FileDialog(null , "Open a document", FileDialog.LOAD);

you will have the error message: "the constructor file dialog is ambiguous"
However, the line of code 11:

FileDialog fd = new FileDialog(this, "Open a document", FileDialog.LOAD);

will pass compiling. Therefore, we should emphasize:
For the first argument "Frame parent" of the FileDialog constroctor one should use "this" indicating the parent Frame is the current object.

tong1 22 Posting Whiz

ezkonekgal ,thank you for your reply. I have checked and tested your code.
(1) You use JFileChooser which seems better than FileDialog which I use currently (because, as you reported, eclipse complains about the constructor I wrote).
(2) May I suggest you delete the "OK" button which is useless.
(3) Your code runs correctly. I have replaced your LayoutManager by FlowLayout so that components show up properly.
Attached please find the modified code. It runs correctly in my machine.

tong1 22 Posting Whiz

(1) May I ask: Why only press "return key" to do something? You may do something when receiving other input string.
(2) One class may implement the interface KeyListener to listening to the keyboard.
(3) I have written a simple program using KeyAdapter to monitor the keyboard for your reference.

/* The following program is listening to the kayboard.
 * DOS window output prints each character client pressed. 
 * When pressing return key, "Do Something" is printed.
 * */
  
import java.awt.event.*;
import javax.swing.*;

public class Key extends JFrame{
	
	public Key(){
	setSize(200,200);
	setVisible(true);	
	addKeyListener(new KeyAdapter(){  //anonymous class			
	public void keyPressed(KeyEvent e){ //call this method by pressing any key
	System.out.println(e.getKeyChar());	// print any printable character
	if ((int)e.getKeyChar()==10) // if pressing the "return key"
		System.out.println("Do Something");// then print "Do Something"
			} 
		});
	}
	
	public static void main(String args[]){
		Key k = new Key();
		k.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
}
tong1 22 Posting Whiz

You have incorrectly placed these lines of code outside of methods. This means that you are declaring attributes for your class. When you declare an array, you may initiate the String array with the corresponding values at the same time. However you wrote assignments' code during declaration, which is wrong.
String[] greeting = new String[4]; // declare an attribute of STring array. It's good.
greeting[0] = "Why, Hello there!"; // Wrong. Assignment shoud be written within a method.
greeting[1] = "Welcome.";//wrong
greeting[2] = "blah blah blah";// wrong
greeting[3] = "more useless crap";// wrong

You may write one line of code to complete the task.

String[] greeting = {"Why, Hello there!","Welcome.","blah blah blah","more useless crap"};
tong1 22 Posting Whiz

line 36 is not correct.
The correct code:

mb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// The value of the defined constant JFrame.EXIT_ON_CLOSE is 3

Thank you, NormR1 for your coments.

was not working

I will have a close look at tutorial on the issue of putClientProperty.

tong1 22 Posting Whiz

Your code shown above is correct. I have tested with a known file. The result is correct. AS long as the browsing files is concerned, as jon.kiparsky indicated, it is already available in Swing. For example, the class FileDialog is a candidate for this purpose. Since its constructor requests a parent frame , as written in Java API, the class you define has to inherit JFrame. I have modified your code as follows. You have to modify your main method accordingly. Attached please the code altered for your reference.

import java.io.*;
import java.awt.*;
import javax.swing.*;
class FileRead extends JFrame {
	static File name;  // it is created in constructor, then used in main
	static int count =0; // count the number of lines where characters are found
	static int count2=0; // count the nubmer of empty lines
	
public 	FileRead(){  // constructor for FileRead
	try{
      FileDialog fd = new FileDialog(this, "Open a document", FileDialog.LOAD); 
      fd.setDirectory(System.getProperty("user.dir")); // the window starts with current folder
      fd.setVisible(true);	
   	  name= new File(fd.getDirectory(), fd.getFile());
   	 }catch(Exception e){
   	 	System.err.println(e.getMessage());
   	 	}
   	setSize(400,400);
   	setVisible(true);
   	 }

Good luck.

tong1 22 Posting Whiz

The following code may help you:

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

public class MultiButtons extends JFrame implements ActionListener{
	JButton btn[] = new JButton[3];  // define and allocate for the array of 3 buttons
	String colorName[]={"RED","BLUE","GREEN"};  // the string on each button
	Color color[] = {Color.red, Color.blue, Color.green}; // Color array
    Container container;
    
    
	public MultiButtons(){
	JPanel p = new JPanel(); // create a sub container to have 3 buttons
	for (int i=0; i<btn.length;i++){ // create button and add ActionListener for each button.
		btn[i]= new JButton(colorName[i]);
		btn[i].addActionListener(this);
		btn[i].putClientProperty( "JButton.buttonType", "roundRect" ); // setup clientProperty, as JamesCherrill indicated.
		p.add(btn[i]);// put each button into the sub container
                  }
	container= getContentPane(); // The JFrame has the default layout manager: BorderLayout
	container.add(p, BorderLayout.NORTH); // the subcontainer holding 3 buttons is placed in the NORTH area
	container.setBackground(color[0]); // initial background is red in color
	setSize(400,200);
	setVisible(true);
	}	
	
	public void actionPerformed(ActionEvent e){ // the ActionListener monitoring 3 buttons.  
		for (int i=0; i<btn.length;i++) // using for loop to scan buttons
		if (btn[i]== e.getSource()){ // the button[i] is being pressed
		container.setBackground(color[i]); // re-set background color accordingly
		break;
		}
		}
	public static void main(String args[]){
	MultiButtons mb= new MultiButtons();
	mb.setDefaultCloseOperation(2);
	}
}

e.g.
In my machine, the line code:
btn.putClientProperty( "JButton.buttonType", "roundRect" );
was not working
I tried putClientProperty() in different way. It ended with no changes in buttons' apprearence at all.

tong1 22 Posting Whiz

If you want the icon only. The code will be:
b2=new JButton(back);
I have made a back.gif and modified your code:
e.g. insert
Container container=getContentPane();
.....
container.add(p1);
.....
Attached please find the code modified and the image file I made. Hope it helps.
I did not add (p2). I delete the lines for login since I have no definition for it. It works

tong1 22 Posting Whiz

Yes. In super class you may define a method to invoke the method of the subclass so that you may call the method with the super class reference.

class Superclass{
void display(){
System.out.println("Super");
}

void Sub2Display(){  // the extra method you define to call the method of its subclass
	Sub2 sub2= new Sub2();
	sub2.display();
	}
}

class Sub1 extends Superclass{
void display(){
System.out.println("sub class1");
}
}
class Sub2 extends Sub1{
void display(){
System.out.println("Sub class2");
}

void display2(){
System.out.println("Second method");
}
}


public class reference {
public static void main(String[] args){
Superclass ref=new Sub1();
ref.display();
ref.Sub2Display(); //invoke the method of the subclass with the super class reference
//((Sub2)ref).display();
}
}
tong1 22 Posting Whiz

The constructor as indicated in API:
JButton(String text, Icon icon)
Create a JButton with an Icon
Therefore your code line:
b2=new JButton("Back"); // b2 is a JButton with ImageIcon
should be replaced with
b2=new JButton("Back",back);// back if the instance of ImageIcon

tong1 22 Posting Whiz

The constructor as indicated in API:
JButton(String text, Icon icon)
创建一个带初始文本和图标的按钮。
There fore your code line:
b2=new JButton("Back"); // b2 is a JButton with ImageIcon?
should be replaced with
b2=new JButton("Back",back);// back if the instance of ImageIcon

tong1 22 Posting Whiz

I have a closer look at your code and tested. Both the image file and the oval may show up although they are overlapped (at the same location). Attached please find the files I have modified. Hope the observation report may help you.
I found:
(1) in class Bullet line 49: g.drawImage(picture, xpos, ypos, width, height, null);
The ImageObserver was null so that the image never shows up
(2) I have changed the access modifiers (private) for the attributes of class Bullet with friendly so that they could be accessed in the class myApplet.
(3) Therefore, the method paint() of the class myApplet (line 101-112) can be enhanced so that the work of display() of the class Bullet can be done without calling s.paint(graphicsBuffer); (line 110)

public void paint(Graphics g)
{
 Graphics2D g2 = (Graphics2D) g;
 graphicsBuffer.setColor(Color.white);
 graphicsBuffer.fillRect(0, 0, getWidth(), getHeight());
 graphicsBuffer.drawImage(s.picture, s.xpos, s.ypos, s.width, s.height, this);
 graphicsBuffer.setColor(Color.red);// I have added this line of code so that the oval shows up 
 graphicsBuffer.fill(s.c);
 g2.drawImage(imageBuffer, 0,0, getWidth(), getHeight(), this);
}

(4) The height of Applet can not be too short. Otherwise the locations of both bullet and the oval beyond the boundary.The size of the applet at least as indicated as follows

<html>
<applet code = "myApplet.class" width = 500 height = 500>
</applet>
</html>

(5) I also found that the Ellipse2D.Bouble c (very slender vertically) and the bullet at the same location so that the oval c overlapps with the bullet image.

tong1 22 Posting Whiz

The following code may help you where clicking mouse may relocate the label.

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

public class MovingLabel extends JFrame{
	int x,y; // define the location of a label
	JLabel label; // movable label
	Container container;
	MovingLabel(){
		super("Test a movable label");
		x=y=100;
		label= new JLabel("label relocated");
        Container container= getContentPane();
        setLayout(null); // Turn the layout manager off by setting the layout manager to null, as NormR1 indicated
		container.add(label); // place the label into the container
		label.setBounds(100,100,150,30);//position and sizing the label yourself
		container.addMouseListener(new MouseAdapter(){ // add MouseListener
			public void mouseClicked(MouseEvent e){
				x = e.getX();
				y = e.getY();
				label.setBounds(x,y,150,50); // relocating label. You may also resizing the label by altering the 3rd and 4th arguments
			}
		});
		setSize(900,500);
		setVisible(true);
	}	
	public static void main(String args[]){
		MovingLabel m = new MovingLabel();
		m.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
}
tong1 22 Posting Whiz

(1) The buttons show up in my machine (JDK 1.6). So it seems to be some problem with your machine. You may use Button of AWT rather than JButton of swing which is a lightweight component and does not show up among any AWT stuff. However, your case is OK. Since you put all the buttons into one separated container so that no conflict occurs, and even JButton shoud show up. If you simply put a JButton into a canvas (e.g. Applet) it wouldn't show up.
(2) You did not set up Layout manager correctly. I modified your code with BorderLayout. It works. (See attached file)
(3) Should we call the class ClickyLatinHelp as a driver class rather then "main class" ? One class may implement several interfaces. Since ActionListener and MouseListener both are interfaces the driver class may implement both.
I am noticed that :
Your code:

if (showeng = true) {
				showeng = false;
			}else {
				showeng = true;
			}
		}

is not correct. It should be if (showeng == true)... rather than if (showeng=true)

tong1 22 Posting Whiz

I hope the following code could help you.
I also made some comments to help you to understand.

import java.util.*;
public class RandomNumSelected{  
 
 static int random[] = new int [20];  // store 20 random numbers varying from 0 to 255;
 static int selected[] = new int[5];  // store the 5 distinct numbers you were looking for
 
	static int search(int a[], int n, int d){   //search the array a from subscript 0 until (n-1) for d. 
	for (int i=0;i<n;i++)  
	if (a[i]==d) // if the element is found
	return i;  // then return correspongding subscript
	return -1; // No thing happens in the for loop, implying d is not found, thus return -1. 
	}
	
    public static void main(String []args){
    Random rn = new Random();
    for (int i=0; i<20; i++)  //  assign 20 random values to the elements of array random 
    random[i]= rn.nextInt(256);
    
    int counter=0;
    selected[0]=random[0]; // the first random number is stored in selected array
    for (int i=1; i<5; i++)
     for(int j=1;i<random.length;j++)
    		if (search(random,i,random[j]) == -1){ // if the current selected array has no such value of random[j]
    		selected[i]=random[j]; // the random number random[j] is stored in the array selected
    		break;  //terminate the nested loop so that the next run for the outerloop starts
    		}    		
   	System.out.println("The 20 random numbers varying betwee 0 and 255 [0,255]: ");
   	for(int a:random)
   	System.out.print(a + " ");
   	System.out.println();  
   	System.out.println("The 5 distinct numbers selected from the above 20 numbers:"); 				
   for (int a:selected)
   System.out.print(a + " ");
   System.out.println();
    }
}

The output:
The 20 random numbers …

tong1 22 Posting Whiz

ankilosado, I have a question for you:
Why do you declare the class statItem has an attribute valor of type of Integer instead of the primitive type int? Integer is the wrapper class of int. Am I right?

tong1 22 Posting Whiz

Thank you, VinC, for sharing the "Covariant".
line 22 shows that g is a variable of type Grain.
line 25 shows that a variable of type Grain is capable to receive a value of type Wheat. Why?
Because Grain is super class of class Wheat. Wheat is a kind of Grain. An instance of subclass can also be an instance of superclass.
Class Student inherits class Person. Can you say: "Student David is not a person"? definitely Not. David, the instance of class Student is definitely a person.
Also see Java tips

tong1 22 Posting Whiz

her58, perter_budo is right. Since you said "I am able to select 5 random numbers,.." you must have some code. How do you select?

tong1 22 Posting Whiz

har58, you should make plan beforehand. For example,
(1) pre-store 20 existing random nmbers in an array.
(2) when executing program store the distinct 5 random numbers in another array one by one.

Should we start with the following code as clues:

public class RandomNumSelected{  
 
 int random[] = new int [20];  // store 20 random numbers varying from 0 to 255;
 int selected[] = new int[5];  // store the 5 distinct numbers you were looking for
 
	static int search(int a[], int n, int d){   //search the array a from subscript 0 until (n-1) for d. 
	for (int i=0;i<n;i++)  
	if (a[i]==d) // if the element is found
	return i;  // then return correspongding subscript
	return -1; // No thing happens in the for loop, implying d is not found, thus return -1. 
	}
	
    public static void main(String []args){
    	.....
    	 
      }
}

comments: The random numbers vary in a range. For example, from 0 to 255 [0,255]
You may generate by:
(1) the static method rand() in Math class.
(2) Create a instance of the class Random:
Random ran = new Random();
int n = ran.nextInt(256);

har58 commented: Thanks +1
tong1 22 Posting Whiz

You may replace the code in line 24 where the error occurs by the following two lines of code:

int va = this.statVect[i].getValor();
     va += otroVect[i].getValor();
     this.statVect[i].set(va);

Can you answer me Why we should modify in this way?

javaAddict commented: Allowing the OP to think +6
tong1 22 Posting Whiz

jon is right. You have to put the printLoop method into the main method. This means when interpreting the program (executing the main() method only) the printLoop() is called.
However, there are two ways to follow jon's instruction.
(1) you have to place a keyword static before the method printLoop(), so that the static method main may call the printLoop().
static void printLoop() {...}
static method can call static mathods only. Or
(2) the printLoop() remains as a member method. In this way you have to create an instance of the class "While" you have defiend. Then the instance will be used as a handle to call the printLoop().

public static void main(String args[]) {
While w= new While();
w.printLoop();
}
tong1 22 Posting Whiz

I have modified a program from a text book by H.M.Deitel, P.J. Deitel (Java How to Program). It helps you to have a solution.

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class Factorial extends JApplet implements ActionListener {
   JLabel numberLabel, resultLabel;
   JTextField numberField, resultField;

   // set up applet GUI
   public void init() {
      // obtain content pane and set its layout to FlowLayout
      Container container = getContentPane();
      container.setLayout( new FlowLayout() );

      // create numberLabel and attach it to content pane
      numberLabel = new JLabel( "Enter an positive integer(less than 21) and press Enter" );
      container.add( numberLabel );

      // create numberField and attach it to content pane
      numberField = new JTextField( 10 );
      container.add( numberField );

      // register this applet as numberField ActionListener
      numberField.addActionListener( this );

      // create resultLabel and attach it to content pane
      resultLabel = new JLabel( "Fibonacci value is" );
      container.add( resultLabel );

      // create numberField, make it uneditable
      // and attach it to content pane
      resultField = new JTextField( 15 );
      resultField.setEditable( false );
      container.add( resultField );

   } // end method init

   // obtain user input and call method fibonacci
   public void actionPerformed( ActionEvent event )
   {  
      long number, facValue;

      // obtain user input and convert to long
      number = Long.parseLong( numberField.getText() );

      showStatus( "Calculating ..." ); 

      // calculate fibonacci value for number user input
      facValue = fac( number );

      // indicate processing complete and display result
      showStatus( "Done." );   
      resultField.setText( Long.toString( facValue ) );

   } // end method actionPerformed
  
   // recursive declaration of method fibonacci …
tong1 22 Posting Whiz

You may do in the following way. Assume the word you are going to random has n characters. In the original character order of the word, each time you select one as the first letter and print it. And then print the rest of the letter (with their order) so that you may have n random words.

For example the word july has 4 characters.

we will have:
july
ujly
ljuy
yjul

A new random word would be printed in the following way.
Each run of the outer loop will do:
(1) select a letter from word in their original order in the word. Then print this letter as the first letter of each new random word.
(2) Then use a nested loop to print the rest letters. That is, print all the characters whose indexex are not the index of the selected letter.
In this way a newly created random word is printed.
The outloop runs n times so that n random words are printed


Hope you understand my idea.

tong1 22 Posting Whiz

Do you mean you try to get another windonw ? Did you use javaw on DOS? If so there would be no console available so that no printed output on screen. But how do you know the System.console() returns null?
The standard method to use console() method (starting from 1.6)is shown as follows:

import java.io.Console;           
public class TestConsole {            
     public static void main(String[] args) {
     	Console console = System.console(); // obtain an instance of Console
     	if (console != null) {              // make sure if you may use the console: if console is available                 
     	String user = new String(console.readLine("Enter username:"));      // read a line of characters                  
     	String pwd = new String(console.readPassword("Enter passowrd:"));   // read a password whti nothing printed on screen                  
     	console.printf("Username is: " + user + "\n");      // print username
     	console.printf("Password is: " + pwd + "\n");   // print passward
     	} else {                  
     	System.out.println("Console is unavailable.");  // have no right to use console              
     	}               
 	}           
}
tong1 22 Posting Whiz

JButtons, JRadioButtons, JLabels, and so on come from lightweight package swing hence not are shown (overlapped) when meeting (conflicting with) heavyweight components, e.g. buttons, labels,... from java.awt. The following class extends Frame (heavyweight) rather than JFrame. Therefore, the JRadioButtons must be placed in one subframe: BorderLayout.NORTH. If they were placed directedly in the Frame, they would all disappear.
The following code also works.

import javax.swing.*;  // lightweight package
import java.awt.*;  // heavyweight package
import java.awt.event.*;
// Frame from java.awt. its heavy
class simo2 extends Frame implements ActionListener{
	private JRadioButton red;  // lightweight component
	private JRadioButton yellow; // lightweight component
	private JRadioButton blue; // lightweight component
	private JRadioButton green; // lightweight component
    private JRadioButton magenta;  // lightweight component


public simo2(){
	setLayout(new BorderLayout());
	setVisible(true);
	setSize(400,250);
	JPanel p = new JPanel();
	red=new JRadioButton(" red");
	yellow=new JRadioButton(" yellow");
	blue=new JRadioButton(" blue");
	green=new JRadioButton(" green");
	magenta=new JRadioButton(" magenta");
	ButtonGroup group=new ButtonGroup();
	group.add(red);
	group.add(yellow);
	group.add(blue);
	group.add(green);
	group.add(magenta);
	red.addActionListener(this);
	yellow.addActionListener(this);
	blue.addActionListener(this);
	green.addActionListener(this);
	magenta.addActionListener(this);
	p.add(red);   // place the light component in a saparate container.
	p.add(yellow);
	p.add(blue);
	p.add(green);
	p.add(magenta);
	add(p,BorderLayout.NORTH);	
}
public void actionPerformed(ActionEvent e){
	if(e.getSource()== red){
		setBackground(Color.red);
	}
	if(e.getSource()== yellow){
		setBackground(Color.yellow);
	}
	if(e.getSource()== blue){
		setBackground(Color.blue);
	}
	if(e.getSource()== green){
		setBackground(Color.green);
	}
	if(e.getSource()== magenta){
		setBackground(Color.magenta);
	}	
	}
	
}
public class simo0 {
	public static void main(String[] args){
		simo2 s=new simo2();
		s.addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent e){
				System.exit(0);
			}
			});
	}			
}
tong1 22 Posting Whiz

It works with one Thread. You may add a button (not JButton) so that when client clicks, one more ball will be added. One should be noticed that the JButton, which is lightweight component, will not be shown on the heavyweight stuff( e.g. awt Graphics). That's why only Button(the heavyweight component) works. You may also setLayout(null), so that the button may use setBounds(int, int, int, int) method to have its own location and size. Then you may start a coding for a game..... Good luck.

/*
Only one Thread is used. You may have more balls up to 10.
*/

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


public class Balls extends JFrame implements Runnable {
	
	static Ball balls[]= new Ball[10];
    static int count=0;
    Thread timer = null;
    
    class Ball {  // inner class 
    	int x,y;  // each ball has its own location indicated by x,y
    	boolean flag;  // each ball has its own flag to direct if y++ or y--
    	
    	public Ball(int x){
    		flag=true;
    		y=0;
    		this.x=x;
    	}
    	
    	public void drawball(Graphics g){ // draw itself
    		g.setColor(Color.red);
    		g.fillOval(x,y,10,10);
    		if (flag)
    		y++;
    		else
    		y--;
    		if (y >= getHeight())  // inner class may call any method of its outer class
    		flag = false;
    		else
    		if (y <=0)
    		flag = true;
    	}
    } // end of the inner class
    
    public void start(){
    	if (timer == null){
    		timer = new Thread(this);
    		timer.start();
    	}
    }
    public void run(){
    	while(timer !=null){
    		try{
    			Thread.sleep(10);
    		}catch(InterruptedException e){}
    		repaint();
    	}
    }
    
    public void paint(Graphics g){
    	g.setColor(Color.white);
    	g.fillRect(0,0,800,600);
    	for (int i=0; i<count; i++){ // …
tong1 22 Posting Whiz

SOS, I have learned a lot from your poster. The answers are highly appreciated.

tong1 22 Posting Whiz

I guess you did not follow NormR1's instruction precisely. I have tested your program. It works.

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

class simo2 extends JFrame implements ActionListener{
	private JRadioButton red;
	private JRadioButton yellow;
	private JRadioButton blue;
	private JRadioButton green;
    private JRadioButton magenta;
    Container container;

public simo2()
{
	super("Radio Button Test");
	container = getContentPane();
	container.setLayout(new FlowLayout());
	setVisible(true);
	setSize(400,250);
	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
	red=new JRadioButton(" red");
	yellow=new JRadioButton(" yellow");
	blue=new JRadioButton(" blue");
	green=new JRadioButton(" green");
	magenta=new JRadioButton(" magenta");
	ButtonGroup group=new ButtonGroup();
	group.add(red);
	group.add(yellow);
	group.add(blue);
	group.add(green);
	group.add(magenta);
	red.addActionListener(this);
	yellow.addActionListener(this);
	blue.addActionListener(this);
	green.addActionListener(this);
	magenta.addActionListener(this);
	container.add(red);
	container.add(yellow);
	container.add(blue);
	container.add(green);
	container.add(magenta);
}
public void actionPerformed(ActionEvent e)
{
	if(e.getSource()== red)
	{
		container.setBackground(Color.red);
	}
	if(e.getSource()== yellow)
	{
		container.setBackground(Color.yellow);
	}
	if(e.getSource()== blue)
	{
		container.setBackground(Color.blue);
	}
	if(e.getSource()== green)
	{
		container.setBackground(Color.green);
	}
	if(e.getSource()== magenta)
	{
		container.setBackground(Color.magenta);
	}
	
	}
	
}
public class simo1 {
	public static void main(String[] args)
	{
		simo2 s=new simo2();
				}

}
tong1 22 Posting Whiz

You may try to use one Thread only in your program.
Your class drawpanel will have attributes x,y only. That is, you define each ball as an instance with their own attributes x and y.

tong1 22 Posting Whiz

Thank you, NormR1. I have tested your code. Yes, it works when the BorderLayout is used swhere two balls are moving in different "subframes":BorderLayout.EAST and BorderLayout.WEST. I have tried FlowLayout, resulted int an overlap of two components. In a game program, two objects (balls) should be moving within one frame rather than two: EAST and WEST. Therefore, we have to figure out the right Layout Manager. Meanwhile programming in J2ME shows different balls are able to move within a common frame. Are they associated with one thread or different threads? We have to make further investigation.