Carrie
March 24th, 2000, 01:19 AM
I'm a beginner in Java programming, and have had difficulty converting a program from AWT to swing. I'm sure I've made some horrendous errors, here's the original.
<javacode>
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class Voca extends Frame {
// global constants
public static final int ERROR = 1;
public static final int MAX_SCORE = 60;
public static final int MAX_TEXT = 30;
public static final String DEFAULT = "default.voc";
// class properties
private Random rndRandom = new Random();
private Vector vctQuestions = new Vector();
private MenuBar mbMenu = new MenuBar();
private Label lblScore, lblResult, englishTextLabel, frenchTextLabel;
private TextField txtEnglish, txtFrench;
private Button cmdExit, cmdReset, cmdSubmit;
private String strQst, strAns;
private int intQuestionNo, intQuestionsRight;
// Voca constructor
public Voca(String strFilename) {
super( "Voca program" );
readFile(strFilename);
lblScore = new Label("Score: 0.0%");
lblScore.setFont(new Font("Helvetica", Font.PLAIN, 14));
(lblScore).setForeground(Color.white);
englishTextLabel = new Label ("English:");
englishTextLabel.setFont(new Font("Helvetica", Font.BOLD, 14));
(englishTextLabel).setForeground(Color.green);
frenchTextLabel = new Label ("French: ");
frenchTextLabel.setFont(new Font("Helvetica", Font.BOLD, 14));
(frenchTextLabel).setForeground(Color.green);
lblResult = new Label("Welcome to Voca, try to get " + MAX_SCORE + "%");
(lblResult).setForeground(Color.white);
lblResult.setFont(new Font("Helvetica", Font.PLAIN, 12));
txtEnglish = new TextField(MAX_TEXT);
(txtEnglish).setBackground(Color.black);
(txtEnglish).setForeground(Color.Green);
txtFrench = new TextField(MAX_TEXT);
(txtFrench).setBackground(Color.black);
(txtFrench).setForeground(Color.green);
cmdExit = new Button("Exit");
(cmdExit).setBackground(Color.black);
(cmdExit).setForeground(Color.white);
cmdReset = new Button("Reset results");
(cmdReset).setBackground(Color.black);
(cmdReset).setForeground(Color.white);
cmdSubmit = new Button("Submit");
(cmdSubmit).setBackground(Color.black);
(cmdSubmit).setForeground(Color.white);
txtEnglish.setEditable(false);
intQuestionsRight = 0;
}
// initialise frame
public void showFrame() {
MyListener myListener = new MyListener();
setBackground( Color.black);
setLayout(new GridLayout(0,1));
// set panels
Panel pn1, pn2, pn3, pn4, pn5;
pn1 = new Panel(new FlowLayout( FlowLayout.RIGHT ));
pn2 = new Panel(new FlowLayout( FlowLayout.LEFT ));
pn3 = new Panel(new FlowLayout( FlowLayout.LEFT ));
pn4 = new Panel(new FlowLayout( FlowLayout.LEFT ));
pn5 = new Panel(new FlowLayout( FlowLayout.RIGHT ));
// add panels
pn1.add( lblScore );
pn2.add( englishTextLabel );
pn2.add( txtEnglish );
pn3.add( frenchTextLabel );
pn3.add( txtFrench );
pn4.add( lblResult );
pn3.add( cmdSubmit );
pn5.add( cmdReset );
pn5.add( cmdExit );
add( pn1 );
add( pn2 );
add( pn3 );
add( pn4 );
add( pn5 );
// set menubar
MenuItem miSubmit = new MenuItem( "Submit" );
MenuItem miReset = new MenuItem( "Reset results" );
MenuItem miExit = new MenuItem( "Exit" );
Menu mMenu = new Menu( "File" );
// add menu to menubar
mbMenu.add( mMenu );
mMenu.add( miSubmit );
mMenu.add( miReset );
mMenu.add( miExit );
setMenuBar( mbMenu );
// set action listener
miSubmit.addActionListener( myListener );
miReset.addActionListener( myListener );
miExit.addActionListener( myListener );
cmdSubmit.addActionListener( myListener );
cmdReset.addActionListener( myListener );
cmdExit.addActionListener( myListener );
getQA();
txtEnglish.setText("How do you say '" + strQst + "' in French?");
pack();
setVisible(true);
addWindowListener(myListener);
}
// check score against MAX_SCORE
public void checkScore(double dblScore) {
if (dblScore >= MAX_SCORE) {
cmdSubmit.setEnabled(false);
} else {
getQA();
txtEnglish.setText("How do you say '" + strQst + "' in French?");
txtFrench.setText("");
}
}
// check and get question and answer
public void getQA() {
Question tmpQuestion;
intQuestionNo = rndRandom.nextInt( vctQuestions.size() );
tmpQuestion = (Question)vctQuestions.elementAt( intQuestionNo );
while (tmpQuestion.getAsk()) {
tmpQuestion = null;
intQuestionNo = rndRandom.nextInt( vctQuestions.size() );
tmpQuestion = (Question)vctQuestions.elementAt( intQuestionNo );
}
strQst = tmpQuestion.getQuestion();
strAns = tmpQuestion.getAnswer();
}
// set the question to never to be chosen in the current session
public void setQuestionAsk() {
Question tmpQuestion;
tmpQuestion = (Question)vctQuestions.elementAt( intQuestionNo );
tmpQuestion.setAsk(true);
vctQuestions.removeElementAt( intQuestionNo );
vctQuestions.insertElementAt( tmpQuestion, intQuestionNo );
}
// error dialog box
public void showErrorDialog() {
MyListener myListener = new MyListener();
Button cmdOK = new Button( "OK" );
Dialog dlgError = new Dialog(new Frame(), "Error!", true);
dlgError.setLayout( new FlowLayout( FlowLayout.LEFT ));
dlgError.add( new Label( "The file specified is missing or invalid" ));
dlgError.add( cmdOK );
dlgError.pack();
cmdOK.addActionListener( myListener );
dlgError.addWindowListener(myListener);
dlgError.setVisible( true );
}
// tokenize line and enter question and answer into linked list
public void tokenQA( String strLine ) {
StringTokenizer stzFile = null;
Question qstQA = null;
String strTmpQ = "";
String strTmpA = "";
// try-catch to spot anomalies in file
try {
stzFile = new StringTokenizer(strLine, ".");
strTmpQ = stzFile.nextToken();
strTmpA = stzFile.nextToken();
qstQA = new Question(strTmpQ, strTmpA);
vctQuestions.addElement(qstQA);
} catch (NoSuchElementException nSEe) {
// print Error and Dialog box
System.out.println( "The file specified is missing or invalid" );
showErrorDialog();
System.exit(0);
}
}
// reads the file
public void readFile( String strFilename ) {
InputStream isFile = null;
String strFile = "";
int intTemp = 0;
// open FileInputStream to read file
try {
isFile = new FileInputStream( strFilename );
} catch ( FileNotFoundException fNFE ) {
System.out.println( "The file specified is missing or invalid" );
showErrorDialog();
System.exit(0);
}
// reads the file and tokenize each line
do {
try {
intTemp = isFile.read();
} catch ( IOException ioE ) {
System.out.println( "The file specified is missing or invalid" );
showErrorDialog();
System.exit(0);
}
if (intTemp == 10) {
tokenQA( strFile );
strFile = "";
} else {
strFile += strFile.valueOf( (char)intTemp );
}
} while ( intTemp != -1 );
tokenQA( strFile );
// closes FileInputStream
try {
isFile.close();
} catch ( IOException ioE ) {
System.out.println( ioE.getMessage() );
System.exit(0);
}
}
// update the score
public void updateScore() {
double dblScore;
dblScore = (int)((double)intQuestionsRight / (double)vctQuestions.size() * 100);
lblScore.setText("Score: " + dblScore + "%");
checkScore(dblScore);
}
// Listener class for 'Voca'
class MyListener extends WindowAdapter implements ActionListener {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
// actions
public void actionPerformed(ActionEvent e) {
String source = "";
if (e.getSource() instanceof Button) {
source = ((Button)e.getSource()).getLabel();
} else if (e.getSource() instanceof MenuItem) {
source = ((MenuItem)e.getSource()).getLabel();
}// end of if
if (source.equals("Exit") | source.equals("OK")) {
// 'Exit' clicked
System.exit(0);
} else if (source.equals("Submit")) {
// 'Submit' clicked
if (txtFrench.getText().equals(strAns)) {
// correct answer given
lblResult.setText("Good!");
setQuestionAsk();
intQuestionsRight++;
updateScore();
} else {
// wrong answer given
lblResult.setText("Wrong! '" + strQst + "' -> '" + strAns +"' ");
getQA();
txtEnglish.setText("How do you say '" + strQst + "' in French?");
txtFrench.setText("");
}// end of if
} else if (source.equals("Reset results")) {
// 'Reset results' clicked
Question tmpQuestion;
lblResult.setText("Welcome to Voca, try to get " + MAX_SCORE + "%");
lblScore.setText("Score: 0.0%");
cmdSubmit.setEnabled(true);
intQuestionsRight = 0;
// reset questions availability
for (int x = 0; x < vctQuestions.size(); x++ ) {
tmpQuestion = (Question)vctQuestions.elementAt(x);
tmpQuestion.setAsk(false);
vctQuestions.removeElementAt(x);
vctQuestions.insertElementAt(tmpQuestion, x);
}// end of for
getQA();
txtEnglish.setText("How do you say '" + strQst + "' in French?");
txtFrench.setText("");
}// end of if
}// end of actionPerformed method
}//end of MyListener inner class
// main subroutine for 'Voca'
public static void main(String[] args) {
Voca myFrame = null;
try {
myFrame = new Voca(args[0]);
} catch (ArrayIndexOutOfBoundsException aIOBe) {
myFrame = new Voca(DEFAULT);
}
myFrame.showFrame();
}//end of main method
}//end of Voca class
// Question class to store one question
class Question {
private String strQuestion;
private String strAnswer;
private boolean blnAsk;
// Question class constructor
Question(String strTmpQuestion, String strTmpAnswer) {
strQuestion = strTmpQuestion;
strAnswer = strTmpAnswer;
blnAsk = false;
}
// returns question
public String getQuestion() {
return strQuestion;
}
// returns answer
public String getAnswer() {
return strAnswer;
}
// returns whether question can be asked again
public boolean getAsk() {
return blnAsk;
}
// set whether question can be asked again
public void setAsk(boolean blnTmpAsk) {
blnAsk = blnTmpAsk;
}
}// end of Question class
</javacode>
And here's what I converted it to (which I'm sure is horrendously wrong in some way). It *will* compile, but I get the following errors:
Exception in thread "main" java.land.IllegalArgumentException: illegal component composition
at java.awt.Container.addImpl(Container.java:303)
at java.awt.Container.add(Container.java:234)
at Voca.showJFrame(Voca.java:98)
at Voca.main(Voca.java:33)
Here's my converted code so far:
<javacode>
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
public class Voca extends JFrame {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel{
UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) { }
new SwingApplication();
}
// global constants
public static final int ERROR = 1;
public static final int MAX_SCORE = 60;
public static final int MAX_TEXT = 30;
public static final String DEFAULT = "default.voc";
// class properties
private Random rndRandom = new Random();
private Vector vctQuestions = new Vector();
private JMenuBar mbMenu = new JMenuBar();
private JLabel lblScore, lblResult, englishTextLabel, frenchTextLabel;
private JTextField txtEnglish, txtFrench;
private JButton cmdExit, cmdReset, cmdSubmit;
private String strQst, strAns;
private int intQuestionNo, intQuestionsRight;
// Voca constructor
public Voca(String strFilename) {
super("Voca program");
readFile(strFilename);
lblScore = new JLabel("Score: 0.0%");
lblScore.setFont(new Font("Helvetica", Font.PLAIN, 14));
(lblScore).setForeground(Color.white);
englishTextLabel = new JLabel ("English:");
englishTextLabel.setFont(new Font("Helvetica", Font.BOLD, 14));
(englishTextLabel).setForeground(Color.green);
frenchTextLabel = new JLabel ("French: ");
frenchTextLabel.setFont(new Font("Helvetica", Font.BOLD, 14));
(frenchTextLabel).setForeground(Color.green);
lblResult = new JLabel("Welcome to Voca, try to get " + MAX_SCORE + "%");
(lblResult).setForeground(Color.white);
lblResult.setFont(new Font("Helvetica", Font.PLAIN, 14));
txtEnglish = new JTextField(MAX_TEXT);
(txtEnglish).setBackground(Color.black);
(txtEnglish).setForeground(Color.green);
txtFrench = new JTextField(MAX_TEXT);
(txtFrench).setBackground(Color.black);
(txtFrench).setForeground(Color.green);
cmdExit = new JButton("Exit");
(cmdExit).setBackground(Color.black);
(cmdExit).setForeground(Color.white);
cmdReset = new JButton("Reset results");
(cmdReset).setBackground(Color.black);
(cmdReset).setForeground(Color.white);
cmdSubmit = new JButton("Submit");
(cmdSubmit).setBackground(Color.black);
(cmdSubmit).setForeground(Color.white);
txtEnglish.setEditable(false);
intQuestionsRight = 0;
}
// initialise frame
public void showJFrame() {
MyListener myListener = new MyListener();
Container pane = getContentPane();
setBackground( Color.black);
pane.setLayout(new GridLayout(0,1));
// set panels
JPanel pn1, pn2, pn3, pn4, pn5;
pn1 = new JPanel();
pane.add(pn1, FlowLayout.RIGHT);
pn2 = new JPanel();
pane.add(pn2, FlowLayout.LEFT);
pn3 = new JPanel();
pane.add(pn3, FlowLayout.LEFT);
pn4 = new JPanel();
pane.add(pn4, FlowLayout.LEFT);
pn5 = new JPanel();
pane.add(pn5, FlowLayout.RIGHT);
// add panels
pn1.add( lblScore );
pn2.add( englishTextLabel );
pn2.add( txtEnglish );
pn3.add( frenchTextLabel );
pn3.add( txtFrench );
pn4.add( lblResult );
pn3.add( cmdSubmit );
pn5.add( cmdReset );
pn5.add( cmdExit );
// set menubar
JMenuItem miSubmit = new JMenuItem( "Submit" );
JMenuItem miReset = new JMenuItem( "Reset results" );
JMenuItem miExit = new JMenuItem( "Exit" );
JMenu mMenu = new JMenu( "File" );
// add menu to menubar
mbMenu.add( mMenu );
mMenu.add( miSubmit );
mMenu.add( miReset );
mMenu.add( miExit );
setJMenuBar( mbMenu );
// set action listener
miSubmit.addActionListener( myListener );
miReset.addActionListener( myListener );
miExit.addActionListener( myListener );
cmdSubmit.addActionListener( myListener );
cmdReset.addActionListener( myListener );
cmdExit.addActionListener( myListener );
getQA();
txtEnglish.setText("How do you say '" + strQst + "' in French?");
pack();
setVisible(true);
addWindowListener(myListener);
}
// check score against MAX_SCORE
public void checkScore(double dblScore) {
if (dblScore >= MAX_SCORE) {
cmdSubmit.setEnabled(false);
} else {
getQA();
txtEnglish.setText("How do you say '" + strQst + "' in French?");
txtFrench.setText("");
}
}
// check and get question and answer
public void getQA() {
Question tmpQuestion;
intQuestionNo = rndRandom.nextInt( vctQuestions.size() );
tmpQuestion = (Question)vctQuestions.elementAt( intQuestionNo );
while (tmpQuestion.getAsk()) {
tmpQuestion = null;
intQuestionNo = rndRandom.nextInt( vctQuestions.size() );
tmpQuestion = (Question)vctQuestions.elementAt( intQuestionNo );
}
strQst = tmpQuestion.getQuestion();
strAns = tmpQuestion.getAnswer();
}
// set the question to never to be chosen in the current session
public void setQuestionAsk() {
Question tmpQuestion;
tmpQuestion = (Question)vctQuestions.elementAt( intQuestionNo );
tmpQuestion.setAsk(true);
vctQuestions.removeElementAt( intQuestionNo );
vctQuestions.insertElementAt( tmpQuestion, intQuestionNo );
}
// error dialog box
public void showErrorDialog() {
MyListener myListener = new MyListener();
JButton cmdOK = new JButton( "OK" );
JDialog dlgError = new JDialog(new JFrame(), "Error!", true);
dlgError.setLayout( new FlowLayout( FlowLayout.LEFT ));
dlgError.add( new JLabel( "The file specified is missing or invalid" ));
dlgError.add( cmdOK );
dlgError.pack();
cmdOK.addActionListener( myListener );
dlgError.addWindowListener(myListener);
dlgError.setVisible( true );
}
// tokenize line and enter question and answer into linked list
public void tokenQA( String strLine ) {
StringTokenizer stzFile = null;
Question qstQA = null;
String strTmpQ = "";
String strTmpA = "";
// try-catch to spot anomalies in file
try {
stzFile = new StringTokenizer(strLine, ".");
strTmpQ = stzFile.nextToken();
strTmpA = stzFile.nextToken();
qstQA = new Question(strTmpQ, strTmpA);
vctQuestions.addElement(qstQA);
} catch (NoSuchElementException nSEe) {
// print Error and Dialog box
System.out.println( "The file specified is missing or invalid" );
showErrorDialog();
System.exit(0);
}
}
// reads the file
public void readFile( String strFilename ) {
InputStream isFile = null;
String strFile = "";
int intTemp = 0;
// open FileInputStream to read file
try {
isFile = new FileInputStream( strFilename );
} catch ( FileNotFoundException fNFE ) {
System.out.println( "The file specified is missing or invalid" );
showErrorDialog();
System.exit(0);
}
// reads the file and tokenize each line
do {
try {
intTemp = isFile.read();
} catch ( IOException ioE ) {
System.out.println( "The file specified is missing or invalid" );
showErrorDialog();
System.exit(0);
}
if (intTemp == 10) {
tokenQA( strFile );
strFile = "";
} else {
strFile += strFile.valueOf( (char)intTemp );
}
} while ( intTemp != -1 );
tokenQA( strFile );
// closes FileInputStream
try {
isFile.close();
} catch ( IOException ioE ) {
System.out.println( ioE.getMessage() );
System.exit(0);
}
}
// update the score
public void updateScore() {
double dblScore;
dblScore = (int)((double)intQuestionsRight / (double)vctQuestions.size() * 100);
lblScore.setText("Score: " + dblScore + "%");
checkScore(dblScore);
}
// Listener class for 'Voca'
class MyListener extends WindowAdapter implements ActionListener {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
// actions
public void actionPerformed(ActionEvent e) {
String source = "";
if (e.getSource() instanceof JButton) {
source = ((JButton)e.getSource()).getText();
} else if (e.getSource() instanceof JMenuItem) {
source = ((JMenuItem)e.getSource()).getText();
}// end of if
if (source.equals("Exit") | source.equals("OK")) {
// 'Exit' clicked
System.exit(0);
} else if (source.equals("Submit")) {
// 'Submit' clicked
if (txtFrench.getText().equals(strAns)) {
// correct answer given
lblResult.setText("Good!");
setQuestionAsk();
intQuestionsRight++;
updateScore();
} else {
// wrong answer given
lblResult.setText("Wrong! '" + strQst + "' -> '" + strAns +"' ");
getQA();
txtEnglish.setText("How do you say '" + strQst + "' in French?");
txtFrench.setText("");
}// end of if
} else if (source.equals("Reset results")) {
// 'Reset results' clicked
Question tmpQuestion;
lblResult.setText("Welcome to Voca, try to get " + MAX_SCORE + "%");
lblScore.setText("Score: 0.0%");
cmdSubmit.setEnabled(true);
intQuestionsRight = 0;
// reset questions availability
for (int x = 0; x < vctQuestions.size(); x++ ) {
tmpQuestion = (Question)vctQuestions.elementAt(x);
tmpQuestion.setAsk(false);
vctQuestions.removeElementAt(x);
vctQuestions.insertElementAt(tmpQuestion, x);
}// end of for
getQA();
txtEnglish.setText("How do you say '" + strQst + "' in French?");
txtFrench.setText("");
}// end of if
}// end of actionPerformed method
}//end of MyListener inner class
}//end of Voca class
// Question class to store one question
class Question {
private String strQuestion;
private String strAnswer;
private boolean blnAsk;
// Question class constructor
Question(String strTmpQuestion, String strTmpAnswer) {
strQuestion = strTmpQuestion;
strAnswer = strTmpAnswer;
blnAsk = false;
}
// returns question
public String getQuestion() {
return strQuestion;
}
// returns answer
public String getAnswer() {
return strAnswer;
}
// returns whether question can be asked again
public boolean getAsk() {
return blnAsk;
}
// set whether question can be asked again
public void setAsk(boolean blnTmpAsk) {
blnAsk = blnTmpAsk;
}
}// end of Question class
</javacode>
Where am I going wrong? I'm pulling my hair out here :-). If someone could please offer me some assistance, I would be most grateful.
If anyone could also tell me how exactly to change the look and feel of the app, that would be fantastic.
Someone please help (struggling college student is going mad!)
Carrie
<javacode>
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class Voca extends Frame {
// global constants
public static final int ERROR = 1;
public static final int MAX_SCORE = 60;
public static final int MAX_TEXT = 30;
public static final String DEFAULT = "default.voc";
// class properties
private Random rndRandom = new Random();
private Vector vctQuestions = new Vector();
private MenuBar mbMenu = new MenuBar();
private Label lblScore, lblResult, englishTextLabel, frenchTextLabel;
private TextField txtEnglish, txtFrench;
private Button cmdExit, cmdReset, cmdSubmit;
private String strQst, strAns;
private int intQuestionNo, intQuestionsRight;
// Voca constructor
public Voca(String strFilename) {
super( "Voca program" );
readFile(strFilename);
lblScore = new Label("Score: 0.0%");
lblScore.setFont(new Font("Helvetica", Font.PLAIN, 14));
(lblScore).setForeground(Color.white);
englishTextLabel = new Label ("English:");
englishTextLabel.setFont(new Font("Helvetica", Font.BOLD, 14));
(englishTextLabel).setForeground(Color.green);
frenchTextLabel = new Label ("French: ");
frenchTextLabel.setFont(new Font("Helvetica", Font.BOLD, 14));
(frenchTextLabel).setForeground(Color.green);
lblResult = new Label("Welcome to Voca, try to get " + MAX_SCORE + "%");
(lblResult).setForeground(Color.white);
lblResult.setFont(new Font("Helvetica", Font.PLAIN, 12));
txtEnglish = new TextField(MAX_TEXT);
(txtEnglish).setBackground(Color.black);
(txtEnglish).setForeground(Color.Green);
txtFrench = new TextField(MAX_TEXT);
(txtFrench).setBackground(Color.black);
(txtFrench).setForeground(Color.green);
cmdExit = new Button("Exit");
(cmdExit).setBackground(Color.black);
(cmdExit).setForeground(Color.white);
cmdReset = new Button("Reset results");
(cmdReset).setBackground(Color.black);
(cmdReset).setForeground(Color.white);
cmdSubmit = new Button("Submit");
(cmdSubmit).setBackground(Color.black);
(cmdSubmit).setForeground(Color.white);
txtEnglish.setEditable(false);
intQuestionsRight = 0;
}
// initialise frame
public void showFrame() {
MyListener myListener = new MyListener();
setBackground( Color.black);
setLayout(new GridLayout(0,1));
// set panels
Panel pn1, pn2, pn3, pn4, pn5;
pn1 = new Panel(new FlowLayout( FlowLayout.RIGHT ));
pn2 = new Panel(new FlowLayout( FlowLayout.LEFT ));
pn3 = new Panel(new FlowLayout( FlowLayout.LEFT ));
pn4 = new Panel(new FlowLayout( FlowLayout.LEFT ));
pn5 = new Panel(new FlowLayout( FlowLayout.RIGHT ));
// add panels
pn1.add( lblScore );
pn2.add( englishTextLabel );
pn2.add( txtEnglish );
pn3.add( frenchTextLabel );
pn3.add( txtFrench );
pn4.add( lblResult );
pn3.add( cmdSubmit );
pn5.add( cmdReset );
pn5.add( cmdExit );
add( pn1 );
add( pn2 );
add( pn3 );
add( pn4 );
add( pn5 );
// set menubar
MenuItem miSubmit = new MenuItem( "Submit" );
MenuItem miReset = new MenuItem( "Reset results" );
MenuItem miExit = new MenuItem( "Exit" );
Menu mMenu = new Menu( "File" );
// add menu to menubar
mbMenu.add( mMenu );
mMenu.add( miSubmit );
mMenu.add( miReset );
mMenu.add( miExit );
setMenuBar( mbMenu );
// set action listener
miSubmit.addActionListener( myListener );
miReset.addActionListener( myListener );
miExit.addActionListener( myListener );
cmdSubmit.addActionListener( myListener );
cmdReset.addActionListener( myListener );
cmdExit.addActionListener( myListener );
getQA();
txtEnglish.setText("How do you say '" + strQst + "' in French?");
pack();
setVisible(true);
addWindowListener(myListener);
}
// check score against MAX_SCORE
public void checkScore(double dblScore) {
if (dblScore >= MAX_SCORE) {
cmdSubmit.setEnabled(false);
} else {
getQA();
txtEnglish.setText("How do you say '" + strQst + "' in French?");
txtFrench.setText("");
}
}
// check and get question and answer
public void getQA() {
Question tmpQuestion;
intQuestionNo = rndRandom.nextInt( vctQuestions.size() );
tmpQuestion = (Question)vctQuestions.elementAt( intQuestionNo );
while (tmpQuestion.getAsk()) {
tmpQuestion = null;
intQuestionNo = rndRandom.nextInt( vctQuestions.size() );
tmpQuestion = (Question)vctQuestions.elementAt( intQuestionNo );
}
strQst = tmpQuestion.getQuestion();
strAns = tmpQuestion.getAnswer();
}
// set the question to never to be chosen in the current session
public void setQuestionAsk() {
Question tmpQuestion;
tmpQuestion = (Question)vctQuestions.elementAt( intQuestionNo );
tmpQuestion.setAsk(true);
vctQuestions.removeElementAt( intQuestionNo );
vctQuestions.insertElementAt( tmpQuestion, intQuestionNo );
}
// error dialog box
public void showErrorDialog() {
MyListener myListener = new MyListener();
Button cmdOK = new Button( "OK" );
Dialog dlgError = new Dialog(new Frame(), "Error!", true);
dlgError.setLayout( new FlowLayout( FlowLayout.LEFT ));
dlgError.add( new Label( "The file specified is missing or invalid" ));
dlgError.add( cmdOK );
dlgError.pack();
cmdOK.addActionListener( myListener );
dlgError.addWindowListener(myListener);
dlgError.setVisible( true );
}
// tokenize line and enter question and answer into linked list
public void tokenQA( String strLine ) {
StringTokenizer stzFile = null;
Question qstQA = null;
String strTmpQ = "";
String strTmpA = "";
// try-catch to spot anomalies in file
try {
stzFile = new StringTokenizer(strLine, ".");
strTmpQ = stzFile.nextToken();
strTmpA = stzFile.nextToken();
qstQA = new Question(strTmpQ, strTmpA);
vctQuestions.addElement(qstQA);
} catch (NoSuchElementException nSEe) {
// print Error and Dialog box
System.out.println( "The file specified is missing or invalid" );
showErrorDialog();
System.exit(0);
}
}
// reads the file
public void readFile( String strFilename ) {
InputStream isFile = null;
String strFile = "";
int intTemp = 0;
// open FileInputStream to read file
try {
isFile = new FileInputStream( strFilename );
} catch ( FileNotFoundException fNFE ) {
System.out.println( "The file specified is missing or invalid" );
showErrorDialog();
System.exit(0);
}
// reads the file and tokenize each line
do {
try {
intTemp = isFile.read();
} catch ( IOException ioE ) {
System.out.println( "The file specified is missing or invalid" );
showErrorDialog();
System.exit(0);
}
if (intTemp == 10) {
tokenQA( strFile );
strFile = "";
} else {
strFile += strFile.valueOf( (char)intTemp );
}
} while ( intTemp != -1 );
tokenQA( strFile );
// closes FileInputStream
try {
isFile.close();
} catch ( IOException ioE ) {
System.out.println( ioE.getMessage() );
System.exit(0);
}
}
// update the score
public void updateScore() {
double dblScore;
dblScore = (int)((double)intQuestionsRight / (double)vctQuestions.size() * 100);
lblScore.setText("Score: " + dblScore + "%");
checkScore(dblScore);
}
// Listener class for 'Voca'
class MyListener extends WindowAdapter implements ActionListener {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
// actions
public void actionPerformed(ActionEvent e) {
String source = "";
if (e.getSource() instanceof Button) {
source = ((Button)e.getSource()).getLabel();
} else if (e.getSource() instanceof MenuItem) {
source = ((MenuItem)e.getSource()).getLabel();
}// end of if
if (source.equals("Exit") | source.equals("OK")) {
// 'Exit' clicked
System.exit(0);
} else if (source.equals("Submit")) {
// 'Submit' clicked
if (txtFrench.getText().equals(strAns)) {
// correct answer given
lblResult.setText("Good!");
setQuestionAsk();
intQuestionsRight++;
updateScore();
} else {
// wrong answer given
lblResult.setText("Wrong! '" + strQst + "' -> '" + strAns +"' ");
getQA();
txtEnglish.setText("How do you say '" + strQst + "' in French?");
txtFrench.setText("");
}// end of if
} else if (source.equals("Reset results")) {
// 'Reset results' clicked
Question tmpQuestion;
lblResult.setText("Welcome to Voca, try to get " + MAX_SCORE + "%");
lblScore.setText("Score: 0.0%");
cmdSubmit.setEnabled(true);
intQuestionsRight = 0;
// reset questions availability
for (int x = 0; x < vctQuestions.size(); x++ ) {
tmpQuestion = (Question)vctQuestions.elementAt(x);
tmpQuestion.setAsk(false);
vctQuestions.removeElementAt(x);
vctQuestions.insertElementAt(tmpQuestion, x);
}// end of for
getQA();
txtEnglish.setText("How do you say '" + strQst + "' in French?");
txtFrench.setText("");
}// end of if
}// end of actionPerformed method
}//end of MyListener inner class
// main subroutine for 'Voca'
public static void main(String[] args) {
Voca myFrame = null;
try {
myFrame = new Voca(args[0]);
} catch (ArrayIndexOutOfBoundsException aIOBe) {
myFrame = new Voca(DEFAULT);
}
myFrame.showFrame();
}//end of main method
}//end of Voca class
// Question class to store one question
class Question {
private String strQuestion;
private String strAnswer;
private boolean blnAsk;
// Question class constructor
Question(String strTmpQuestion, String strTmpAnswer) {
strQuestion = strTmpQuestion;
strAnswer = strTmpAnswer;
blnAsk = false;
}
// returns question
public String getQuestion() {
return strQuestion;
}
// returns answer
public String getAnswer() {
return strAnswer;
}
// returns whether question can be asked again
public boolean getAsk() {
return blnAsk;
}
// set whether question can be asked again
public void setAsk(boolean blnTmpAsk) {
blnAsk = blnTmpAsk;
}
}// end of Question class
</javacode>
And here's what I converted it to (which I'm sure is horrendously wrong in some way). It *will* compile, but I get the following errors:
Exception in thread "main" java.land.IllegalArgumentException: illegal component composition
at java.awt.Container.addImpl(Container.java:303)
at java.awt.Container.add(Container.java:234)
at Voca.showJFrame(Voca.java:98)
at Voca.main(Voca.java:33)
Here's my converted code so far:
<javacode>
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
public class Voca extends JFrame {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel{
UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) { }
new SwingApplication();
}
// global constants
public static final int ERROR = 1;
public static final int MAX_SCORE = 60;
public static final int MAX_TEXT = 30;
public static final String DEFAULT = "default.voc";
// class properties
private Random rndRandom = new Random();
private Vector vctQuestions = new Vector();
private JMenuBar mbMenu = new JMenuBar();
private JLabel lblScore, lblResult, englishTextLabel, frenchTextLabel;
private JTextField txtEnglish, txtFrench;
private JButton cmdExit, cmdReset, cmdSubmit;
private String strQst, strAns;
private int intQuestionNo, intQuestionsRight;
// Voca constructor
public Voca(String strFilename) {
super("Voca program");
readFile(strFilename);
lblScore = new JLabel("Score: 0.0%");
lblScore.setFont(new Font("Helvetica", Font.PLAIN, 14));
(lblScore).setForeground(Color.white);
englishTextLabel = new JLabel ("English:");
englishTextLabel.setFont(new Font("Helvetica", Font.BOLD, 14));
(englishTextLabel).setForeground(Color.green);
frenchTextLabel = new JLabel ("French: ");
frenchTextLabel.setFont(new Font("Helvetica", Font.BOLD, 14));
(frenchTextLabel).setForeground(Color.green);
lblResult = new JLabel("Welcome to Voca, try to get " + MAX_SCORE + "%");
(lblResult).setForeground(Color.white);
lblResult.setFont(new Font("Helvetica", Font.PLAIN, 14));
txtEnglish = new JTextField(MAX_TEXT);
(txtEnglish).setBackground(Color.black);
(txtEnglish).setForeground(Color.green);
txtFrench = new JTextField(MAX_TEXT);
(txtFrench).setBackground(Color.black);
(txtFrench).setForeground(Color.green);
cmdExit = new JButton("Exit");
(cmdExit).setBackground(Color.black);
(cmdExit).setForeground(Color.white);
cmdReset = new JButton("Reset results");
(cmdReset).setBackground(Color.black);
(cmdReset).setForeground(Color.white);
cmdSubmit = new JButton("Submit");
(cmdSubmit).setBackground(Color.black);
(cmdSubmit).setForeground(Color.white);
txtEnglish.setEditable(false);
intQuestionsRight = 0;
}
// initialise frame
public void showJFrame() {
MyListener myListener = new MyListener();
Container pane = getContentPane();
setBackground( Color.black);
pane.setLayout(new GridLayout(0,1));
// set panels
JPanel pn1, pn2, pn3, pn4, pn5;
pn1 = new JPanel();
pane.add(pn1, FlowLayout.RIGHT);
pn2 = new JPanel();
pane.add(pn2, FlowLayout.LEFT);
pn3 = new JPanel();
pane.add(pn3, FlowLayout.LEFT);
pn4 = new JPanel();
pane.add(pn4, FlowLayout.LEFT);
pn5 = new JPanel();
pane.add(pn5, FlowLayout.RIGHT);
// add panels
pn1.add( lblScore );
pn2.add( englishTextLabel );
pn2.add( txtEnglish );
pn3.add( frenchTextLabel );
pn3.add( txtFrench );
pn4.add( lblResult );
pn3.add( cmdSubmit );
pn5.add( cmdReset );
pn5.add( cmdExit );
// set menubar
JMenuItem miSubmit = new JMenuItem( "Submit" );
JMenuItem miReset = new JMenuItem( "Reset results" );
JMenuItem miExit = new JMenuItem( "Exit" );
JMenu mMenu = new JMenu( "File" );
// add menu to menubar
mbMenu.add( mMenu );
mMenu.add( miSubmit );
mMenu.add( miReset );
mMenu.add( miExit );
setJMenuBar( mbMenu );
// set action listener
miSubmit.addActionListener( myListener );
miReset.addActionListener( myListener );
miExit.addActionListener( myListener );
cmdSubmit.addActionListener( myListener );
cmdReset.addActionListener( myListener );
cmdExit.addActionListener( myListener );
getQA();
txtEnglish.setText("How do you say '" + strQst + "' in French?");
pack();
setVisible(true);
addWindowListener(myListener);
}
// check score against MAX_SCORE
public void checkScore(double dblScore) {
if (dblScore >= MAX_SCORE) {
cmdSubmit.setEnabled(false);
} else {
getQA();
txtEnglish.setText("How do you say '" + strQst + "' in French?");
txtFrench.setText("");
}
}
// check and get question and answer
public void getQA() {
Question tmpQuestion;
intQuestionNo = rndRandom.nextInt( vctQuestions.size() );
tmpQuestion = (Question)vctQuestions.elementAt( intQuestionNo );
while (tmpQuestion.getAsk()) {
tmpQuestion = null;
intQuestionNo = rndRandom.nextInt( vctQuestions.size() );
tmpQuestion = (Question)vctQuestions.elementAt( intQuestionNo );
}
strQst = tmpQuestion.getQuestion();
strAns = tmpQuestion.getAnswer();
}
// set the question to never to be chosen in the current session
public void setQuestionAsk() {
Question tmpQuestion;
tmpQuestion = (Question)vctQuestions.elementAt( intQuestionNo );
tmpQuestion.setAsk(true);
vctQuestions.removeElementAt( intQuestionNo );
vctQuestions.insertElementAt( tmpQuestion, intQuestionNo );
}
// error dialog box
public void showErrorDialog() {
MyListener myListener = new MyListener();
JButton cmdOK = new JButton( "OK" );
JDialog dlgError = new JDialog(new JFrame(), "Error!", true);
dlgError.setLayout( new FlowLayout( FlowLayout.LEFT ));
dlgError.add( new JLabel( "The file specified is missing or invalid" ));
dlgError.add( cmdOK );
dlgError.pack();
cmdOK.addActionListener( myListener );
dlgError.addWindowListener(myListener);
dlgError.setVisible( true );
}
// tokenize line and enter question and answer into linked list
public void tokenQA( String strLine ) {
StringTokenizer stzFile = null;
Question qstQA = null;
String strTmpQ = "";
String strTmpA = "";
// try-catch to spot anomalies in file
try {
stzFile = new StringTokenizer(strLine, ".");
strTmpQ = stzFile.nextToken();
strTmpA = stzFile.nextToken();
qstQA = new Question(strTmpQ, strTmpA);
vctQuestions.addElement(qstQA);
} catch (NoSuchElementException nSEe) {
// print Error and Dialog box
System.out.println( "The file specified is missing or invalid" );
showErrorDialog();
System.exit(0);
}
}
// reads the file
public void readFile( String strFilename ) {
InputStream isFile = null;
String strFile = "";
int intTemp = 0;
// open FileInputStream to read file
try {
isFile = new FileInputStream( strFilename );
} catch ( FileNotFoundException fNFE ) {
System.out.println( "The file specified is missing or invalid" );
showErrorDialog();
System.exit(0);
}
// reads the file and tokenize each line
do {
try {
intTemp = isFile.read();
} catch ( IOException ioE ) {
System.out.println( "The file specified is missing or invalid" );
showErrorDialog();
System.exit(0);
}
if (intTemp == 10) {
tokenQA( strFile );
strFile = "";
} else {
strFile += strFile.valueOf( (char)intTemp );
}
} while ( intTemp != -1 );
tokenQA( strFile );
// closes FileInputStream
try {
isFile.close();
} catch ( IOException ioE ) {
System.out.println( ioE.getMessage() );
System.exit(0);
}
}
// update the score
public void updateScore() {
double dblScore;
dblScore = (int)((double)intQuestionsRight / (double)vctQuestions.size() * 100);
lblScore.setText("Score: " + dblScore + "%");
checkScore(dblScore);
}
// Listener class for 'Voca'
class MyListener extends WindowAdapter implements ActionListener {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
// actions
public void actionPerformed(ActionEvent e) {
String source = "";
if (e.getSource() instanceof JButton) {
source = ((JButton)e.getSource()).getText();
} else if (e.getSource() instanceof JMenuItem) {
source = ((JMenuItem)e.getSource()).getText();
}// end of if
if (source.equals("Exit") | source.equals("OK")) {
// 'Exit' clicked
System.exit(0);
} else if (source.equals("Submit")) {
// 'Submit' clicked
if (txtFrench.getText().equals(strAns)) {
// correct answer given
lblResult.setText("Good!");
setQuestionAsk();
intQuestionsRight++;
updateScore();
} else {
// wrong answer given
lblResult.setText("Wrong! '" + strQst + "' -> '" + strAns +"' ");
getQA();
txtEnglish.setText("How do you say '" + strQst + "' in French?");
txtFrench.setText("");
}// end of if
} else if (source.equals("Reset results")) {
// 'Reset results' clicked
Question tmpQuestion;
lblResult.setText("Welcome to Voca, try to get " + MAX_SCORE + "%");
lblScore.setText("Score: 0.0%");
cmdSubmit.setEnabled(true);
intQuestionsRight = 0;
// reset questions availability
for (int x = 0; x < vctQuestions.size(); x++ ) {
tmpQuestion = (Question)vctQuestions.elementAt(x);
tmpQuestion.setAsk(false);
vctQuestions.removeElementAt(x);
vctQuestions.insertElementAt(tmpQuestion, x);
}// end of for
getQA();
txtEnglish.setText("How do you say '" + strQst + "' in French?");
txtFrench.setText("");
}// end of if
}// end of actionPerformed method
}//end of MyListener inner class
}//end of Voca class
// Question class to store one question
class Question {
private String strQuestion;
private String strAnswer;
private boolean blnAsk;
// Question class constructor
Question(String strTmpQuestion, String strTmpAnswer) {
strQuestion = strTmpQuestion;
strAnswer = strTmpAnswer;
blnAsk = false;
}
// returns question
public String getQuestion() {
return strQuestion;
}
// returns answer
public String getAnswer() {
return strAnswer;
}
// returns whether question can be asked again
public boolean getAsk() {
return blnAsk;
}
// set whether question can be asked again
public void setAsk(boolean blnTmpAsk) {
blnAsk = blnTmpAsk;
}
}// end of Question class
</javacode>
Where am I going wrong? I'm pulling my hair out here :-). If someone could please offer me some assistance, I would be most grateful.
If anyone could also tell me how exactly to change the look and feel of the app, that would be fantastic.
Someone please help (struggling college student is going mad!)
Carrie