Java: Waiting for a mouseClickedEvent - java

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);
}

Related

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.

Why is my program not cycling through the array

I have tried a bunch of arrangements for my code, and this is my last version of code. I am trying to create a window, that will cycle through my 5 questions, and the end it will display how many you got correct.
Currently after entering my first answer in the text field it jumps to the end of the array. After that it will continually stay on the same question.
Sorry if I have made many coding errors, as this is my first time creating a program after watching a bunch of tutorials. Thanks for any help!
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class testwin extends JFrame {
private JTextField input;
private JLabel problem;
private String[] questions = new String[5];
private String[] answers = new String[5];
private String[] response = new String[5];
private int total = 5;
private int result = 0;
private String mark;
public testwin(){
super("Pop Quiz");
setLayout(new FlowLayout());
questions[0] = "Solve for x \t (x + 3)*2-10 = 4";
questions[1] = "Factorize \t x^2 + 10x + 21";
questions[2] = "Find the square root of 64";
questions[3] = "Multiply 23 and 94";
questions[4] = "Add 2145, 1452, 253,1414";
answers[0] = "4";
answers[1] = "(x + 3)(x + 7)";
answers[2] = "8";
answers[3] = "2162";
answers[4] = "5264";
problem = new JLabel(questions[0]);
add(problem);
input = new JTextField("Answer goes here",20);
add(input);
mark = String.format("You got %s correct out of %s", result,total);
input.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
int y = 0;
int x = 0;
if(event.getSource() == input){
while(x < questions.length){
problem.setText(questions[x]);
response[y] = String.format("%s",event.getActionCommand());
input.setText("Answer goes here");
x++;
y++;
}
}
if(x == 4)
JOptionPane.showMessageDialog(null, mark);
for(int z = 0; z < questions.length; z++){
if(response[z] == answers[z])
result++;
}
}
}
);
add(input);
setSize(250,250);
setVisible(true);
}
}
During each actionPerformed call you cycle through the whole list. Here:
while(x < questions.length){
problem.setText(questions[x]);
response[y] = String.format("%s",event.getActionCommand());
input.setText("Answer goes here");
x++;
y++;
}
So by the time the text is actually displayed again, you have set to it to each different question, but stop with the last one and that is what the user actually sees. You only want to change the text once, to the next question, everytime an action is performed.
You'll need to keep some sort of counter for which question you are on that can be accessed by the actionPerformed method
Also, as mentioned in the comments, you will want to change your result checking to use the equals method. Strings can't be compared using the == sign because for Strings == compares the reference each String object is pointing to, not the value of the String object
if(response[z].equals(answers[z]))
result++;
The issue is the while() loop inside your ActionListener, it will always iterate through the entire set of questions and finish at the last entry. This is due to the fact that your x and y variables are local to the scope of the ActionListener, and as such, are always reset to 0 and looped on each input click.
To fix this, you don't need a while loop, just make your x variable a private class field (questionIndex), use an if statement ensure the index is within the array bounds, and update the problem and response values accordingly.
Here's some psuedocode that should do the right thing:
private int questionIndex = 0;
public void actionPerformed(ActionEvent event){
if(event.getSource() == input){
if(questionIndex < questions.length){
problem.setText(questions[questionIndex]);
response[questionIndex] = String.format("%s",event.getActionCommand());
input.setText("Answer goes here");
questionIndex++;
}
...
}
}

Product Delete button not responding well

I got an application in the make here and working on a basket.
This is the button (everytime a product gets added it gets a X delete button):
for(int i=0;i < products.size(); i++){
btnDeleteproduct = new JButton("X");
btnDeleteproduct.setBounds(380, verticalPosition + i * productOffset, 20, 20);
btnDeleteproduct.setFont(WinkelApplication.FONT_10_BOLD);
btnDeleteproduct.setName("" + i);
btnDeleteproduct.addActionListener(this);
this.add(btnDeleteproduct);
}
productamount is to set up the label aantal with the amount of products:
productamount = (int) WinkelApplication.getBasket().getProductAmount(productdelete);
if (event.getSource() == btnDeleteproduct) {
productamount--;
lblamount.setText("" + productamount);
WinkelApplication.getInstance().showPanel(new view.Payment());
if (productamount < 1) {
WinkelApplication.getBasket().deleteProduct(productdelete);
}
}
Now the last batch is the deleteProduct method:
public void deleteProduct(Product product) {
// check if product is allready added to the basket
if (products.containsKey(product)) {
products.remove(product);
WinkelApplication.getInstance().showPanel(new view.Payment());
}
if(products.size() == 0){
WinkelApplication.getInstance().showPanel(new view.CategoryList());
}
}
Ok I have got two problems with this. 1) The label doesn't respond to setText in the button so it doesn't change if i put it in a other button it does change. 2) if I add more than 1 products i can only delete products from bottom to top, so it only reacts to the last button made and then the following and so on.
Hope anyone can help!
For point two:
for(int i=0;i < products.size(); i++){
btnDeleteproduct = new JButton("X");
btnDeleteproduct.setBounds(380, verticalPosition + i * productOffset, 20, 20);
btnDeleteproduct.setFont(WinkelApplication.FONT_10_BOLD);
btnDeleteproduct.setName("" + i);
btnDeleteproduct.addActionListener(this);
this.add(btnDeleteproduct);
}
When creating the delete buttons, you only keep the btnDeleteproduct reference. As you overwrite it in each iteration, you only keep the last one for the
if (event.getSource() == btnDeleteproduct) {
check in your listener.
Solution: Create a listener class that holds the key of the product that you want to delete. Instantitate a different object for each button, and add it as a listener instead of using a single listener for all of them.

Have user input into JTextField in for loop in Action Listener

I'm decently new to Java. I want the user to be able to input 4 different inputs separately by clicking submit. I'm using a for loop to count, but I do not know how to have the user input their answer multiple times. The for loops just repeats all at once. I'm using arrays to hold the user's answers. Here is part of my code. If you have questions or need more explanation I will def. explain more
private void Question1()
{
int count = 1;
QuestionsPanel.add(new JLabel(Q1.getQuestion()));
QuestionsPanel.add(new JLabel(Arrays.toString(mans1)));
AnswerField = new JTextField(10);
AnswerPanel.add(AnswerField);
Submit = new JButton("Submit");
AnswerPanel.add(Submit);
Submit.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if ((e.getSource() == Submit) && count == 0)
{
int value = Integer.parseInt(AnswerField.getText());
for (int i = 0; i < 4; i++)
{
if (value == -1) break;
ans[i] = value - 1;
AnswerField.setText("");
}
This doesn't work because you placed the loop in the ActionListener, which is executed once on button click.
What you should do is to keep a counter of the current answer somewhere
int count = 0;
public void actionPerformed(ActionEvent e) {
if ((e.getSource() == Submit) && count < 4) {
int value = Integer.parseInt(AnswerField.getText());
if (value == -1) break;
ans[count++] = value - 1;
AnswerField.setText("")
}
}
In this way the loop is implicitly managed by the actionlistener: everytime you press submit count is incremented by 1 and the correct answer is placed inside the array. Of course you should do something, like disabling the submit button, upon submitting the fourth answer.

Access already running objects - 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?

Categories

Resources