Access already running objects - Java - java

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?

Related

Custom java calculator troubleshooting

New programmer here, I have been working for a few days on this bit of code that is meant to create a UI where I input a basement's perimeter length (textfield integer), if a new pump is needed (combobox string), if there is an outlet nearby (combobox string), and how many hours It will take to prepare a site (textfield integer), and I calculate my costs to complete a job. I was able to set up a UI where I can enter the inputs and press a button to calculate but I'm having trouble connecting the button I made to the formula I made to generate a price. Here is my code:
package packagepackage;
import packagepackage.HintTextFieldUI;
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CP_GUI implements ActionListener {
String[] sumpo = {"New sump pump","Existing sump pump"};
String[] electo = {"There is an outlet within 6 feet of sump pump","There is no outlet nearby, or I do not need a new one"};
Integer estimatex = 0;
String esto = String.valueOf(estimatex);
public volatile String estimatoof = "Estimated Cost: ${}".format(esto);
private JComboBox sump = new JComboBox(sumpo);
private JComboBox elec = new JComboBox(electo);
private JTextField linear = new JTextField();
private JTextField prep = new JTextField();
private JLabel title = new JLabel("Drain Tile Calculator");
private JButton calculate = new JButton("Calculate!");
public JLabel estimate = new JLabel(estimatoof);
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
public CP_GUI() {
linear.addActionListener(this);
calculate.addActionListener(this);
elec.addActionListener(this);
sump.addActionListener(this);
prep.addActionListener(this);
// the panel with the button and text
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(400, 400, 100, 100));
panel.setLayout(new GridLayout(0, 1));
panel.add(linear);
panel.add(sump);
panel.add(elec);
panel.add(prep);
frame.add(panel, BorderLayout.CENTER);
panel.add(title);
calculate.addActionListener(this);
panel.add(calculate);
// set up the frame and display it
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Drain Tile Calculator");
frame.pack();
frame.setVisible(true);
linear.setUI(new HintTextFieldUI("Perimeter length", true));
prep.setUI(new HintTextFieldUI("Hours of preptime", true));}
// create one Frame
public static void main(String[] args) {
new CP_GUI();
}
#Override
public void actionPerformed(ActionEvent e){
// TODO Auto-generated method stub
if(e.getSource()==linear) {String input = linear.getText();
Integer pars = Integer.parseInt(input);
Integer distVar = pars *= 13;
estimatex += distVar;
} else if (e.getSource()==sump) {String inputa = sump.getToolTipText();
int sumpa = 0;
if(inputa == "New sump pump" | inputa == "yes") {
sumpa += 260;}
estimatex += sumpa;
} else if (e.getSource()==elec) {String inputb =elec.getToolTipText();
int eleca = 0;
if("There is an outlet within 6 feet of the sump pump".equals(inputb)) {
eleca += 1;
}
eleca *= 280;
estimatex += eleca;
}
else if (e.getSource()==prep) {String inputc = prep.getText();
int parsa = Integer.parseInt(inputc);
int prepCost = parsa += 1;
prepCost *= 110;
estimatex += prepCost;
} else if (e.getSource()==linear) {
String disto = linear.getText();
int di = Integer.parseInt(disto);
di *= 13;
String pumpo = (String)sump.getSelectedItem();
int sumpo = 0;
if ("New sump pump".equals(pumpo)) {
sumpo += 260;
}
String ele = (String)elec.getSelectedItem();
int elc = Integer.parseInt(ele);
elc *= 280;
String clea = prep.getText();
int cla = Integer.parseInt(clea);
cla += 1;
cla *= 110;
int cali = 0;
cali += di;
cali += sumpo;
cali += elc;
cali += cla;
estimatex = cali;
}
}
}
Edit: Made the suggested edits made so far and now the UI opens and works, the only issue is that the estimated price does not show up. Am I connecting the action listener correctly?
Your "primary" problem is right here...
String disto = String.valueOf(linear);
where linear is a JTextField, so the above call will generate something like...
javax.swing.JTextField[,0,0,0x0,invalid,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=com.apple.laf.AquaTextFieldBorder#4e323305,flags=288,maximumSize=,minimumSize=,preferredSize=,caretColor=javax.swing.plaf.ColorUIResource[r=0,g=0,b=0],disabledTextColor=javax.swing.plaf.ColorUIResource[r=128,g=128,b=128],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=com.apple.laf.AquaImageFactory$SystemColorProxy[r=0,g=0,b=0],selectionColor=com.apple.laf.AquaImageFactory$SystemColorProxy[r=165,g=205,b=255],columns=0,columnWidth=0,command=,horizontalAlignment=LEADING]
which is obviously not what you're looking for.
You should probably be just doing something like...
String disto = linear.getText();
pumpo == "New sump pump" is also not how you compare a String in Java, you should be using "New sump pump".equals(pumpo) ... but I suspect you're going to have the same issues as mentioned above.
I really recommend you take the time to read through Creating a GUI With Swing as well as taking the time to come to grips with the core basics of the language

Java: Waiting for a mouseClickedEvent

I am writing a program where users answer questions by clicking on JTable cells. If the question is answered correctly/incorrectly, the MouseListener changes the value of answeredResult. The program will keep running until there are no available questions (the available array list contains a list of Items, which is a class I created that contains strings event, year, and description, called by getEvent(), getYear(), and getDescription() methods respectively). However, for each question, I want to wait until a mouseClickedEvent is detected before executing the proceeding code (see below).
I know that adding another while loop for waiting is really bad. I've also seen
some answers suggesting to put whatever I want to do in the mouseClicked method, but I don't know how in my case, since I want to repeat it multiple times.
I think another problem is that the program is stuck in the while(available.size()!=0) loop. So it cant detect the mouse click.
Any suggestions on how to make this work?
ArrayList<Item> available = new ArrayList<Item>();
for(int i = 0; i < 5; i++){
available.add(new Item("Event " + i, "Year " + i, "Description " + i));
}
JTable table = new JTable(model);
table.addMouseListener(new java.awt.event.MouseAdapter() {
#Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
int row = table.rowAtPoint(evt.getPoint());
int col = table.columnAtPoint(evt.getPoint());
if (row >= 0 && col == 2 && canPlay) {
clickedYear = (String)data[row][col];
if(clickedYear.equals(answerYear)){
answeredResult = 1;
}else{
answeredResult = -1;
}
}
}
});
while(available.size()!=0){
promptPanel.removeAll();
answeredResult = 0; //0-unanswered 1-correct 2-incorrect
int random = (int)(Math.random()*(available.size()-1));
JLabel label = new JLabel(available.get(random).getEvent()+"\n");
promptPanel.add(label);
canPlay = true;
//wait for mouse clicked before proceeding to the next code
if(answeredResult == 1){
JLabel correct = new JLabel("Correct!");
promptPanel.add(correct);
}else if(answeredResult == -1){
JLabel wrong = new JLabel("Wrong.");
promptPanel.add(wrong);
}
revalidate();
repaint();
available.remove(random);
}

Java Connect4 Game with GUI bug issues

http://imgur.com/a/V7LPP
Grid images are in the link
I have 2 main issues with my current connect4 code, sometimes the "AI" places 2 discs in one turn and the player can't fill the entire board without the "AI" entering an infinite loop. Any help is appreciated.
/**
* Auto Generated Java Class.
*/
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class EmptyFrame1 implements ActionListener
{
//Array of JButtons
static JButton [] mnuBtn = new JButton[2];
static JButton [] btnArray = new JButton[7];
static JLabel [][] board = new JLabel[6][7];
static int [][] numBoard = new int[6][7];
static int choice = 0;
static int playerColour = 1;
static int computerColour = 2;
static int computerTurn = 0;
static ImageIcon emptyGrid = new ImageIcon("EmptyGrid.png");
static ImageIcon yellowGrid = new ImageIcon("YellowGrid.png");
static ImageIcon redGrid = new ImageIcon("RedGrid.png");
static JPanel pnlBoard;
static boolean validTurn;
static int pieceCount = 42;
public EmptyFrame1()
{
JFrame game = new JFrame("Connect 4");
//mainFrame panel to hold all components
JPanel mainFrame = new JPanel();
pnlBoard = new JPanel();
pnlBoard.setLayout(new GridLayout(7,6));
//Change mainFrame layout to vertical BoxLayout
mainFrame.setLayout(new BoxLayout(mainFrame, BoxLayout.Y_AXIS));
//For every single button
//Set the button text to its index value, add an action listener and add it to the pnlButtons
for (int i = 0; i < btnArray.length; i++)
{
btnArray[i] = new JButton("place");
btnArray[i].addActionListener(this);
pnlBoard.add(btnArray[i]);
}//end for
for (int r = 0; r < board.length; r++)
{
for (int c = 0; c < board[r].length; c++)
{
board[r][c] = new JLabel(emptyGrid);
board[r][c].setPreferredSize(new Dimension(69, 69));
pnlBoard.add(board[r][c]);
}//end for
}//end for
//Add all the panels to the mainFrame panel
mainFrame.add(pnlBoard);
//add mainFrame to the JFrame
game.add(mainFrame);
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Added this for security
game.pack();
game.setVisible(true);
game.setResizable(false);
}
//*Action listener for all buttons*
public void actionPerformed(ActionEvent e)
{
for (int i = 0; i < btnArray.length; i++)
{
//if the current button was triggered, set the choice to the button index
if (btnArray[i] == e.getSource())
{
choice = i;
colCheck(choice, 1);
//System.out.println("User turn used");
pieceCount--;
for (int j = 0; j < btnArray.length; j++)
{
if (numBoard[0][j] == 0) btnArray[j].setEnabled(true);
}
if (pieceCount > 0)
{
validTurn = false;
while(!validTurn)
{
computerTurn = (int) (Math.random() * 7);
System.out.print(computerTurn + " ");
validTurn = colCheck(computerTurn, 2);
//System.out.println("CPU tried to move");
}
}
System.out.println();
setGrid();
pieceCount--;
System.out.println(pieceCount);
validTurn = false;
}//end if
}//end for
pnlBoard.repaint();
}//end actionPerformed
public static boolean colCheck(int choice, int currentTurn)
{
int row = -1;
for (int r = 5; r >= 0; r--)
{
if (numBoard[r][choice] == 0)
{
row = r;
break;
}
}
//System.out.println("Row That CPU Chooses: " + row);
if (row > -1)
{
numBoard[row][choice] = currentTurn;
if (row == 0)
{
btnArray[choice].setEnabled(false);
return false;
}
return true;
}
return false;
}
public static void setGrid()
{
for (int r = 0; r < numBoard.length; r++)
{
for (int c = 0; c < numBoard[r].length; c++)
{
if (numBoard [r][c] == 0)
{
board[r][c].setIcon(emptyGrid);
}
else if (numBoard [r][c] == 1)
{
board[r][c].setIcon(redGrid);
}
else if (numBoard [r][c] == 2)
{
board[r][c].setIcon(yellowGrid);
}
}
}
}
/**
* Inner helper class that defines the graphics
*/
public static void main(String[] args)
{
new EmptyFrame1();
}
//end constructor
Some problems and suggestions:
Your colCheck method and the while (!validTurn) { loop in the actionPerformed method is where the problem is located.
This method should not set numBoard value or disable buttons. In other words, it should not have any "side effects".
Instead it should only check for validity and then return a boolean value, nothing more or less
You should have another method that is called first, one that checks if no valid columns are available, if the game is effectively over. This should be called before the while loop above and should prevent the while loop from entering. This will end your endless loop problem because it's looping because no valid columns can be found for the computer turn.
You should have another method for setting the numBoard state and for enabling and disabling JButtons.
Change your colCheck to this to see where the loop is coming from:
public static boolean colCheck(int choice, int currentTurn) {
int row = -1;
for (int r = 5; r >= 0; r--) {
if (numBoard[r][choice] == 0) {
row = r;
break;
}
}
// System.out.println("Row That CPU Chooses: " + row);
if (row > -1) {
numBoard[row][choice] = currentTurn;
if (row == 0) {
btnArray[choice].setEnabled(false);
System.out.printf("debug 1 row %d %n", row);
return false;
}
System.out.printf("debug 2 row %d %n", row);
return true;
}
System.out.printf("debug 3 row %d %n", row);
return false;
}
Other issues not directly related to your problem at hand, but which should be addressed
You're grossly over-using the static modifier, and in fact none of your fields should be static. All should be private instance fields.
You've got your program logic code, the model, mixed in the same class as the GUI, the view, making it hard to debug problems and enhance the program. Much better if you could make your model a completely separate class, one that is "view-agnostic" meaning that it is testable on its own and can work with any view, be it a command line or Swing or Android UI.
Your question depends on images, EmptyGrid.png, YellowGrid.png.... that we have no access to, preventing us from testing it.
You're using magic numbers, such as 0, 1, 2 for position values, and need to avoid doing this.
Instead use an enum for empty, user and computer
This is Java not Javascript. You'll want to be clear on the difference because they're two completely different languages.

Edit an object in an ArrayList (Java Swing/GUI)

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.

how to add label to hangman game

these are my code I've problem with label when i read line from the text filed i can add the labels "_" that they are equal to the size of the word the program road it before.
I've problem creating label , I hope you understand my problem & please if you can can you give me a solution ?
public class HangGame extends JFrame {
JLabel lbl;
JLabel word ;
private String[]myword = new String [20];
Game() {
}
void readfile () {
Properties prob = new Properties();
try{
for(int x=0; x<n; x++){
}
}}
private void initLabelPanel() {
//craete array of labels the size of the word
letterHolderPanel = new JPanel();
int count =0;
//if you run my code I've problem with this array [myword.length()] the compiler can not find it.
wordToFindLabels = new JLabel[myword.length()];
//Initiate each labels text add tp array and to letter holder panel
for (int i = 0; ih; i++) {JLabel lbl = new JLabel("_");
letterHolderPanel.add(lbl);
lbl.setBounds();
}
}
}
myword is an array of Strings, not a single String so you need to replace:
wordToFindLabels = new JLabel[myword.length()];
with
wordToFindLabels = new JLabel[myword.length];
You could rename the variable to, say, mywordArray, to avoid confusion.
Also use a layout manager rather than using absolute positioning(null layout).
See: Doing Without a Layout Manager (Absolute Positioning)
length is property not method change the code accordingly
wordToFindLabels = new JLabel[myword.length];
and now youre code will be
for (int i = 0; i < wordToFindLabels.length; i++) {
String labelValue="";
if(myword[i] != null) {
for (int j = 0; j < myword[i].length(); j++){
labelValue+="_"
}
}
JLabel lbl = new JLabel(labelValue);
wordToFindLabels[i] = lbl;
letterHolderPanel.add(lbl);
lbl.setBounds(30, 60, 20, 20);
}

Categories

Resources