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

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

Related

Assign JButton for-loop

String[] nomMois =
{"Janvier","FĂ©vrier","Mars","Avril","Mai","Juin","Juillet","Aout",
"Septembre","Octobre","Novembre","Decembre"};
JPanel tabJPanelMois[] = new JPanel[nomMois.length];
for(int indice=0; indice<tabJPanelMois.length; indice++){
tabJPanelMois[indice]= new JPanel();
tabJPanelMois[indice].setLayout(new GridLayout(0,7,8,18));
for(int j=1; j<=Date.dernierJourDuMois(indice+1,2017);j++){
tabJPanelMois[indice].add(new JButton(Integer.toString(j)));
}
I want to put an ActionListener on each Button but with that code i don't assign a name for each JButton so I can't,how must I do?
Define a temporal Button, and use it in the loop, creating a new object will allow you to recycle the variable x as much as you need:
JButton x;
for(int j=1; j<=Date.dernierJourDuMois(indice+1,2017);j++){
x = new JButton(Integer.toString(j));
x.setMyNewListener(abcListner);
tabJPanelMois[indice].add(x);
}

Java getText of looped multiple JTextFields

My first question here. Already got a lot of help but now I don't know how to do.
My code:
package view;
import javax.swing.*;
public class OptionPlayerNames {
JPanel playerPanel = new JPanel();
JTextField playerNames = new JTextField();
public OptionPlayerNames() {
for (int i = 0; i < 8; i++) {
// JTextField playerNames = new JTextField();
playerPanel.add(new JLabel("Player " + (i + 1)));
playerPanel.add(playerNames);
}
playerPanel.setLayout(new BoxLayout(playerPanel, BoxLayout.Y_AXIS));
playerPanel.add(Box.createHorizontalStrut(5));
}
public JPanel getPanel(){
return playerPanel;
}
public String getPlayerNames() {
return playerNames.getText();
}
I want to have 8 Jlabels with just under it 8 JTextFields for user input.
Then get the text of the textfields.
Now I get only 1 text from 1 textField. Off course I only add 1 field.
When I put the JTextField under the for loop I get what I want but how to I get the text from all the JTextFields then? playerNames is then not known in the getter.
Thank you for your help.
You can do as follows, creating a Listof JTextField:
JPanel playerPanel = new JPanel();
List<JTextField> playerNames = new ArrayList<JTextField>();
public OptionPlayerNames() {
for (int i = 0; i < 8; i++) {
JTextField playerName = new JTextField();
playerPanel.add(new JLabel("Player " + (i + 1)));
playerPanel.add(playerName);
playerNames.add(playerName);
}
playerPanel.setLayout(new BoxLayout(playerPanel, BoxLayout.Y_AXIS));
playerPanel.add(Box.createHorizontalStrut(5));
}
public JPanel getPanel() {
return playerPanel;
}
public String getPlayerNames() {
String output = "";
// Compound you exit from the playerNames List
// Or better, return a List of String
return output;
}
You need to declare a Vector or array of JTextField as an instance variable (not just one, as you've commented out) and fill it in as you loop. Then you have random (arbitrary) access to any text value. Conveniently, the index i is already there for you to index into the array.
There should be a tip-off that the type: JTextField is singular, but your variable name: playerNames is plural. :-)
Note that getPlayerNames() also needs to be re-done to handle an array not a single field.
While this will work, ultimately, the whole code block isn't good separation of Model & View, so as you advance in programming, be sure to pay attention to that concept.

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