java index of selected item arraylist - java

In Java, I'm trying to identify which JComboBox within an ArrayList was just clicked on. Some of the code follows:
private ArrayList<JComboBox<String>> setTextBoxList;
// basic initialization
public void populateList() {
String str[] = {"one", "two"};
for(int i=0; i<2; i++) {
JComboBox<String> jcb = new JComboBox<String>(str);
setTextBoxList.add(new JComboBox<String>(str));
jcb.addActionListener(this);
}
}
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if(o instanceof JComboBox) {
// here's where I'd like to see which box was just changed
System.out.println("change index "
+ setTextBoxList.indexOf((JComboBox)o) );
}
}
My problem is that when I click on and change one of the comboboxes, the index shown is always -1. I'd like to get the index of which box in the arraylist was just clicked on/changed. I get the same results w/o the explicit type-cast.

The problem is in this segment of code:
for(int i=0; i<2; i++) {
JComboBox<String> jcb = new JComboBox<String>(str);
setTextBoxList.add(new JComboBox<String>(str)); // <-- error!
jcb.addActionListener(this);
}
You are creating two JComboBoxes, and the one that gets the listener is not the one that is in the list. Try changing the code to:
for(int i=0; i<2; i++) {
JComboBox<String> jcb = new JComboBox<String>(str);
setTextBoxList.add(jcb); // changed line
jcb.addActionListener(this);
}

Related

error: cannot find symbol in ActionLearner

I am currently working on a GUI and I have an array of Jbutton. I also have another array of information to insert specifically into each Jbutton. So when I press a button it will bring me to a new popup however I want the popup to print only the information specifically for that Jbutton. I am unsure how I can do it. Below is a snippet of my script. Really hope there will be someone out there to help me with this. Pardon me as im not too sure how I can phrase it and if there is any doubt I can explain further. (the ** ic ** and ** s ** is meant to bold the two variables im not too sure why it is not bold)
jbArray = new JButton [pArray.length];
for (int i = 0; i < pArray.length ; i++)
{
defaultpic = new ImageIcon("default.jpg");
rolloverpic = new ImageIcon("coloured.jpg");
jbArray[i]= new JButton (pArray[i].getbuttonName(),defaultpic);
jbArray[i].setRolloverIcon(rolloverpic);
add (jbArray[i]);
}
// Register the events to each button
for (int i = 0; i < jbArray.length; i++)
{
jbArray[i].addActionListener (new SButtonClass (pArray[i].getbuttonName()));
ImageIcon **ic** = pArray[i].getimageFile();
String **s** = pArray[i].toString();
}
//----------------------End of Student Buttons ----------------------
}
private class SButtonClass implements ActionListener{
#Override
public void actionPerformed (ActionEvent e)
{
if (e.getSource () == questionBox);
String str = **s** + questionBox.getText();
Icon studentdp = new ImageIcon (**ic**);
JOptionPane.showMessageDialog(null, str, "Welcome to Chat Room", JOptionPane.INFORMATION_MESSAGE, studentdp);
}
}
update: I removed class SButtonclass and adjusted the new SButtonClass code to:
for (int i = 0; i < jbArray.length; i++)
{
jbArray[i].addActionListener((e) -> {
String str = pArray[i].toString() + questionBox.getText();
Icon studentdp = new ImageIcon (pArray[i].getimageFile());
JOptionPane.showMessageDialog(null, str, "Welcome to Chat Room", JOptionPane.INFORMATION_MESSAGE, studentdp);
});
}
however I face a new error: "local variables referenced from a lambda expression must be final or effectively final."
local variable referring to the i in this statement String str = pArray[i].toString() + questionBox.getText();

how to set combobox value when choosing jtable data

public void setForm(mhs m)
{
String[] jurusan = {"TI","SI"};
JComboBox<String> cjurusan = new JComboBox<String> (jurusan);
String st;
st = ((String)m.getJurusan()).toUpperCase();
for(int i = 0; i < cjurusan.getItemCount(); i++)
{
String jur = ((String) cjurusan.getItemAt(i)).toUpperCase();
if(jur.equals("SI"))
{
cjurusan.setSelectedIndex(1);
}
else
{
cjurusan.setSelectedIndex(0);
}
}
tnim.setText(m.getNim());
tnama.setText(m.getNama());
cjurusan.setBounds(110,70,90,20);
add(cjurusan);
}
}
I want to set jcombobox's value according the data record in jtable, till now, I just get the data value at the first time, for second time the jcombobox's value is the same with last. please help. many thanks.
This is my sample image program : screenshoot

Set toggleButton non-clickable

So this is my movie GUI. There are 30 JToggleButton. I want it to find out which seat has been selected by checking the value in MySQL. If the seat not selected, they are clickable, otherwise they are not.
public selectSeat(String title, String day, String time) throws Exception
{
JPanel topPanel= new JPanel(new GridLayout(1, 15));
RectDraw rect= new RectDraw();
rect.setPreferredSize(new Dimension(30,25));
topPanel.add(rect);
JToggleButton[] ButtonList = new JToggleButton[30];
JPanel ButtonPanel= new JPanel(new GridLayout(5,15,45,25)); // row,col,hgap,vgap
for(int i = 0; i < 30; i++) {
a=i+1;
ButtonList[i]= new JToggleButton(""+a);
ButtonPanel.add(ButtonList[i]);
}
int no= findNo(day,title,time); // get hall number
System.out.println(no);
List<String> seats= checkSeat(no); // get selected seats value
System.out.println(seats); // [22,23]
for(String s : seats)
{
for(int j = 0; j<30;j++)
{
if(s.contains(ButtonList[j].getText())) // if seats label with 22 and 23
{
ButtonList[j].setEnabled(false); // non-clickable
}
}
}
However, the toggle button labelling with 2,3,22 and 23 become non-clickable.
OK, I solved by using this way
for(String s : seats) // remove [] brackets (22,23)
{
String[] selected=s.split(","); // remove the comma
for (String t: selected)
{
for(int j = 0; j<30;j++)
{
if(ButtonList[j].getText().equals(t)) // if seats label with 22 and 23
{
ButtonList[j].setEnabled(false); // non-clickable
}
}
}
}
You're checking if "23" contains "2" or "3" and it does. Get rid of the outer for loop and instead simply check if the ArrayList contains the String, not if the List's String contains a substring:
for(int j = 0; j < ButtonList.length; j++) {
ButtonList[j].setEnabled(!seats.contains(ButtonList[j].getText()));
}
The mistake is the if statement if(s.contains(ButtonList[j].getText()))
you are checking if your String s which contains the number of the Buttons you should compare if the are equal with s.equals()

Getting value of String in Jlist

How can I get the value of an item in this case String item that has been added to a JList? What I meanV
String[] coinNames ={"Quarters","Dimes","Nickels","Pennies"};
JList coinList = new JList (coinNames);
coinList[0] == "Quarters" ???????
Since I clearly can't reference it like a normal array, how might I go about getting the string value of coinlist[0]?
This is a simple example to get just an index to your JList and display all your JList.
public static void main(String[] args) {
String[] coinNames ={"Quarters","Dimes","Nickels","Pennies"};
JList coinList = new JList (coinNames);
String myCoin = (String) coinList.getModel().getElementAt(0);
System.out.println(myCoin);
/* LIST AL YOUR COINNAMES */
System.out.println("\nCoinList\n");
for(int i =0; i < coinList.getModel().getSize(); i++){
System.out.println((String) coinList.getModel().getElementAt(i));
}
coinNames[0] = "My new Value"; // Edit your CoinNames at index 0
/* LIST AL YOUR NEW COINNAMES */
System.out.println("\nNew coinList edited\n");
for(int i =0; i < coinList.getModel().getSize(); i++){
System.out.println((String) coinList.getModel().getElementAt(i));
}
}
coinList.getModel().getElementAt(0);
pls read the manual: http://docs.oracle.com/javase/8/docs/api/javax/swing/JList.html#getModel--
EDIT: or simply take a look at the example at the op of the amnual page: http://docs.oracle.com/javase/8/docs/api/javax/swing/JList.html
// Create a JList that displays strings from an array
String[] data = {"one", "two", "three", "four"};
JList<String> myList = new JList<String>(data);
// Create a JList that displays the superclasses of JList.class, by
// creating it with a Vector populated with this data
Vector<Class<?>> superClasses = new Vector<Class<?>>();
Class<JList> rootClass = javax.swing.JList.class;
for(Class<?> cls = rootClass; cls != null; cls = cls.getSuperclass()) {
superClasses.addElement(cls);
}
JList<Class<?>> myList = new JList<Class<?>>(superClasses);
// The automatically created model is stored in JList's "model"
// property, which you can retrieve
ListModel<Class<?>> model = myList.getModel();
for(int i = 0; i < model.getSize(); i++) {
System.out.println(model.getElementAt(i));
}

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.

Categories

Resources