Java Thread

Cromewell

Administrator
Staff member
Here:
Code:
JScrollPane editor_scrPane = new JScrollPane();
		editor_scrPane.addHierarchyBoundsListener(new HierarchyBoundsAdapter() {
			@Override
			public void ancestorResized(HierarchyEvent e) {
				this.setSize(new Dimension());
			}
		});
though I'm not sure it will work, usually to do that you need to do exactly what the compiler told you, declare it as a final.
 

Troncoso

VIP Member
That doesn't work, but adding final does make the error go away.

Now, how will I actually account for the change in size of the window, to properly update the size of editor_scrPane?
 

Cromewell

Administrator
Staff member
Try passing the new height and width you want to the dimension yo uare creating. You'll have to figure out what they should be but that shouldn't be overly difficult. e.getChanged() will return the object which was resized.
 

neilofbodom

Member
Hi, i'm working on a Java project as part of my a-level. I decided to create a music trivia quiz. I have encountered some problems in displaying the multiple choice answers using a JComboBox. The program reads the questions and answers from a text file I created separately. I think there is something wrong with my code. Is there anyone who would be willing to help me please? The code is quite long since it involves different classes so I won't paste it here. If anyone can help, i'll email the code.

Thank you very much :)

-neilofbodom
 

Troncoso

VIP Member
Hi, i'm working on a Java project as part of my a-level. I decided to create a music trivia quiz. I have encountered some problems in displaying the multiple choice answers using a JComboBox. The program reads the questions and answers from a text file I created separately. I think there is something wrong with my code. Is there anyone who would be willing to help me please? The code is quite long since it involves different classes so I won't paste it here. If anyone can help, i'll email the code.

Thank you very much :)

-neilofbodom

You can go ahead and post the code here. Just be sure to use the "[COD E][/COD E]"
(No space before the E).
That way, it'll restrict your code to a smaller window size.
 

neilofbodom

Member
This is the code for the Main Menu Window. Depending on the user's choice, it calls another window.
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MainMenuWindow extends JFrame implements MouseListener {

	private JButton start, exit;
	private JComboBox genreField;

	public MainMenuWindow() throws Exception{

		super("Main Menu");
		build();
	}

	public void build() throws Exception{
		this.setLayout(new BorderLayout());

		JPanel north = new JPanel(new FlowLayout(FlowLayout.CENTER));
		JLabel title = new JLabel("Main Menu- Music Trivia Quiz");
		title.setFont(new Font("Comic Sans",Font.BOLD,18));
		north.add(title);
		this.add(north,BorderLayout.NORTH);

		JPanel center = new JPanel(new GridLayout(1,1));

		JPanel genreLabelPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		JLabel genre = new JLabel ("Choose Genre: ");
		genreLabelPanel.add(genre);

		JPanel genrePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		String[] options = new String[3];
		options[0] = "Classical";
		options[1] = "Rock";
		options[2] = "Metal";
		for (int i = 0; i < options.length; i++){
			System.out.println(options[i]);
		}
		genreField = new JComboBox(options);
		genreLabelPanel.add(genreField);
		genrePanel.add(genreLabelPanel);
		genreField.addMouseListener(this);

		center.add(genreLabelPanel);
		center.add(genrePanel);

		this.add(center,BorderLayout.WEST);

		JPanel south = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		start = new JButton("START");
		start.setForeground(Color.WHITE);
		start.setBackground(Color.BLACK);

		exit = new JButton("EXIT");
		exit.setForeground(Color.WHITE);
		exit.setBackground(Color.BLACK);
		south.add(start);
		south.add(exit);
		start.addMouseListener(this);
		exit.addMouseListener(this);
		this.add(south,BorderLayout.SOUTH);

		north.setBackground(Color.BLACK);
		center.setBackground(Color.BLACK);
		south.setBackground(Color.BLACK);
		genreLabelPanel.setBackground(Color.BLACK);
		genrePanel.setBackground(Color.BLACK);
		this.setBounds(0,0,500,300);
		this.setResizable(false);
		this.setVisible(true);
	}

	public void mouseClicked(MouseEvent e){
		if (e.getSource().equals(start)){
			this.setVisible(false);
			String x = genreField.getSelectedItem().toString();
			if (x == "Rock"){
				StartRockWindow sr = new StartRockWindow();
				sr.setVisible(true);
			}else if (x == "Classical"){
				StartClassicalWindow sc = new StartClassicalWindow();
				sc.setVisible(true);
			}

		} else if (e.getSource().equals(exit)){
			this.setVisible(false);
		}
	}

	public void mouseEntered(MouseEvent e){

	}

	public void mouseExited(MouseEvent e){

	}

	public void mousePressed(MouseEvent e){

	}

	public void mouseReleased(MouseEvent e){

	}
}

/* That is the code for the main menu. The next code is for the Rock Window which opens if the user selects 'Rock' from the main menu. */

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

public class StartRockWindow extends JFrame implements MouseListener{

	private JButton next, exit;
	private JComboBox choiceField;

	public StartRockWindow() throws Exception{
		super("Start Rock");
		build();
	}

	private void build() throws Exception{
		FileReader f = new FileReader("RockQuestions.txt");
  		BufferedReader br = new BufferedReader(f);
		String question = br.readLine();

		FileReader f1 = new FileReader("RockAnswers.txt");
		BufferedReader br1 = new BufferedReader(f1);
		String []choices = new String [60];

		for (int i = 0; i < 2; i++){
			choices[i] = br.readLine();
		}

		for (int i = 0; i < 20; i++){
			String q[] = new String[20];
			String a[] = new String[60];
			String[] choice = new String[3];

			this.setLayout(new BorderLayout());

			JPanel north = new JPanel(new FlowLayout(FlowLayout.CENTER));
			JLabel title = new JLabel("Rock Section");
			title.setFont(new Font("Comic Sans",Font.BOLD,18));
			north.add(title);
			this.add(north,BorderLayout.NORTH);

			JPanel center = new JPanel(new GridLayout(1,1));
			String x = "";

			switch (i){
				case 0: q[0] = question;
						a[0] = choices[0];
						a[1] = choices[1];
						a[2] = choices[2];
						if (x == a[0]){
							CorrectAnswerWindow ca = new CorrectAnswerWindow();
							ca.setVisible(true);
						} else {
							WrongAnswerWindow wa = new WrongAnswerWindow();
							wa.setVisible(true);
						}
						break;

			}


			JPanel question1LabelPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
			JLabel question1 = new JLabel ("Question "+(i+1)+": "+q[i]);
			question1LabelPanel.add(question1);

			JPanel choicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));


			for (int j = 0; j < choice.length; j++){
					choices[j] = choices[j];
			}

			choiceField = new JComboBox(choice);
			question1LabelPanel.add(choiceField);
			choicePanel.add(question1LabelPanel);
			choiceField.addMouseListener(this);

			center.add(question1LabelPanel);
			center.add(choicePanel);
			this.add(center,BorderLayout.WEST);

			JPanel south = new JPanel(new FlowLayout(FlowLayout.RIGHT));
			next = new JButton("NEXT");
			next.setForeground(Color.WHITE);
			next.setBackground(Color.BLACK);

			exit = new JButton("EXIT");
			exit.setForeground(Color.WHITE);
			exit.setBackground(Color.BLACK);
			south.add(next);
			south.add(exit);
			next.addMouseListener(this);
			exit.addMouseListener(this);
			this.add(south,BorderLayout.SOUTH);

			north.setBackground(Color.BLACK);
			center.setBackground(Color.BLACK);
			south.setBackground(Color.BLACK);
			question1LabelPanel.setBackground(Color.BLACK);
			choicePanel.setBackground(Color.BLACK);
			this.setBounds(0,0,500,300);
			this.setResizable(false);


			this.setVisible(true);
		}


	}

	public void mouseClicked(MouseEvent e) {
		if (e.getSource().equals(exit)){
			this.setVisible(false);
		} else if (e.getSource().equals(next)){
		}
	}

	public void mouseEntered(MouseEvent e){

	}

	public void mouseExited(MouseEvent e){

	}

	public void mousePressed(MouseEvent e){

	}

	public void mouseReleased(MouseEvent e){

	}

}
 
Last edited by a moderator:

neilofbodom

Member
My problem lies somewhere in the StartRockWindow class. I need to print on the window the question and a combo box containing the answers (multiple choice). It is printing the question but leaves the combo box empty. Any ideas?
 

Cromewell

Administrator
Staff member
Is there a reason a bunch of your methods throw a generic exception? Instead of catching it or throwing a more specific one?

Are you getting any exceptions in the console? I'm guessing that it's not finding your text file.
 

neilofbodom

Member
Is there a reason a bunch of your methods throw a generic exception? Instead of catching it or throwing a more specific one?

Are you getting any exceptions in the console? I'm guessing that it's not finding your text file.

I was getting exceptions so I decided to throw exceptions that way. I do not know how to do proper exception handling, i never understood them properly.

It finds the text file for the questions though because it displays them. I think it is finding the text file for the answers but it is not displaying them.
 

neilofbodom

Member
Just want to let you know that i managed to solve the problem.
In the StartRockWindow class, the following line was incorrect: String []choices = new String [60];

It had to be: String []choices = new String [3];
Also, the loop
for (int i = 0; i < 2; i++){
choices = br.readLine();
}

was combined with the other loop to get this:
for (int j = 0; j < choices.length; j++){
choices[j] = br1.readLine();
System.out.println(choices[j]);
}

thank you very much for you help anyway :)
 

Cromewell

Administrator
Staff member
Good to hear you got it working.
I was getting exceptions so I decided to throw exceptions that way. I do not know how to do proper exception handling, i never understood them properly.

It finds the text file for the questions though because it displays them. I think it is finding the text file for the answers but it is not displaying them.
Exceptions are relatively easy to work with/understand. One is thrown when something doesn't work as intended. For files, it could be they weren't found, it was locked, etc. To handle them use try { code } catch (exceptionThatCodeThrows e) { code for when error occurs }

In your application, I think you are only dealing with IO exceptions, you always have them when dealing with files, but I haven't read through it all there may be another.
 

neilofbodom

Member
Good to hear you got it working.

Exceptions are relatively easy to work with/understand. One is thrown when something doesn't work as intended. For files, it could be they weren't found, it was locked, etc. To handle them use try { code } catch (exceptionThatCodeThrows e) { code for when error occurs }

In your application, I think you are only dealing with IO exceptions, you always have them when dealing with files, but I haven't read through it all there may be another.

Thanks Cromewell! i'll try it out :)
 

neilofbodom

Member
In my code, I'm getting a nullPointerException. How is that caused and how can I solve it?
The code is as follows (there were some changes to my previous post):

private void build() throws Exception{
FileReader f = new FileReader("RockQuestions.txt");
BufferedReader br = new BufferedReader(f);
String question = br.readLine();

FileReader f1 = new FileReader("RockAnswers.txt");
BufferedReader br1 = new BufferedReader(f1);

FileReader f2 = new FileReader("RockCorrectAnswers.txt");
BufferedReader br2 = new BufferedReader(f2);
correct = br2.readLine();

for (int i = 0; i < 20; i++){
String q[] = new String[20];
String a[] = new String[60];
String []choices = new String [3];

this.setLayout(new BorderLayout());

JPanel north = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel title = new JLabel("Rock Section");
title.setFont(new Font("Comic Sans",Font.BOLD,18));
north.add(title);
this.add(north,BorderLayout.NORTH);

JPanel center = new JPanel(new GridLayout(1,1));


switch (i){
case 0: q[0] = question;
a[0] = choices[0];
a[1] = choices[1];
a[2] = choices[2];
break;

}


JPanel question1LabelPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JLabel question1 = new JLabel ("Question "+(i+1)+": "+q);
question1LabelPanel.add(question1);

for (int j = 0; j < 3; j++){
choices[j] = br1.readLine();
System.out.println(choices[j]);
}

JPanel choicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));


choiceField = new JComboBox(choices);
question1LabelPanel.add(choiceField);
choicePanel.add(question1LabelPanel);
choiceField.addMouseListener(this);

x = choiceField.getSelectedItem().toString();

center.add(question1LabelPanel);
center.add(choicePanel);
this.add(center,BorderLayout.WEST);

JPanel south = new JPanel(new FlowLayout(FlowLayout.RIGHT));
next = new JButton("NEXT");
next.setForeground(Color.WHITE);
next.setBackground(Color.BLACK);

exit = new JButton("EXIT");
exit.setForeground(Color.WHITE);
exit.setBackground(Color.BLACK);
south.add(next);
south.add(exit);
next.addMouseListener(this);
exit.addMouseListener(this);
this.add(south,BorderLayout.SOUTH);

north.setBackground(Color.BLACK);
center.setBackground(Color.BLACK);
south.setBackground(Color.BLACK);
question1LabelPanel.setBackground(Color.BLACK);
choicePanel.setBackground(Color.BLACK);
this.setBounds(0,0,500,300);
this.setResizable(false);


this.setVisible(true);
}


}

public void mouseClicked(MouseEvent e) {
if (e.getSource().equals(exit)){
this.setVisible(false);
} else if (e.getSource().equals(next)){
if (x == correct){
CorrectAnswerWindow ca = new CorrectAnswerWindow();
ca.setVisible(true);
} else {
WrongAnswerWindow wa = new WrongAnswerWindow();
wa.setVisible(true);
}

}
}
The error lies in x = choiceField.getSelectedItem().toString();
Also, how can I compare 2 strings to see if they contain the same word? For example, if the correct answer is "ABC" but the user chose "DEF", how can I compare the 2 strings?

Thanks in advance!
 

Cromewell

Administrator
Staff member
A nullPointerException occurs when you try to use a null value when you need to use an object. Most often this happens if you try to do something like
ArrayList<String> abcd;
abcd.add("asdf");

instead of
ArrayList<String> abcd = new ArrayList<String>;
abcd.add("asdf");

Do you have an item selected in your combobox?

To compare strings use .equals(object) or .equalsIgnoreCase(object).
 
Last edited:

Cromewell

Administrator
Staff member
Ok. Can you post up your text files? I don't need the full thing, just 1 complete question and answer.

edit: I'm also missing a bunch of classes. I've removed the StartClassicalWindow references but in StartRockWindow there are CorrectAnswerWindow and WrongAnswerWindow. It looks like I can safely remove them for now but if there are errors in them you may still get exceptions.

You have references to variables x and correct which have no declarations that I can find. That should be preventing your code from building. Is it possible there were other parts you changed but forgot to post?
 
Last edited:

neilofbodom

Member
Ok. Can you post up your text files? I don't need the full thing, just 1 complete question and answer.

edit: I'm also missing a bunch of classes. I've removed the StartClassicalWindow references but in StartRockWindow there are CorrectAnswerWindow and WrongAnswerWindow. It looks like I can safely remove them for now but if there are errors in them you may still get exceptions.

You have references to variables x and correct which have no declarations that I can find. That should be preventing your code from building. Is it possible there were other parts you changed but forgot to post?

RockQuestions.txt has:
Where was the band Led Zeppelin from?

RockAnswers.txt has:
England //this is the correct answer
Ireland
USA

You can ignore the StartClassicalWindow for now.

CorrectAnswerWindow class:

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

public class CorrectAnswerWindow extends JFrame implements MouseListener{

private JButton cont;

public CorrectAnswerWindow(){
super("Correct Answer");
build();
}


public void build(){

this.setLayout(new BorderLayout());

JPanel north = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel title = new JLabel("Music Trivia Quiz");
title.setFont(new Font("Comic Sans",Font.BOLD,18));
north.add(title);
this.add(north,BorderLayout.NORTH);

JPanel center = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel comment = new JLabel("CORRECT ANSWER! You get 2 points.");
comment.setFont(new Font("Comic Sans", Font.BOLD, 28));
center.add(comment);
this.add(center,BorderLayout.CENTER);

JPanel south = new JPanel(new FlowLayout(FlowLayout.RIGHT));
cont = new JButton("CONTINUE");
cont.setForeground(Color.RED);
cont.setBackground(Color.BLACK);
south.add(cont);
cont.addMouseListener(this);
this.add(south,BorderLayout.SOUTH);
this.setBounds(0,0,300,200);

this.setVisible(false);
}

public void mouseClicked(MouseEvent e) {
if (e.getSource().equals(cont)){
this.setVisible(false);
}
}

public void mouseEntered(MouseEvent e){

}

public void mouseExited(MouseEvent e){

}

public void mousePressed(MouseEvent e){

}

public void mouseReleased(MouseEvent e){

}
}

WrongAnswerWindow class:

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

public class WrongAnswerWindow extends JFrame implements MouseListener{

private JButton cont;

public WrongAnswerWindow(){
super("Wrong Answer");
build();
}


public void build(){

this.setLayout(new BorderLayout());

JPanel north = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel title = new JLabel("Music Trivia Quiz");
title.setFont(new Font("Comic Sans",Font.BOLD,18));
north.add(title);
this.add(north,BorderLayout.NORTH);

JPanel center = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel comment = new JLabel("Wrong answer! You lose a point.");
comment.setFont(new Font("Comic Sans", Font.BOLD, 28));
center.add(comment);
this.add(center,BorderLayout.CENTER);

JPanel south = new JPanel(new FlowLayout(FlowLayout.RIGHT));
cont = new JButton("CONTINUE");
cont.setForeground(Color.RED);
cont.setBackground(Color.BLACK);
south.add(cont);
cont.addMouseListener(this);
this.add(south,BorderLayout.SOUTH);
this.setBounds(0,0,300,200);

this.setVisible(true);
}

public void mouseClicked(MouseEvent e) {
if (e.getSource().equals(cont)){
this.setVisible(false);
}
}

public void mouseEntered(MouseEvent e){

}

public void mouseExited(MouseEvent e){

}

public void mousePressed(MouseEvent e){

}

public void mouseReleased(MouseEvent e){

}
}

The MainMenuWindow class wasn't changed. I guess that's everything you need. Thank you very much, I really appreciate your help! :D :)

Oh and StartRockWindow class also has this code which goes before the private void build() method:

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

public class StartRockWindow extends JFrame implements MouseListener{

private JButton next, exit;
private JComboBox choiceField;
public String x = new String();
public String correct;

public StartRockWindow() throws Exception{
super("Start Rock");
build();
}
 
Last edited:

Cromewell

Administrator
Staff member
I'm seeing a few things now that I have all the code in Eclipse.

I know you aren't finished yet but your exit button doesn't really exit, it's just hiding the StartRockWindow and not reshowing the main window. There's a couple other things, the main one being instead of loading the choice into X during your build method you need to check what was picked when they click the next button otherwise it will always think they picked the first option.

As for the exception, you must not have 20 questions yet. You have a for loop in StartRockWindow (it's on line 35 for me, but I don't remember if I added/removed lines above it). It looks like for (int i = 0; i < 20; i++){ ... for now, change the 20 to the number of questions/answer sets you have. For the future, if you know it's 1 question per line, you could read the file for how many you have and loop that many times to initialize it. I would suggest building a question class instead of maintaining all those string arrays as well.
 

neilofbodom

Member
Cheers! I managed to get rid of that exception and I solved the issue with the X and choice thing.

How do I exit the program then? I don't of any other way of exiting than what I wrote ie using .setVisible(false)

By the way, I am getting a problem when clicking on the next and exit buttons on the StartRockWindow. They are not responding.

An update of the code:
//the code before this remained the same

private void build() throws Exception{
FileReader f = new FileReader("RockQuestions.txt");
BufferedReader br = new BufferedReader(f);
String question = br.readLine();

FileReader f1 = new FileReader("RockAnswers.txt");
BufferedReader br1 = new BufferedReader(f1);

FileReader f2 = new FileReader("RockCorrectAnswers.txt");
BufferedReader br2 = new BufferedReader(f2);
correct = br2.readLine();

for (int i = 0; i < 2; i++){
String q[] = new String[20];
String a[] = new String[60];
String []choices = new String [3];

this.setLayout(new BorderLayout());

JPanel north = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel title = new JLabel("Rock Section");
title.setFont(new Font("Comic Sans",Font.BOLD,18));
north.add(title);
this.add(north,BorderLayout.NORTH);

JPanel center = new JPanel(new GridLayout(1,1));

for (int j = 0; j < 3; j++){
choices[j] = br1.readLine();
System.out.println(choices[j]);
}

switch (i){
case 0: q[0] = question;
a[0] = choices[0];
a[1] = choices[1];
a[2] = choices[2];
break;
case 1: q[0] = question;
a[3] = choices[0];
a[4] = choices[1];
a[5] = choices[2];
break;
}

JPanel question1LabelPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JLabel question1 = new JLabel ("Question "+(i+1)+": "+q);
question1LabelPanel.add(question1);

JPanel choicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));


choiceField = new JComboBox(choices);
question1LabelPanel.add(choiceField);
choicePanel.add(question1LabelPanel);
choiceField.addMouseListener(this);

center.add(question1LabelPanel);
center.add(choicePanel);
this.add(center,BorderLayout.WEST);

JPanel south = new JPanel(new FlowLayout(FlowLayout.RIGHT));
next = new JButton("NEXT");
next.setForeground(Color.WHITE);
next.setBackground(Color.BLACK);

exit = new JButton("EXIT");
exit.setForeground(Color.WHITE);
exit.setBackground(Color.BLACK);
south.add(next);
south.add(exit);
next.addMouseListener(this);
exit.addMouseListener(this);
this.add(south,BorderLayout.SOUTH);

north.setBackground(Color.BLACK);
center.setBackground(Color.BLACK);
south.setBackground(Color.BLACK);
question1LabelPanel.setBackground(Color.BLACK);
choicePanel.setBackground(Color.BLACK);
this.setBounds(0,0,500,300);
this.setResizable(false);


this.setVisible(true);
}


}

public void mouseClicked(MouseEvent e) {
if (e.getSource().equals(exit)){
this.setVisible(false);
} else if (e.getSource().equals(next)){
x = choiceField.getSelectedItem().toString();
if (x.equals(correct)){
CorrectAnswerWindow ca = new CorrectAnswerWindow();
ca.setVisible(true);
} else {
WrongAnswerWindow wa = new WrongAnswerWindow();
wa.setVisible(true);
}

}
}

public void mouseEntered(MouseEvent e){

}

public void mouseExited(MouseEvent e){

}

public void mousePressed(MouseEvent e){

}

public void mouseReleased(MouseEvent e){

}

}

Thanks Cromewell, you have been great help! :D
 

Cromewell

Administrator
Staff member
The most correct way would be to use Window Listeners (http://docs.oracle.com/javase/tutorial/uiswing/events/windowlistener.html).

For now hiding the window will work, just make sure you show the old window so you can close it with the X or Alt-F4 or with a System.exit() button (not the cleanest way to close but it will end it) or you might have the process stuck running forever.

I'll update your code and step through it when I get a chance later tonight.
 
Top