error: cannot find symbol in ActionLearner - java

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

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.

Checking to see if a JtextField is NOT equal to saved arrays

Hey guys I'm very new to Java and started in July with an intro to Java class.
I am currently working on a project which is a translator with arrays. The main applet shows 10 words in english that when typed into a JTextField outputs the spanish translation of that work. And vice versa. The program also shows a picture associated with that word.
The program is all done in that case, the only portion I am missing currently is that if a user inputs ANY other word than the 20 given words (10 spanish and 10 english) the JTextArea where translations are displayed is supposed to show "That word is not in the dictionary".
I'm having issues creating an ELSE statement that shows this error message. Here is the complete code. I'm not sure what to do to make it so eg
if (textFieldWord.!equals(englishWords[english])){
translate.setText("That word is not in the Dictionary");}
Here is the complete code - - - -
import java.awt.*;
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class DictionaryArrays extends JApplet implements ActionListener{
String[] spanishWords = {"biblioteca","reloj",
"alarma", "volcan", "ventana",
"autobus", "raton", "lago", "vaca", "encendedor"};
String[] englishWords = {"library", "clock", "alarm",
"volcano", "window", "bus", "rat",
"lake","cow","lighter"};
String textFieldWord;
Image[] photos;
ImageIcon icon;
ImageIcon icontwo;
JButton getTranslation;
JTextField entry;
JLabel imageviewer;
TextArea translate;
static int defaultX = 10;
static int defaultY = 10;
static int defaultW = 780;
static int defaultH = 50;
public void init() {
photos = new Image[10];
photos[0] = getImage(getCodeBase(), "library.jpg");
photos[1] = getImage(getCodeBase(), "clock.jpg");
photos[2] = getImage(getCodeBase(), "alarm.jpg");
photos[3] = getImage(getCodeBase(), "volcano.jpg");
photos[4] = getImage(getCodeBase(), "window.jpg");
photos[5] = getImage(getCodeBase(), "bus.jpg");
photos[6] = getImage(getCodeBase(), "rat.jpg");
photos[7] = getImage(getCodeBase(), "lake.jpg");
photos[8] = getImage(getCodeBase(), "cow.jpg");
photos[9] = getImage(getCodeBase(), "lighter.jpg");
final JPanel outer = new JPanel(new BorderLayout());
JPanel inner = new JPanel(new BorderLayout());
JPanel viewer = new JPanel(new BorderLayout());
JPanel visualviewer = new JPanel(new BorderLayout());
// here is the main component we want to see
// when the outer panel is added to the null layout
//JButton toSpanish = new JButton("English to Spanish");
//JButton toEnglish = new JButton("Spanish to English");
final JLabel list = new JLabel("<HTML><FONT COLOR=RED>English</FONT> - library, clock, alarm, volcano, window, bus, rat, lake, cow, lighter"
+"<BR><FONT COLOR=RED>Spanish</FONT> - biblioteca, reloj, alarma, volcan, ventana, autobus, raton, lago, vaca, encendedor<BR>");
translate = new TextArea("Your translation will show here");
imageviewer = new JLabel(icon);
viewer.add("West",translate);
visualviewer.add("East",imageviewer);
inner.add("Center",list);
//inner.add("West",toSpanish);
//inner.add("East", toEnglish);
outer.add("Center", inner);
JPanel c = (JPanel)getContentPane();
final JPanel nullLayoutPanel = new JPanel();
nullLayoutPanel.setLayout(null);
c.add("Center", nullLayoutPanel);
// set the bounds of the panels manually
nullLayoutPanel.add(outer);
nullLayoutPanel.add(viewer);
nullLayoutPanel.add(visualviewer);
outer.setBounds(defaultX, defaultY, defaultW, defaultH);
viewer.setBounds(20, 75, 300, 300);
visualviewer.setBounds(485, 75, 300, 300);
JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
entry = new JTextField("Enter English or Spanish word to translate here");
entry.addActionListener(this);
entry.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
entry.setText("");
}});
getTranslation = new JButton("Translate");
getTranslation.addActionListener(this);
controlPanel.add(entry);
controlPanel.add(getTranslation);
c.add("South", controlPanel);
viewer.setBackground(Color.blue);
controlPanel.setBackground(Color.red);
inner.setBackground(Color.yellow);
visualviewer.setBackground(Color.black);
outer.setBackground(Color.black);
}
public void paint(Graphics g) {
super.paint(g);
}
public void actionPerformed (ActionEvent ae){
if(ae.getSource()==getTranslation){
textFieldWord=(entry.getText().toLowerCase());
for (int english = 0; english < spanishWords.length; english++){
if (textFieldWord.equals(englishWords[english])){
translate.setText(spanishWords[english]);
icon= new ImageIcon(photos[english]);
imageviewer.setIcon(icon);
break;
}
}
for (int spanish = 0; spanish < englishWords.length; spanish++){
if (textFieldWord.equals(spanishWords[spanish])){
translate.setText(englishWords[spanish]);
icontwo= new ImageIcon(photos[spanish]);
imageviewer.setIcon(icontwo);
break;
}
}
}
}
}
Any help would be appreciated guys. If the top paragraph was TLDR. Im trying to make it so typing in ANY other word in the JTextField (entry) other than the 10 english and 10 spanish words will output an error msg of "That word is not in the Dictionary" in the TextArea (translate)
This is (obviously) wrong...
if (textFieldWord.!equals(englishWords[english])){
and should be...
if (!textFieldWord.equals(englishWords[english])){
Try and think of it this way, String#equals returns a boolean, you want to invert the result of this method call, it would be the same as using something like...
boolean doesEqual = textFieldWord.equals(englishWords[english]);
if (!doesEqual) {...
You need to evaluate the result of the method call, but in oder to make that call, the syntax must be [object].[method], therefore, in order to invert the value, you must complete the method call first, then apply the modifier to it ... ! ([object].[method])
Updated...
Now having said all that, let's look at the problem from a different perspective...
You need to find a matching word, in order to do that, you must, at worse case, search the entire array. Until you've search the entire array, you don't know if a match exists.
This means we could use a separate if-else statement to manage the updating of the output, for example...
String translatedWord = null;
int foundIndex = -1;
for (int english = 0; english < spanishWords.length; english++){
if (textFieldWord.equals(englishWords[english])){
translatedWord = englishWords[english];
foundIndex = english;
break;
}
}
if (translatedWord != null) {
translate.setText(translatedWord);
icon= new ImageIcon(photos[foundIndex]);
imageviewer.setIcon(icon);
} else {
translate.setText("That word is not in the Dictionary");
}
translatedWord = null;
for (int spanish = 0; spanish < englishWords.length; spanish++){
if (textFieldWord.equals(spanishWords[spanish])){
translatedWord = englishWords[english];
foundIndex = spanish;
break;
}
}
if (translatedWord != null) {
translate.setText(translatedWord);
icontwo= new ImageIcon(photos[foundIndex]);
imageviewer.setIcon(icontwo);
} else {
translate.setText("That word is not in the Dictionary");
}
Basically, all this does is sets the translatedWord to a non null value when it finds a match in either of the arrays. In this, you want to display the results, else you want to display the error message...
Equally, you could merge your current approach with the above, so when you find a work, you update the output, but also check the state of the translatedWord variable, displaying the error message if it is null...
String translatedWord = null;
for (int english = 0; english < spanishWords.length; english++){
if (textFieldWord.equals(englishWords[english])){
translatedWord = spanishWords[english];
translate.setText(translatedWord);
icon= new ImageIcon(photos[english]);
imageviewer.setIcon(icon);
break;
}
}
if (translatedWord == null) {
translate.setText("That word is not in the Dictionary");
}
translatedWord = null;
for (int spanish = 0; spanish < englishWords.length; spanish++){
if (textFieldWord.equals(spanishWords[spanish])){
translatedWord = englishWords[spanish];
translate.setText(translatedWord);
icontwo= new ImageIcon(photos[spanish]);
imageviewer.setIcon(icontwo);
break;
}
}
if (translatedWord == null) {
translate.setText("That word is not in the Dictionary");
}
Updated
Okay, you have a logic problem. You're never quite sure which direction you are translating to.
The following basically changes the follow by not translating the work from Spanish IF it was translated to English
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == getTranslation) {
textFieldWord = (entry.getText().toLowerCase());
translate.setText(null);
String translatedWord = null;
for (int english = 0; english < spanishWords.length; english++) {
if (textFieldWord.equals(englishWords[english])) {
translatedWord = spanishWords[english];
translate.append(translatedWord + "\n");
icon = new ImageIcon(photos[english]);
imageviewer.setIcon(icon);
break;
}
}
if (translatedWord == null) {
for (int spanish = 0; spanish < englishWords.length; spanish++) {
if (textFieldWord.equals(spanishWords[spanish])) {
translatedWord = englishWords[spanish];
translate.append(translatedWord + "\n");
icontwo = new ImageIcon(photos[spanish]);
imageviewer.setIcon(icontwo);
break;
}
}
}
if (translatedWord == null) {
translate.append("A Spanish-English match is not in the Dictionary\n");
}
}
}
Now, I would suggest that you replace TextArea with a JTextArea, but you will need to wrap it in a JScrollPane
translate = new JTextArea("Your translation will show here");
viewer.add("West", new JScrollPane(translate));
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
Basically, this was really painful to try and use for this very reason...

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

Change text of a label when a JButton is clicked java

I'm try to change the text on a JLabel when the Jbutton is clicked but i can't figure it out why it turns the text into empty when i clicked the button. I'm trying to retrieve the data from the database.
heres my label
labelDisplay = new JLabel[7];
for(int z = 0; z<7; z++){
labelDisplay[z] = new JLabel("d");
labelDisplay[z].setForeground(new Color(230,230,230));
if( z%2==0)
labelDisplay[z].setBounds(130,65,160,25);
else
labelDisplay[z].setBounds(130,30,160,25);
}
I'm sure that my class for retrieving date is working i test it out.
heres my actionListener:
public class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == extendB)
{
ExtensionForm extend = new ExtensionForm();
extend.setVisible(true);
}
else if(e.getSource()== searchB)
{
//get text from the textField
String guest = guestIDTF.getText();
//parse the string to integer for retrieving of date
int id = Integer.parseInt(guest);
GuestsInfo guestInfo = new GuestsInfo(id);
Room roomInfo = new Room(id);
searchB.setText(""+id);
System.out.println(""+guestInfo.getFirstName());
labelDisplay[1].setText(""+id);
String labels[] = {guestInfo.getFirstName()+" "+guestInfo.getLastName(),
""+roomInfo.getRoomNo(),roomInfo.getRoomType(),guestInfo.getTime(),"11:00",
""+guestInfo.getDeposit(),"30"};
labels = new String[7];
for(int z = 0; z<labels.length; z++){
labelDisplay[z].setText(labels[z]);
}
}
}
}
I did put an initial value for the label text, as you can see from my code it's letter "d" but when i clicked the button it turns to empty.The accessor methods there are really working that why i suspect that the error is from my actionListener. Please help me guys
I edit the constructor it should be id not 1.
Heres the code for the actionListener for the button
ButtonHandler bh = new ButtonHandler();
searchB = new JButton("search");
searchB.setBounds(190,30,75,25);
searchB.addActionListener(bh);
labelDisplay[1].setText(""+id);
String labels[] = {guestInfo.getFirstName()+" "+guestInfo.getLastName(),
""+roomInfo.getRoomNo(),roomInfo.getRoomType(), guestInfo.getTime(),
"11:00", ""+guestInfo.getDeposit(),"30"};
labels = new String[7];
for(int z = 0; z<labels.length; z++){
labelDisplay[z].setText(labels[z]);
}
You never set your labels to something valid. Remove labels = new String[7];
Should have checked the code well sorry!

How can I determine which JCheckBox caused an event when the JCheckBox text is the same

I am working on a program that needs to determine which JCheckBox was selected. I am using three different button groups, two of which have overlapping text. I need to be able to determine which triggered the event so I can add the appropriate charge (COSTPERROOM vs COSTPERCAR) to the total(costOfHome). What I cant figure out is how to differentiate the checkbox source if the text is the same. I was thinking of trying to change the text on one button group to strings like "one" "two" etc, but that introduces a bigger problem with how I have created the checkboxes in the first place. Any ideas would be appreciated, thanks in advance!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JMyNewHome extends JFrame implements ItemListener {
// class private variables
private int costOfHome = 0;
// class arrays
private String[] homeNamesArray = {"Aspen", "Brittany", "Colonial", "Dartmour"};
private int[] homeCostArray = {100000, 120000, 180000, 250000};
// class constants
private final int MAXROOMS = 3;
private final int MAXCARS = 4;
private final int COSTPERROOM = 10500;
private final int COSTPERCAR = 7775;
JLabel costLabel = new JLabel();
// constructor
public JMyNewHome ()
{
super("My New Home");
setSize(450,150);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Font labelFont = new Font("Time New Roman", Font.BOLD, 24);
setJLabelString(costLabel, costOfHome);
costLabel.setFont(labelFont);
add(costLabel);
JCheckBox[] homesCheckBoxes = new JCheckBox[homeNamesArray.length];
ButtonGroup homeSelection = new ButtonGroup();
for (int i = 0; i < homeNamesArray.length; i++)
{
homesCheckBoxes[i] = new JCheckBox(homeNamesArray[i], false);
homeSelection.add(homesCheckBoxes[i]);
homesCheckBoxes[i].addItemListener(this);
add(homesCheckBoxes[i]);
}
JLabel roomLabel = new JLabel("Number of Rooms in Home");
add(roomLabel);
ButtonGroup roomSelection = new ButtonGroup();
JCheckBox[] roomCheckBoxes = new JCheckBox[MAXROOMS];
for (int i = 0; i < MAXROOMS; i++)
{
String intToString = Integer.toString(i + 2);
roomCheckBoxes[i] = new JCheckBox(intToString);
roomSelection.add(roomCheckBoxes[i]);
roomCheckBoxes[i].addItemListener(this);
add(roomCheckBoxes[i]);
}
JLabel carLabel = new JLabel("Size of Garage (number of cars)");
add(carLabel);
ButtonGroup carSelection = new ButtonGroup();
JCheckBox[] carCheckBoxes = new JCheckBox[MAXCARS];
for (int i = 0; i < MAXCARS; i++)
{
String intToString = Integer.toString(i);
carCheckBoxes[i] = new JCheckBox(intToString);
carSelection.add(carCheckBoxes[i]);
carCheckBoxes[i].addItemListener(this);
add(carCheckBoxes[i]);
}
setVisible(true);
}
private void setJLabelString(JLabel label, int cost)
{
String costOfHomeString = Integer.toString(cost);
label.setText("Cost of Configured Home: $ " + costOfHomeString + ".00");
invalidate();
validate();
repaint();
}
public void itemStateChanged(ItemEvent e) {
JCheckBox source = (JCheckBox) e.getItem();
String sourceText = source.getText();
//JLabel testLabel = new JLabel(sourceText);
//add(testLabel);
//invalidate();
//validate();
//repaint();
for (int i = 0; i < homeNamesArray.length; i++)
{
if (sourceText == homeNamesArray[i])
{
setJLabelString(costLabel, costOfHome + homeCostArray[i]);
}
}
}
}
I would
Use JRadioButtons for this rather than JCheckBoxes since I think it is GUI standard to have a set of JRadioButtons that only allow one selection rather than a set of JCheckBoxes.
Although you may have "overlapping text" you can set the button's actionCommand to anything you want to. So one set of buttons could have actionCommands that are "room count 2", "room count 3", ...
But even better, the ButtonGroup can tell you which toggle button (either check box or radio button) has been selected since if you call getSelection() on it, it will get you the ButtonModel of the selected button (or null if none have been selected), and then you can get the actionCommand from the model via its getActionCommand() method. Just first check that the model selected isn't null.
Learn to use the layout managers as they can make your job much easier.
For instance, if you had two ButtonGroups:
ButtonGroup fooBtnGroup = new ButtonGroup();
ButtonGroup barBtnGroup = new ButtonGroup();
If you add a bunch of JRadioButtons to these ButtonGroups, you can then check which buttons were selected for which group like so (the following code is in a JButton's ActionListener):
ButtonModel fooModel = fooBtnGroup.getSelection();
String fooSelection = fooModel == null ? "No foo selected" : fooModel.getActionCommand();
ButtonModel barModel = barBtnGroup.getSelection();
String barSelection = barModel == null ? "No bar selected" : barModel.getActionCommand();
System.out.println("Foo selected: " + fooSelection);
System.out.println("Bar selected: " + barSelection);
Assuming of course that you've set the actionCommand for your buttons.
Checkboxes have item listeners like any other swing component. I would decouple them, and simply add listeners to each
{
checkBox.addActionListener(actionListener);
}
http://www.java2s.com/Code/Java/Swing-JFC/CheckBoxItemListener.htm

Categories

Resources