How to have a unique identifier of a Jlabel? - java

I am new to java swing and I am creatin a Jlabel as follows :
JLabel Lport = new JLabel ("Port: ");
final JTextField Tport = new JTextField ("1883", 10);
what i want to do is to get the name of the label as a string because i want to use it in a switch-case, so i need to get the label name or a unique identifier of that label, some thing like an ID as it exists in Android, i tried the method ",getAction.toString", ".getName" but none of them displayed the name of the labe, which is according to the code posted is "Port: ". please see my attempts below:
if ( (isIPReady(Tip)) && (isPortReady(Tport)) ) {
Thread mqttThread = new Thread(MQTTRunnable, MQTT_THREAD);
mqttThread.start();
System.out.println("Action: " + Tport.get); //here i do not know which method to use
setViewEnableState(Bconnect, true);
}

The short answer is to use JLabel#getText which will return the text which is displayed by the JLabel.
An alternative could be to store your own key-value pair into the different JComponent instances. Each JComponent allows to put and retrieve client properties. A copy-paste from the class javadoc:
Support for component-specific properties. With the
putClientProperty(java.lang.Object, java.lang.Object) and
getClientProperty(java.lang.Object) methods, you can associate
name-object pairs with any object that descends from JComponent.
This would allow you to write:
private static final String ID_KEY = "MyUniqueIDKey";
JLabel label = new JLabel( "Whatever" );
label.putClientProperty( ID_KEY, "labelName" );
and then later on
String labelName = (String) label.getClientProperty( ID_KEY );
Note that this works with any JComponent, including JLabel and JTextField instances like the ones you are using in your code.

JLabel's name is different than the text it displays. To get the text from a JLabel, use getText().

You mention you want the name of the label but in your example you're calling a get on your textfield.
This applies to both a textfield and a label anyway.
That constructor sets the initial text that will display in the text field (or label).
If you want to set a name, you must first set it using setName() then use getName().

Related

Refresh data in a JLabel

I have a program which calculates an integer and then uses the value within a JLabel. On intital creation everything is fine with the initialized value, but when I change the value of the int within the label I can't seem to find a way to update the JLabel. The relevant code is as follows:
JLabel carbLbl;
int totCarbs = 0;
public Main() {
carbLbl = new JLabel("Total Carbs: " + totCarbs);
carbLbl.setFont(new Font("KidSans", Font.PLAIN, 38));
carbLbl.setAlignmentX(Component.RIGHT_ALIGNMENT);
void addFoodToTable() {
String[] s = new String[3];
s = (String[]) foodData.get(foodChoice.getSelectedIndex());
foodList.addRow(s);
totCarbs += Integer.parseInt(s[2]);
carbLbl.repaint();
}
}
There's obviously much more code, but it's too long to include the entire script. Is there a way I can have the label update whenever I invoke the addFoodToTable() method?
The JLabel is not "bound" to your integer variable. When you change the integer you need to update the JLabel using carbLbl.setText(String.valueOf(totCarbs))
Is there not a way to simply update the JLabel using the initial constructor parameters?
carbLbl = new JLabel("Total Carbs: " + totCarbs);
What parameters? There is only a single parameter, the String to be displayed.
The compiler concatenates the hard coded String with the value of your "totCarbs" variable to create a single String.
The compiler will essentially treat the above code like:
String text = "Total Carbs" + totCarbs;
carbLbl = new JLabel( text );
The JLabel has no idea how the String was created (ie. that a variable was used to build the string).
I understand the concept of concatenation, but I just feel like that's a workaround
It is not a work around. The API of the setText(...) method states you provide a single String. So, if you want to update the label you need to provide the entire String.

How do I set the color of a JLabel using Java?

I will be creating multiple Jlabel components upon a JButton click. I know how to create a label and set text inside but I want this label to have a color.
I only know how to change the color of a label if it has a name but an important part of my program is when I declare the labels, I don't have names for them as shown in the code below:
newPanel.add(new JLabel("jlabel text"), g);
How can I set the color of the label?
I don't have names for them as shown in the code below:
newPanel.add(new JLabel("jlabel text"), g);
So give the label a name:
JLabel label = new JLabel("label text");
label.setOpaque( true );
label.setBackground( Color.RED );
newPanel.add(label, g);
You should assign the label to a variable so that you can perform additional operations on it:
JLabel myLabel = new JLabel("jlabel text");
myLabel.setForeground(new java.awt.Color.RED);
newPanel.add(myLabel);
Now place this code in a function, such as an event handler for your button. Each time you click the button it creates a new JLabel. The name myLabel only refers to the current one that is being created. So yes, you can reuse the same name to refer to a different JLabel object. At a given moment, the name can only refer to one JLabel at a time.
yourLabel.setForeground(new java.awt.Color(r,g,b);

Accessing GUI JTextField objects that are dynamically generated

I am writing a program that contains a JButton. Every time the button is clicked, a new JTextField is added to a JPanel.
My problem is that, after the user has created all the JTextFields and filled them with information, I need to get the text of each field. How can I get access to the JTextFields when they are dynamically generated, as they don't have instance names? Is there a better way to get the text of each one, without knowing their instance name.
Here is the code of the actionPerformed event of the JButton...
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
JTextField x = new JTextField();
x.setColumns(12);
p.add(x);
validate();
}
You say you want to get the text from each field. So, when you create the new instances x, why don't you keep a collection of them, such as adding the JTextFields to an ArrayList?
Alternatively, assuming that p is a JPanel, you should be able to get all the children, which would be the JTextFields that you're adding. Try using getComponents() like so...
Component[] children = p.getComponents();
for (int i=0;i<children.length;i++){
if (children[i] instanceof JTextField){
String text = ((JTextField)children[i]).getText():
}
}
You can find them all by looping through the components of the panel (or whatever "p" is). If necessary, check if each is a text box. That is, do p.getComponents and then loop through the returned array. Like:
Component[] components=p.getComponents();
for (Component c : components)
{
if (c instanceof JTextField)
{
String value=((JTextField)c).getText();
... do whatever ...
}
}
If they are interchangeable, that should be all you need. If you need to distinguish them, I think the cleanest thing to do would be to create your own class that extends JTextField and that has a field for a name or sequence number or whatever you need.

How do I underline text "text" when text is a field?

public class Text extends JPanel {
private String text;
public Text()
{
this.setPreferredSize(new Dimension(20,20));
setFont (new Font(text, Font.PLAIN, 24));
text = "";
}
public void showUnderline()
{
Hashtable<TextAttribute, Object> map = new Hashtable
<TextAttribute, Object>();
map.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
}
the text object will be created within another class. in that class I will need to underline it with the showUnderline method. The method seems incomplete.I'm shooting for the java exclusive approach, meaning no HTML.
How do I link the text to the showUnderline method?
What do you mean 'java exclusive approach, meaning no HTML' ? You probably are looking for a JLabel, and you can put very simple html in it. Here's the first result on google:
http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JLabel.html
It has an example of making text different colors, fonts, and bold or italicized. You could probably just do something like:
JLabel label = new JLabel("<u>MY TEXT</u>",JLabel.CENTER);
From there, you can place it like you would place any other JComponent.
If you really don't want HTML, you could use a JTextPane. Here's an example:
http://www.exampledepot.com/egs/javax.swing.text/style_hilitewords2.html

How to print to a J text box the entire contents of a tree map?

Hi Everyone thanks for taking the time to look at my question.
I would like to use the JText field I have created to display the values of a tree map which contains all the employees: ID numbers (as the key in the map)as well as an Employee object which contains a to string method of all the employee details.
the system seems to be working fine because when I print to the console (CMD) it works fine and prints out all the values in the MAP but when I try print it to a JText box it only prints one object (one employee) from the entire list.
I believe the issue lies with my for loop i am using to access all the details.
the issue lies with this line of code:
writeStrings.setText(writeStrings.getText()+" "+dEmp);
This is the code in its entirety:
public void chooseEmpToAdd()
{
JFrame frameAllEmps = new JFrame();
frameAllEmps.setSize( 450, 140 );
frameAllEmps.pack();
frameAllEmps.setVisible(true);
int x = 0;
System.out.println("ALL Emps from the tree map");
for(int key:employeeMap.keySet())
{
JTextField writeStrings;
writeStrings = new JTextField(20);
Employee dEmp = employeeMap.get(key);
System.out.println("Employe no :" +x+": "+dEmp);
writeStrings.setText(writeStrings.getText()+" "+dEmp);
frameAllEmps.add(writeStrings);
x++;
}
}
writeStrings = new JTextField(20);
You create new JTextField component on every iteration and add it to container.
JFrame uses BorderLayout as a default layout.
This layout puts your JTextField component in the center (frameAllEmps.add(writeStrings)). So you lost previous added JTextField and see only last JTextField component.

Categories

Resources