Change text of a label when a JButton is clicked java - 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!

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

Comparing the text of different JButtons

I am currently coding a game and part of it consist of having different tiles to be put in a board. I plan on simulating this by having different buttons that will be used to represent the tiles with their corresponding coordinates. For example, one button will say "A1", "A2", etc. What I would like to accomplish, is to have the user click on the "A1" tile and then the button on the board that represents "A1" will change colors, is there any way to go through the buttons on the board and compare its text to the selection of the user? The following is what I used to create the board:
JButton[][] buttons = new JButton[9][12];
JPanel panel = new JPanel(new GridLayout(9,12,5,5));
panel.setBounds(10, 11, 800, 600);
frame.getContentPane().add(panel);
//board
for (int r = 0; r < 9; r++)
{
for (int c = 0; c < 12; c++)
{
buttons[r][c] = new JButton("" + (c + 1) + numberList[r]);
buttons[r][c].setBackground(Color.WHITE);
panel.add(buttons[r][c]);
}
}
This is what I wrote on the code of one of the tiles
JButton tile1 = new JButton ("A1");
tile1.setBounds(60,725,60,60);
frame.getContentPane().add(tile1);
tile1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String buttonText = tile1.getText();
// iterating through all buttons:
for(int i=0;i<buttons.length;i++){
for(int j=0;j<buttons[0].length;j++)
{
JButton b = buttons[i][j];
String bText = b.getText();
if(buttonText.equals(bText))
{
[i][j].setBackground(Color.BLACK);
}
}
}
}
} );
However, it is given me an error saying that there is an action expected after "{"
You may add an action listener to each of the JButton you are creating in the loop like below:
buttons[r][c].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// your code here
}
} );
Placing the listener in your code may look like
JButton[][] buttons = new JButton[9][12];
JPanel panel = new JPanel(new GridLayout(9,12,5,5));
panel.setBounds(10, 11, 800, 600);
frame.getContentPane().add(panel);
//board
for (int r = 0; r < 9; r++)
{
for (int c = 0; c < 12; c++)
{
buttons[r][c] = new JButton("" + (c + 1) + numberList[r]);
buttons[r][c].setBackground(Color.WHITE);
buttons[r][c].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
String buttonText = button.getText();
// now iterate over all the jbuttons you have
for(int i=0;i<buttons.length;i++){
for(int j=0;j<buttons[0].length;j++){
JButton b = buttons[i][j];
String bText = b.getText();
if(buttonText.equals(bText)){
// you found a match here
// and you have the positions i, j
//
}
}
}
}
} );
panel.add(buttons[r][c]);
}
}
And you could store the the colors to be changed to in global static array, and use that array in your action listener.
For information on adding listener to the JButton, you may refer this thread How do you add an ActionListener onto a JButton in Java
Hope this helps!
You need listeners.
Implement ActionListener to your class. This will require you to add public void actionPerformed(ActionEvent e) {} to your class.
Every JButton you use should have an action listener.
Apply one like that:
JButton but = new JButton();
but.addActionListener(this);
Finally, in the actionPerformed method we added, you need to add something like that:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == but)
but.setBackground(Color.BLACK);
}
P.S. you can get a button's text value by the means of:
but.getText();

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

How do I parse a string to an object's name?

So I have a small amount of objects (10 JLabels) and I want to change their text depending on the users input.
The Initializer for the labels goes like this:
private JLabel j1 = new JLabel();
private JLabel j2 = new JLabel();
private JLabel j3 = new JLabel();
...etc
and continues on to 10.
How do I mass change the text of each JLabel without writing each variable name every time?
I had an idea like below, but I don't know how to access the variable by name from strings.
for(int x=1;x<=10;x++){
String d = (String) x; //this isn't what d equals, it's example.
String label = "j"+x;
label.setText(d); //I know this won't work, but this is what I want to do
}
Is there any way this can be done without errors?
This is an excellent chance to use an array to store your JLabel objects:
private JLabel[] labels = new JLabel[10];
for (int i=0; i<10; i++) {
labels[i] = new JLabel();
}
/* ... */
for (int i=0; i<10; i++) {
labels[i].setText("Hello from label " + i);
}
If you have created the JLabel as an array like JLabel j[10] = new JLabel[10]. Then you can use the for loop to create an instance for each index and then set the text as well.
for(int x=0;x<10;x++){
j[x] = new JLabel();
String d = String.valueOf(x);
String label = "j"+x;
j[x].setText(d);
}

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