-

2011年8月3日星期三

Why does this java code not work?

-This code runs, however when the drop down menu options are selected they give no output, how can I make it give the desired output!

import java.awt.*;

import java.applet.*;

import java.awt.event.*;



public class DropDOWN extends Applet implements ActionListener {



Choice chosen;

int declaration;



public void init()

{



chosen = new Choice();

chosen.addItem("Tom");

chosen.addItem("Sam");

chosen.addItem("Jim");



add(chosen);



}



public void actionPerformed(ActionEvent e)

{

switch (chosen.getSelectedIndex())

{

case 0:

{

declaration = 1;

repaint();

}

break;



case 1:

{

declaration = 2;

repaint();

}

break;



case 2:

{

declaration = 3;

repaint();

}

break;



}

repaint();

}



public void paint(Graphics g)

{

if (declaration == 1){

g.drawString("My name is Tom", 380,380); //desired output

}



if (declaration == 2){

g.drawString("My name is Jim", 380, 380); //desired output

}



if (declaration == 3){

g.drawString("My name is Sam", 380,380); //desired output

}



}

}There are two things that come to mind. First, I think you want an ItemListener with the Choice object instead of trying to handle action events. Your approach might be workable, but I believe it was designed around using an ItemListener, looking at the documentation:



http://download.oracle.com/javase/1.4.2/鈥?/a>



Second, it sound silly, but make sure that your String objects are actually being drawn in a viewable portion of the screen (i.e. make sure your applet actually is big enough to display the text where you are putting it.

没有评论:

发表评论