I am in the middle of creating a children's board game, that asks random maths questions and players move if they answer right. I have a main BoardGUI class that includes 2 panels. One for the board, and one for the questions.
I'm having trouble with the Question panel. I'm reading in questions from a text file and saving each question as an object within an array. The issue is I can answer one question correctly and it will refresh the question with a new one, however doesn't keep doing this.
I'll paste the QuestionGUI class, as I think this is the one with issues to do with generating the same question/answers from a random number.
public class QuestionGUI extends JPanel implements ActionListener {
JLabel question;
JButton btnAnswers[];
Reader r1 = new Reader();
Questions q1 = new Questions();
Random rand = new Random();
boolean answered;
int random = rand.nextInt(r1.ArraySize());
int random2 = rand.nextInt(r1.ArraySize());
int length = q1.getArrayItem(random).getAnswers().length;
public QuestionGUI() {
questionInit(random);
}
public void questionInit(int randomNum) {
this.random = randomNum;
//gets the answers from the array obj
String[] answers = q1.getArrayItem(random).getAnswers();
//sets the question from question of array obj (same obj as answers I assumed, using random num)
question = new JLabel("<html>" + (q1.getArrayItem(random).getQuestion()) + "</html>", SwingConstants.CENTER);
question.setPreferredSize(new Dimension(280, 100));
add(question);
btnAnswers = new JButton[length];
for (int i = 0; i < length; i++) {
btnAnswers[i] = new JButton(answers[i]);
btnAnswers[i].setPreferredSize(new Dimension(280, 60));
btnAnswers[i].addActionListener(this);
add(btnAnswers[i]);
}
}
#Override
public void actionPerformed(ActionEvent e) {
//sets the correct answers to question also using the random num
String[] correctAnswers = q1.getArrayItem(random).getCorrectAnswers();
for (int i = 0; i < length; i++) {
if (e.getSource().equals(btnAnswers[i])) {
String tmp1 = btnAnswers[i].getText();
if (Arrays.asList(correctAnswers).contains(tmp1)) {
System.out.println("Correct");
removeAll();
revalidate();
answered = true;
questionInit(random2);
repaint();
} else {
answered = false;
}
}
}
}
public boolean getAnswered() {
return answered;
}
}
It looks like you only generate the random number used as the index once.
int random2 = rand.nextInt(r1.ArraySize());
.
.
.
questionInit(random2);
You need to regenerate a random number each time. You can write a helper method to do this, or just put the code in the argument:
questionInit(rand.nextInt(r1.ArraySize()));
This might require additional refactoring.
Related
I need to create a lottery program that will allow user to select 4 numbers (image of the buttons here)
which then should be inputed into an array, I cannot get the array to fill fully, I have tried different versions of adding an int into array and I just can't seem to find the right one..
int hold;
int userNumbers[] = new int[3];
public lotteryGUI() {
initComponents();
}
private void twentyoneActionPerformed(java.awt.event.ActionEvent evt) {
hold = 21;
hold += userNumbers[0];
}
private void nineActionPerformed(java.awt.event.ActionEvent evt) {
hold = 9;
userNumbers[0]= hold + userNumbers[0];
}
private void oneActionPerformed(java.awt.event.ActionEvent evt) {
hold = 1;
userNumbers[0] = userNumbers[0] + hold ;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(Arrays.toString(userNumbers));
}
This is just a sample with 3 buttons, As you can probably tell the output i get is (10,0,0).
#edit
I have contacted my lecturer about this project and I received a little hint. I am supposed to add ActionListener and if the button is checked I am supposed to add it to an array. Not really sure how to do that, I'm going to look at some tutorials and edit this post if necessary
I would hate to hard code it, but it is really up to you to figure out how to do that for 28 buttons. Here is example for 1 button:
int counter = 0;
int[] userNumbers = new int[3];
public lotteryGUI() {
initComponents();
JButton number1 = new JButton("1");
JButton number2 = new JButton("2");
number1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
userNumbers[counter] = 1;
counter = counter + 1;
if (counter == 3)
// disable all buttons and display result maybe?
}
}
// ... the rest 27 buttons maybe?
}
I'm developing a simple game where all the images are randomized. I've noticed that some of the image are repeated although I have put the random code. I'm still new to Java. I hope that someone can help me solve my problem. Below is my coding.
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Random;
import javax.swing.*;
public class Task1 extends JFrame implements KeyListener,ActionListener {
JFrame frame = new JFrame("FYP");
JTextField textField = new JTextField();
JButton btnNext = new JButton("NEXT");
int sum=0;
int Error=0;int total_test = 0;
static String inputID;
static int index;
String[] imgFileHP = {"1.jpg","3.jpg","4.jpg","7.jpg","9.jpg","10.jpg","12.jpg","16.jpg","17.jpg","18.jpg"};
String[] imgNo = {"5","4","6","3","5","3","4","4","6","6"};
int randomNo;
Random rand = new Random();
public Task1(String inputID)
{
frame.setSize(2200,2500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.getContentPane().setLayout(new BorderLayout(0, 0));
Task(inputID);
}
public void Task(String inputID)
{
JPanel panel = new JPanel();
JLabel labelUsername = new JLabel("");
frame.getContentPane().add(panel, BorderLayout.CENTER);
panel.setBackground(Color.WHITE);
Collections.shuffle(Arrays.asList(imgFileHP));
Set<Integer> uniqueList = new HashSet<Integer>();//This would create list with the number 0 to 9
for(int count=0;count<imgFileHP.length;count++){
uniqueList.add(count);
labelUsername.setIcon(new ImageIcon(getClass().getResource("/image/" + imgFileHP[count])));
if(!uniqueList.isEmpty()){
index = (int) (Math.random() * (upper - lower)) + lower;
if(uniqueList.contains(index)){
uniqueList.remove(index);//particular number is delete from the list so that duplicate images doesnt show up
System.out.println(imgFileHP[r]);//This printf statement is just for your reference
}
}
}
textField.setText("");
textField.setColumns(10);
textField.addKeyListener(this);
btnNext.addActionListener(this);
panel.add(labelUsername);
panel.add(textField);
panel.add(btnNext);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
if(!textField.getText().equals("")){
total_test += 1;
if(isNumeric(textField.getText())){
//********************Correct Integer**********************
if(Integer.valueOf(imgNo[randomNo])==Integer.valueOf(textField.getText())){
//********************Correct Answer**********************
System.out.println("Correct");
sum+=1;
}else{
//********************Incorrect Answer**********************
System.out.println("Incorrect");
Error+=1;
}
refreshFrame();
}else{
//********************Incorrect Integer/Alphabet**********************
System.out.println("Invalid");
Error+=1;
refreshFrame();
}
}else{
System.out.println("Null Input");
}
//System.out.println(Integer.valueOf(imgNo[randomNo]));
}
public void refreshFrame(){
if(total_test>=10){
// add result page to see how many score
//Task2(sum, Error);
System.out.println("Correct: "+sum+" Incorrect: "+Error);
frame.dispose();
}else{
btnNext.removeActionListener(this);
frame.getContentPane().removeAll();
getContentPane().removeAll();
Task(inputID);
}
}
public static void main(String args[]) {
Task1 a = new Task1(inputID);
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
public static boolean isNumeric(String str)
{
try
{
Integer.valueOf(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
}
EDIT part (But some of the image is still repeating.)
Collections.shuffle(Arrays.asList(imgFileHP));
Set<Integer> uniqueList = new HashSet<Integer>();//This would create list with the number 0 to 9
for(int count=0;count<imgFileHP.length;count++){
uniqueList.add(count);
}
if(!uniqueList.isEmpty()){
index = (int) (Math.random() * (upper - lower)) + lower;
randomNo = index;
if(uniqueList.contains(index)){
labelUsername.setIcon(new ImageIcon(getClass().getResource("/image/" + imgFileHP[index])));
uniqueList.remove(index);//particular number is delete from the list so that duplicate images doesnt show up
System.out.println(imgFileHP[r]);//This printf statement is just for your reference
}
}
Here is how Random works. Even though you have mentioned rand.nextInt(10);but everytime it gets called, there is not pre-defined rule in java that it has to generate unique numbers and not the duplicate the previously generated ones.
For Example:
when you call -
int index = rand.nextInt(10); // Index could be 2
index = rand.nextInt(10); // Now again the value could be 2 as well
So what you need to do is you have to add an extra piece of code to check the uniqueness every time random is called.
Since you want to generate numbers between 0 to 10. Try the following code, it might help you understand.
String[] imgFileHP = {"1.jpg","3.jpg","4.jpg","7.jpg","9.jpg","10.jpg","12.jpg","16.jpg","17.jpg","18.jpg"};
int upper = imgFileHP.length;
int lower = 0;
int r=0;
int index=0;
Set<Integer> uniqueList = new HashSet<Integer>();//This would create list with the number 0 to 9
for(int count=0;count<imgFileHP.length;count++){
uniqueList.add(count);
}
if(!uniqueList.isEmpty()){
index = (int) (Math.random() * (upper - lower)) + lower;
if(uniqueList.contains(index)){
uniqueList.remove(index);//particular number is delete from the list so that duplicate images doesnt show up
System.out.println(imgFileHP[r]);//This printf statement is just for your reference
}
}
Another easier method is to use Collections.Shuffle as shown below:
Collections.shuffle(Arrays.asList(imgFileHP));
Example of Collection.shuffle().
Lets say you have an array String[] arr = {"abc","def","xyz","bla"}
when you do Collections.shuffle(Arrays.asList(arr));
then print array from index 0 to 3. Array might be shuffled something like this: {"def","bla","abc","xyz"}
**EDIT 2:**Solution based on your edit in main code:
for(int count=0;count<imgFileHP.length;count++){//first add the counters into List
uniqueList.add(count);
}
if(!uniqueList.isEmpty()){
index = (int) (Math.random() * (upper - lower)) + lower;
if(uniqueList.contains(index)){
labelUsername.setIcon(new ImageIcon(getClass().getResource("/image/" + imgFileHP[index])));
uniqueList.remove(index);//particular number is delete from the list so that duplicate images doesnt show up
System.out.println(imgFileHP[r]);//This printf statement is just for your reference
}
}
I'm currently working on a simple GUI system in Java using Swing and I am trying to edit a Passenger. The passenger is an object that is stored in an arrayList. There is inheritance involved so there is also multiple classes involved. The code I currently have for the edit method is for from perfect eg If/Elses may not actually work but all I require is advice on how to get the actual method going/working.
Firstly, the Passenger inherits its details from 3 classes, Person, Date and Name. The details of the passenger are the unique ID which auto increments, the Title, Firstname, Surname, DOB (Day, month, year), number of bags and priority boarding. Here is the code where the passenger inherits the details.
public Passenger(String t, String fN, String sn, int d, int m, int y, int noB, boolean pB)
{
// Call super class constructor - Passing parameters required by Person
super(t, fN, sn, d, m, y);
// And then initialise Passengers own instance variables
noBags = noB;
priorityBoarding = pB;
}
I then have a PassengerFileHandler class that has all the methods that I will need for the GUI aspect of things eg Add/Delete passenger etc etc. Here is my edit method that I have in my PassengerFileHandler class. This is most likely where the problem starts, I believe this is the correct way to make a method for the purpose of editing an object.
public Passenger editForGUI(int id, Passenger passenger)
{
for (Passenger passengerRead : passengers)
{
if (id == passengerRead.getNumber())
{
passengers.set(id, passenger);
}
}
return null;
}
I then go into my actual frame class that I have where I make the GUI and call the methods. To call the methods I made an instance of the passengerFileHandler class by typing the following
final PassengerFileHandler pfh = new PassengerFileHandler();
Here is where I make the Edit button and do the ActionListener for the JButton.
btnEditAPassenger.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
editPanel = new JPanel();
editPanel.setLayout(new GridLayout(9, 2));
editPanel.setPreferredSize(new Dimension(280, 280));
//Add radiobutton for priority
JRadioButton yes1 = new JRadioButton();
yes1.setText("Yes");
JRadioButton no1 = new JRadioButton();
no1.setText("No");
ButtonGroup group1 = new ButtonGroup();
group1.add(yes1);
group1.add(no1);
//Make an panel for the RadioButtons to be horizontal
radioButtonPanel1 = new JPanel();
radioButtonPanel1.setLayout(new GridLayout(1, 2));
radioButtonPanel1.setPreferredSize(new Dimension(40, 40));
radioButtonPanel1.add(yes1);
radioButtonPanel1.add(no1);
//title is a comboBox that is auto filled
editPanel.add(new JLabel("Title : "));
editPanel.add(editTitleComboBox = new JComboBox<String>());
editTitleComboBox.addItem("Mr");
editTitleComboBox.addItem("Ms");
editTitleComboBox.addItem("Mrs");
editTitleComboBox.addItem("Miss");
//Add the firstName textfield
editPanel.add(new JLabel("First name : "));
editPanel.add(editFirstNameText = new JTextField(20));
//Add the surname textfield
editPanel.add(new JLabel("Surname : "));
editPanel.add(editSurNameText = new JTextField(20));
//Day is a comboBox that is auto filled
editPanel.add(new JLabel("Day : "));
editPanel.add(editDayComboBox = new JComboBox<Integer>());
int days = 0;
for(int i = 0; i < 31; i++)
{
days++;
editDayComboBox.addItem(days);
}
//Month is a comboBox that is auto filled
editPanel.add(new JLabel("Month : "));
editPanel.add(editMonthComboBox = new JComboBox<Integer>());
int months = 0;
for(int i = 0; i < 12; i++)
{
months++;
editMonthComboBox.addItem(months);
}
//Year is a comboBox that is auto filled
editPanel.add(new JLabel("Year : "));
editPanel.add(editYearComboBox = new JComboBox<Integer>());
int yearNum = 2014 + 1 ;
for(int i = 1900; i < yearNum; i++)
{
editYearComboBox.addItem(i);
}
//NumberOfBags is a comboBox that is auto filled
editPanel.add(new JLabel("Number of Bags : "));
editPanel.add(editBagsComboBox = new JComboBox<Integer>());
int bags = 0;
for(int i = 0; i < 10; i++)
{
bags++;
editBagsComboBox.addItem(bags);
}
//Priority booking is a button group
editPanel.add(new JLabel("Priority boarding : "));
editPanel.add(radioButtonPanel1);
String input1 = JOptionPane.showInputDialog(null,"Enter the ID of the passenger you wish to edit: ");
if (input1 == null)
{
JOptionPane.showMessageDialog(null,"You have decided not to edit a Passenger");
}
if (input1.length() <1)
{
JOptionPane.showMessageDialog(null,"Invalid entry");
}
if (input1 != null)
{
// Put a Border around the Panel
editPanel.setBorder(new TitledBorder("Edit Passenger Details"));
//Make custom buttons
Object[] customButtonSet1 = {"Edit Passenger", "Cancel"};
int customButtonClick1 = JOptionPane.showOptionDialog(null,editPanel,"Edit", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, customButtonSet1, customButtonSet1[1]);
if(customButtonClick1 == JOptionPane.YES_OPTION)
{
try
{
if(pfh.passengers.contains(Integer.valueOf(input1)))
{
Passenger myObj = pfh.passengers.get(Integer.valueOf(input1));
//Passenger passenger1 = pfh.list().get(String.valueOf(pfh.passengers.equals(input1))))
//JOptionPane.showMessageDialog(null, "Succesfully edited the Passenger");
String title1 = String.valueOf(editTitleComboBox.getSelectedItem());
String firstName1 = String.valueOf(editFirstNameText.getText());
String surName1 = String.valueOf(editSurNameText.getText());
int day1 = Integer.valueOf(editDayComboBox.getSelectedItem().toString());
int month1 = Integer.valueOf(editMonthComboBox.getSelectedItem().toString());
int year1 = Integer.valueOf(editYearComboBox.getSelectedItem().toString());
int numBags1 = Integer.valueOf(editBagsComboBox.getSelectedItem().toString());
boolean priority1;
//Method to get the boolean
if(yes1.isSelected())
{
priority1 = true;
}
else
{
priority1 = false;
}
myObj.setName(new Name(title1, firstName1, surName1));
myObj.setDateOfBirth(new Date(day1, month1, year1));
myObj.setNoBags(numBags1);
myObj.setPriorityBoarding(priority1);
//Makes the toString clean
String formatedString = (pfh.passengers.toString().replace("[", "").replace("]", "").trim());
//refreshes the textArea and auto fills it with the current ArrayList
textArea.setText("");
textArea.append(formatedString);
}
else
{
JOptionPane.showMessageDialog(null, "Passenger does not exist");
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
else
{
JOptionPane.showMessageDialog(null, "Passenger does not exist");
}
if(customButtonClick1 == JOptionPane.CANCEL_OPTION || customButtonClick1 == JOptionPane.NO_OPTION)
{
JOptionPane.showMessageDialog(null, "You have decided not to Edit a Passenger");
}
}
}
catch (Exception ex)
{
// do nothing
}
}
});
I am pretty sure that one of the bigger issues is that when I do the code where I ask the user for the ID of the passenger they wish to edit it doesn't actually check if the Passenger exists correctly. I also understand that I don't actually even call the edit method but I couldn't get it working using the method either.
Here are images to help you understand what the GUI looks like and what the code may/may not be doing. Image 1 is the GUI and how it looks with the buttons. Image 2 is when you click the "Edit" button, the ID request pops up. Image 3 is where the user attempts to set the new passenger data.
Simple enough it's with strings but I think the issue is you don't know how to really use an arraylist.
public String[] currentArray = { "temp", "temp1", "temp3"};
public void addToList(String tobeadded) {
ArrayList<String> temp = new ArrayList<String>();
for(String s: currentArray) {
temp.add(s);
}
temp.add(tobeadded);
currentArray = temp.toArray(new String[temp.size()]);
}
public void removeFromList(String toRemove) {
ArrayList<String> temp = new ArrayList<String>();
for(String s: currentArray) {
if(!toRemove.equals(s))
temp.add(s);
}
currentArray = temp.toArray(new String[temp.size()]);
}
public void edit(String orginal, String new1) {
ArrayList<String> temp = new ArrayList<String>();
for(String s: currentArray) {
if(!orginal.equals(s))
temp.add(s);
}
temp.add(new1);
currentArray = temp.toArray(new String[temp.size()]);
}
i am not sure about your editForGUI method a it is not very clear. I am assuming that when you update the passenger details and click on edit passenger, it should update list.. If that is the case then try this..
If you are using updatedPassenger and Passsenger list as parameters in your method then the following will work
`
void editForGUI(Passenger updatedObject, List passengers){
for(int i=0; i<passengers.size; i++){
Passenger p = passengers.get(i);
if( p.getId() == updatedPassenger.getId()){
passengers.set(i, updatedObject);
return;
}
}
}
`
Why don't you use HashMap in place of list? In-place update would be more efficient. id will be key and Passenger object will be the value in HashMap..
I believe your ArrayList problem is in this line:
passengers.set(id, passenger);
At this point, you have found the passenger that matches the id and you want to replace it. If you take a look at the ArrayList documentation, the method signature for set is
set(int index, E element)
The first parameter you pass is the index you want to set, not the id. However, since you used the enhanced for loop to iterate through the ArrayList, you don't know the index. You can call the indexOf() method to get the index using the passenger that you found, but that would be inefficient since you just iterated through the array and the method call would basically repeat everything you just did to get the index. Instead you can keep a counter that increments after the if check, and once you have found it, the counter is set to the index of your item. Inside your if block, you can immediately set your passenger using that index and return right after.
For a school project, I created the following program:
BlckJckUI.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class BlckJckUI {
public static void main(String args[])
{
JFrame GUI = new JFrame("Blackjack Advisor");
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setSize(800,800);
GUI.setVisible(true);
ImageIcon Ace = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\Ace.jpg");
JButton ace = new JButton(Ace);
ace.setSize(300, 100);
ace.setLocation(100, 100);
ace.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
if (array.playerhandtotal <= 21)
{
math.cardvalue = 11;
}
else
{
math.cardvalue = 1;
}
array.clicktracker++;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(ace);
ImageIcon Two = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\2.jpg");
JButton two = new JButton(Two);
two.setSize(300, 100);
two.setLocation(100, 200);
two.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 2;
array.clicktracker++;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(two);
ImageIcon Three = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\3.jpg");
JButton three = new JButton(Three);
three.setSize(300, 100);
three.setLocation(100, 300);
three.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 3;
array.clicktracker++;
;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(three);
ImageIcon Four = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\4.jpg");
JButton four = new JButton(Four);
four.setSize(300, 100);
four.setLocation(100, 400);
four.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 4;
array.clicktracker++;
;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(four);
ImageIcon Five = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\5.jpg");
JButton five = new JButton(Five);
five.setSize(300, 100);
five.setLocation(100, 500);
five.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 5;
array.clicktracker++;
;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(five);
ImageIcon Six = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\6.jpg");
JButton six = new JButton(Six);
six.setSize(300, 100);
six.setLocation(900, 100);
six.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 6;
array.clicktracker++;
;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(six);
ImageIcon Seven = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\7.jpg");
JButton seven = new JButton(Seven);
seven.setSize(300, 100);
seven.setLocation(900, 200);
seven.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 7;
array.clicktracker++;
;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(seven);
ImageIcon Eight = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\8.jpg");
JButton eight = new JButton(Eight);
eight.setSize(300, 100);
eight.setLocation(900, 300);
eight.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 8;
array.clicktracker++;
;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(eight);
ImageIcon Nine = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\9.jpg");
JButton nine = new JButton(Nine);
nine.setSize(300, 100);
nine.setLocation(900, 400 );
nine.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 9;
array.clicktracker++;
;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(nine);
ImageIcon Ten = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\ten.jpg");
JButton ten = new JButton(Ten);
ten.setSize(300, 100);
ten.setLocation(900, 500);
ten.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 10;
array.clicktracker++;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(ten);
JButton start = new JButton("Start/Reset");
start.setSize(300, 100);
start.setLocation(500,500);
start.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
;
Arrays array = new Arrays();
array.playerhand.clear();
array.dealer = 0;
array.clicktracker = 0;
array.playerhandtotal = 0;
array.result = null;
JOptionPane.showMessageDialog(null,"Please select the card \nthat the dealer is showing :)");
}
});
GUI.add(start);
GUI.setLayout(null);
GUI.pack();
//start.setSize(somethinghere);
//start.setLocation(Somethinghere);
}
}
Math.java
public class Math
{
public int cardvalue;
public Math()
{
Arrays array = new Arrays();
if (array.clicktracker == 1)
{
array.dealer = cardvalue;
array.result = "Please select the first card you have :)";
}
else if (array.clicktracker == 2)
{
array.playerhand.add(cardvalue);
array.result = "Please select the second card you have :)";
}
else if (array.clicktracker >= 3)
{
array.playerhand.add(cardvalue);
if (array.playerhandtotal <= 8)
{
// array.result = result statement
array.result = "You should just hit until you're safe. If the dealer 6 or below,\n"
+ " the chances are that he'll bust and if not, remain low above 17.\n"
+ " As long as you can pull a 17 or higher, you should be safe. Pick \n"
+ "another card or reset.";
}
else if (array.playerhandtotal == 9)
{
if (3 <= array.dealer && array.dealer <= 6)
{
array.result = "Double down. The chances of him busting is high,\n"
+ "chances of him not having a high total is high as well. \n"
+ "Chances you'll get a 10 is high as well. Pick another card or reset.";
}
else
{
array.result = "Your best option is to Hit, and it's a luck thing from there. The dealer has some room with a 2; it's highly likely for him to get right below 21 and well above 16, and given that you'll have to beat him in the end, you have to hit until you're high. With 7 plus, he's set: He gets a 10 and he can stop, and again in the end, you'll have to beat his score. May the Goddess of Luck favor you, because you'll need it. Pick another card or reset.";
}
}
else if (array.playerhandtotal == 10)
{
if (2 <= array.dealer && array.dealer <= 9)
{
array.result = "Double down, since Assumption Rule wins out in your favor, if you have a 10, you're golden. The dealer has very little chance of beating you: chances are that he busts or loses to your almighty 20. Even if you bust, the chance that he busts is sufficiently high as well. Very unlikely for him to get 21. Pick another card or reset.";
}
else
{
array.result = "Hit. Dealer is in green zone, Assumption Rule states that he'll get a 20 or 21. Gotta beat him, no way around it. Hope for the best. A double will never cut it, since you're gambling on 1 card to get 20-21. Better safe than sorry. Pick another card or reset.";
}
}
else if (array.playerhandtotal == 11)
{
if (2 <= array.dealer && array.dealer <= 10)
{
array.result = "Double down, since Assumption Rule wins out in your favor, if you have a 10, you're golden. The dealer has very little chance of beating you: chances are that he busts ors loses to your almighty 21. Even if you bust, the chance that he busts is sufficiently high as well. Pick another card or reset.";
}
else
{
array.result = "Hit. He's going to have a 10 due to Assumption Rule. You may as well, but remember, you're less likely to. Thus, hit to be safe. You have to beat to win, and if you Double Down, you lock yourself into a position where the chances of you beating the dealer is slim. (At least, slimmer than hitting.) Pick another card or reset.";
}
}
else if (array.playerhandtotal == 12)
{
if ((array.dealer == 2 || array.dealer == 3) || (array.dealer >= 7))
{
array.result = "Hit. You're likely to lose anyways, per the Assumption Rule. However, there's always a chance that you won't. Doubling makes no sense, and it will reduce your chance of winning. The dealer has some room with a 2; it's highly likely for him to get right below 21 and well above 16, and given that you'll have to beat him in the end, you have to hit until you're high. With 7 plus, he's set: He gets a 10 and he can stop, and again in the end, you'll have to beat his score. Pick another card or reset.";
}
else
{
array.result = "Stand. You have a high chance of bust, but the dealer does as well. If you stay, chances are, dealer will bust. Pick another card or reset.";
}
}
else if (13 <= array.playerhandtotal && array.playerhandtotal <= 16)
{
if (array.dealer >= 7)
{
array.result = "Hit. Might as well. Chances are against you severely, but you still have to play on chance. Hitting is the safest option. Pick another card or reset.";
}
else
{
array.result = "Stand. Dealer may bust; ride on that chance. Pick another card or reset.";
}
}
else if (17 <= array.playerhandtotal && array.playerhandtotal <= 21)
{
array.result = "Stand. You're golden. Just hope for the best and let Lady Luck work her magic. Rest please.";
}
else if (array.playerhandtotal >= 22)
{
array.result = " Oi. You've busted. Reset please.";
}
}
}
}
Arrays.java
import java.util.*;
public class Arrays
{
public String result;
ArrayList<Integer> playerhand = new ArrayList<Integer>();
public int dealer = 0;
public int clicktracker = 0;
public int playerhandtotal = 0;
{
for (int element: playerhand)
{
playerhandtotal = element + playerhandtotal;
}
}
}
The program is supposed to be a Black Jack Advisory tool, and when you click "start/reset" it should ask you to click 1 card (which is the card that the dealer shows.) When you click a card , it then asks you to click the first card you have. When you click that, it then asks for your second card, etc. etc.
When you click start, it works fine, however, when you click ANY of the number cards, the JOptionPanel doesn't say anything.
I'm pretty sure this is because the value of the string its supposed to put out is "null," which I don't want it to be.
How do I make it so that it takes the value of array.result in the if-else statements?
Check your Arrays class. Your missing a method definition around your for statement. And my best guess is to give your result variable a default empty value ->
public String result = "";
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
public class vasilisTable extends JFrame {
Object[] split_data_l;
Object[][] split_data;
Object [][] split_data_clone;
Object [][] split_data_reverse;
Object [][] split_data_reverse_num;
String[] temp;
private JTable table;
private JPanel bottom_panel;
private JLabel average;
private JLabel max_dr;
public vasilisTable(String name, String data, int choice)
{
super(name);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //the DISPOSE_ON_CLOSE means that when we press the x button is will close only the table window and not the whole programm
//this.getAccessibleContext().setAccessibleName(name);
//System.out.println(this.getAccessibleContext().getAccessibleName());
setSize(800,600);
String[] columnNames = {"Date", "Open","High","Low","Close",
"Volume", "Adjusted" };//defines the column names
//------ Start of making the arrays that will be used as data for the table creation
split_data_l = data.split( "\n" );
int lngth = split_data_l.length;
split_data = new Object[lngth-1][7];
split_data_clone = new Object[lngth-1][7];
split_data_reverse= new Object[lngth-1][7];
split_data_reverse_num= new Object[lngth-1][7];
double sum = 0;
for(int k=1; k<split_data_l.length; k++) //initializing the three arrays with the data we got from the URLReader
{
temp = split_data_l[k].toString().split(",");
for (int l=0; l<temp.length; l++)
{
split_data[k-1][l] = temp[l];
split_data_clone[k-1][l] = temp[l];
split_data_reverse[k-1][l] = temp[l];
split_data_reverse_num[k-1][l] = temp[l];
}
}
for(int k=split_data_l.length-2; k>=1; k--) // making of the clone array that contains all the last column with colours
{
Double temp = Double.parseDouble(split_data[k][6].toString());
Double temp1 = Double.parseDouble(split_data[k-1][6].toString());
double check =temp-temp1;
if (check>0)
{
String color_temp = "<html><span style = 'color:red'>" + split_data_clone[k-1][6] +"</span></html>" ;
split_data_clone[k-1][6] = color_temp;
}
else
{
String color_temp = "<html><span style = 'color:green'>" +split_data_clone[k-1][6]+"</span></html>" ;
split_data_clone[k-1][6] = color_temp;
}
}
int l = split_data_clone.length;
int m = l-1;
for (int i=0; i<l; i++) //making of the reversed array
{
for (int j = 0; j<=6; j++)
{
split_data_reverse[i][j]=split_data_clone[m][j];
}
m--;
}
m = l-1;
for (int i=0; i<l; i++) //making of the reversed array
{
for (int j = 0; j<=6; j++)
{
split_data_reverse_num[i][j]=split_data[m][j];
}
m--;
}
//------ End of making the arrays that will be used as data for the table creation
//------ Start of calculating the average
for (int i=0; i<lngth-1; i++)
{
Double temp = Double.parseDouble(split_data[i][6].toString());
sum = sum+temp;
//System.out.println("turn "+i+" = "+split_data[i][6]);
}
float avg = (float) (sum/(lngth-1));
avg = Round((float) avg,2);
String avg_str;
avg_str = "<html>Average: <b>"+avg+"</b></html>";
//"<html><b>Average: </b></html>"
//------ End of calculating the average
//------ Start of Calculating the Maximal Drawdown
double high=0;
double low=100000000;
double drawdown=0;
double max_drawdown=0;
int last_high=0;
int last_low=0;
for (int i=0; i<lngth-1; i++)
{
Double temp = Double.parseDouble(split_data_reverse_num[i][6].toString());
//Double temp1 = Double.parseDouble(split_data[i+1][6].toString());
if (temp>high)
{
high = temp;
last_high = i;
//System.out.println("max high = "+temp);
}
else
{
low = temp;
last_low = i;
//System.out.println("max low = "+temp);
}
if (last_low>last_high)
{
drawdown = high-low;
//System.out.println("drawdown = "+drawdown);
}
if (drawdown>max_drawdown)
{
max_drawdown = drawdown;
}
}
//System.out.println("max dr = "+max_drawdown);
String max_dr_str = "<html>Maximal Drawdown: <b>"+max_drawdown+"</b></html>";
//------ End of Calculating the Maximal Drawdown
average = new JLabel(avg_str);
max_dr = new JLabel(max_dr_str);
bottom_panel = new JPanel();
String space = " ";
JLabel space_lbl = new JLabel(space);
bottom_panel.add(average);
bottom_panel.add(space_lbl);
bottom_panel.add(max_dr);
//-------- Start of table creation ---------
if(choice==1)
{
table = new JTable(split_data_clone, columnNames);//creates an instance of the table with chronological order
}else
{
table = new JTable(split_data_reverse, columnNames);//creates an instance of the table with reverse chronological order
}
TableColumn column = null;
for (int i = 0; i < 7; i++) {
column = table.getColumnModel().getColumn(i);
if (i == 0) {
column.setPreferredWidth(100); //third column is bigger
} else if (i == 5) {
column.setPreferredWidth(85); //third column is bigger
}
else if (i == 6) {
column.setPreferredWidth(70); //third column is bigger
}
else {
column.setPreferredWidth(50);
}
}
table.setShowGrid(true);
table.setGridColor(Color.black);
//-------- End of table creation ---------
JPanel table_panel = new JPanel (new BorderLayout());
JScrollPane table_container = new JScrollPane(table); // create a container where we will put the table
//table.setFillsViewportHeight(true); // if the information are not enough it still fill the rest of the screen with cells
table_panel.add(table_container, BorderLayout.CENTER);
table_panel.add(bottom_panel, BorderLayout.SOUTH);
//table_panel.add();
setContentPane (table_panel);
pack(); // here i pack the final result to decrease its dimensions
}
public float Round(float Rval, int Rpl) // this functions rounds the number to 2 decimal points
{
float p = (float)Math.pow(10,Rpl);
Rval = Rval * p;
float tmp = Math.round(Rval);
return (float)tmp/p;
}
}
I am making an application which creates various instances of a class. These instances are actually some windows. After having create multiple of these windows, how can I access one of them and bring it in front? I know the .tofront() method, but how can I specify the window that I want to bring in front?
Above is the code that creates every window. My main problem is that after I have create e.g 5 windows, how can I access one of them?
ps
code that creates each window:
if (sData != null) {
//System.out.println("Success, waiting response");
vasilisTable ftable = new vasilisTable(name, sData, choice);
hashMap.put(name, ftable);
ftable.setVisible(true);
//choice=2;
}
My main problem is that after I have create e.g 5 windows, how can I access one of them?
You have to keep a reference to the relevant objects in variables or an array or a collection or something. The "bring it to the front" function needs to:
figure out what domain object needs to be brought to the front,
lookup its corresponding JFrame, and
call toFront() on it.
Java provides no built-in mechanisms for finding previously created instances of objects.
When you create your various instances of the above JFrame, you can keep track of the created instances, may be store them within a HashMap, then you can pick the right JFrame instance basing on its designated name and bring it to the front. Have a look at the below code for more illustration:
HashMap<String, VasilisTable> hashMap = new HashMap<String, VasilisTable>();
JFrame firstWindow = new VasilisTable("firstWindow",data, choice);
hashMap.put("firstWindow", firstWindow);
JFrame secondWindow = new VasilisTable("secondWindow",data, choice);
hashMap.put("secondWindow", secondWindow);
JFrame thirdWindow = new VasilisTable("thirdWindow",data, choice);
hashMap.put("thirdWindow", thirdWindow);
// To bring a certain window to the front
JFrame window = hashMap.get("firstWindow");
window.setVisible(true);
window.toFront();
Are these JFrame or JWindow objects? If they are you can call -
jframe.setVisible(true);
jframe.toFront();
This is something interesting I found at the API doc.
Places this Window at the top of the stacking order and shows it in
front of any other Windows in this VM. No action will take place if
this Window is not visible. Some platforms do not allow Windows which
own other Windows to appear on top of those owned Windows. Some
platforms may not permit this VM to place its Windows above windows of
native applications, or Windows of other VMs. This permission may
depend on whether a Window in this VM is already focused. Every
attempt will be made to move this Window as high as possible in the
stacking order; however, developers should not assume that this method
will move this Window above all other windows in every situation.
I would recommend you to check out these answers as well.
Java Swing: JWindow appears behind all other process windows, and will not disappear
Java: How can I bring a JFrame to the front?