JLabel does not update when using setText method - java

In the project I am currently working on I have several pieces of information that I would like to make visible via Jlabel. There are a few buttons and textfields elsewhere in the GUI that allow for altering said information I would like to update the JLabel but the text never changes, or updates upon startup.
I have attempted to use concurrency to update the labels, as suggested in other questions on this site, but I have had no luck with the labels updating. The concurrency does work with updating textfields and comboBoxes as needed.
The current iteration of my code looks as follows,
The JFrame
//// This is a snippet from the JFrame
public void start()
{
this.setSize(900, 700);
this.setVisible(true);
devicePanel.populateDeviceDefinitions();
updateServiceInfo();
updateCommandInfo();
startUpdateTimer();
}
public void updateServiceInfo()
{
EventService service = JetstreamApp.getService();
generalPanel.updateServiceInfo(service.getBaseUri(),
service.getAccessKey(), String.valueOf(service.getWindowTime()));
}
public void updateCommandInfo()
{
JetstreamServiceClient client = JetstreamApp.getClient();
generalPanel.updateCommandInfo(client.getBaseUri(), client.getAccessKey());
}
The JPanel named generalPanel
//// This is a snippet from the generalPanel
//// All of the variables in the following code are JLabels
public void updateServiceInfo(String baseUrl, String accessKey,
String windowTime)
{
serviceUrl.setText(baseUrl);
serviceAccessKey.setText(accessKey);
serviceWindowTime.setText(windowTime);
}
public void updateCommandInfo(String baseUrl, String accessKey)
{
commandUrl.setText(baseUrl);
commandAccessKey.setText(accessKey);
}
The labels start with an Empty string for their text and upon window start it is intended that they be updated by grabbing the information from the relevant sources. Can I please have some insight as to why the JLabels never update and display their information?

How did you create the JLabel? If the text starts out as "", and you've created it with new JLabel(""), the width of the JLabel may be initialized to 0 and then none of your text would show up when you update it. I believe I've had that sort of problem in the past. As a test, try using new JLabel("aaaaaaaaaa") or some longer string to create the label, then setText(""); then later, when you setText(somethingElse), see if that causes text to show up. If it does, then the width is probably the problem and you can work on it from there. – ajb 19 mins ago
This comment is the actual answer, when creating a JLabel with an empty string as the text the label's dimensions do not get set properly when using WindowBuilderPro. My labels did exist, and were being updated with the code provided in my question but the labels were not visible.
Starting with a label that has text in it, then setting the text to an empty string works properly.

The method paintImmediately() can be used to cause a Swing component to get updated immediately. after setText(), you should call paintImmediately() like below.
jLabel.setText("new text")
jLabel.paintImmediately(jLabel.getVisibleRect());

You should try to call revalidate() or repaint() on the component that contains your JLabels.
Cheers

Related

JTextField in JFrame uneditable when using JCEF in JInternalFrame until JFrame loses focus

I have started implementing JCEF in a project of mine, and I am initializing the embedded browser in a JInternalFrame inside of a JFrame, alongside a series of form fields on a JPanel next to the JInternalFrame. The browser component doesn't fully initialize until the JFrame actually becomes visible, and I'm finding that my JTextFields are uneditable unless the JFrame loses and regains focus.
Any idea of what could be happening and how to fix it? This only happens when using a JInternalFrame with the JCEF component...
It also happens every time I call loadURL to load a new page in the browser: the JTextFields become uneditable again, until I lose/gain focus in the JFrame.
UPDATE:
I have found a hack which allows the JTextFields to become editable again, but I wouldn't call it a solution because it is not very elegant. I added a load handler to the CefClient instance ( client.addLoadHandler(new CefLoadHandlerAdapter()) ) with an #Ovveride on the onLoadingStateChange method, which in turn gives access to the current browser component. From there I can detect when loading in the browser is complete, and use SwingUtilities to get the Window that the browser component is in. Then I setVisible(false) and setVisible(true) on that Window. I say it's not a solution because every time the browser is done loading the Window disappears and reappears. Even though the JTextFields are editable again, it is quite ugly to see the window flashing. I've tried all kinds of revalidate() and repaint() methods to no avail, unless I didn't call them right...
client.addLoadHandler(new CefLoadHandlerAdapter() {
#Override
public void onLoadingStateChange(CefBrowser browser, boolean isLoading,
boolean canGoBack, boolean canGoForward) {
if (!isLoading) {
//browser_ready = true;
System.out.println("Browser has finished loading!");
SwingUtilities.windowForComponent( browser.getUIComponent() ).setVisible(false);
SwingUtilities.windowForComponent( browser.getUIComponent() ).setVisible(true);
}
}
});
If anyone can suggest a better solution, please do!
I figured out the problem by studying the sample JCEF application a little better. I need to implement a FocusHandler in order to release the embedded browser's hold on keyboard input:
private boolean browserFocus_ = true;
---
jTextField1.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
if (!browserFocus_) return;
browserFocus_ = false;
KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
jTextField1.requestFocus();
}
});

Java (JFace Application Window) Setting external label text

I am looking to figure out how to set the text of a label on an external Application Window.
What I have:
I have two windows so far. The first one is the main application window that will appear when the user starts the program. The second window is another separate window that I have created specifically to display a custom error window.
The problem: I seem to be unable to call the label that I have created on the error window and set the text to something custom. Why? I want to be able to reuse this window many times! This window is aimed for things like error handling when there is invalid input or if the application cannot read/save to a file.
I was going to post screen shots but you need 10 rep for that. It would have explained everything better.
Here is the code for the label on the Error_dialog window:
Label Error_label = new Label(container, SWT.NONE);
Error_label.setBounds(10, 10, 348, 13);
Error_label.setText("Label I actively want to change!");
Here is the condition I would like to fire off when it is met:
if(AvailableSpaces == 10){
//Set the label text HERE and then open the window!
showError.open();
}
I have included this at the top of the class as well:
Error_dialog showError = new Error_dialog();
Just save the label as a field in your dialog class and add a 'setter' method. Something like:
public class ErrorDialog extends Dialog
{
private Label errorLabel;
... other code
public void setText(String text)
{
if (errorLabel != null && !errorLabel.isDisposed()) {
errorLabel.setText(text);
}
}
You will need to use your dialog like this:
ErrorDialog dialog = new ErrorDialog(shell);
dialog.create(); // Creates the controls
dialog.setText("Error message");
dialog.open();
Note: you should stick to the rules for Java variable names - they always start with lower case.
Further learn to use Layouts. Using setBounds will cause problems if the user is using different fonts.

Why doesn't the value passed to a method of a different class reflect in Java (using NetBeans 7.01)?

Before I start, Hi. This is is my first question here. I am not good with Java so have been trying and improve that and here it goes.
I am trying to create an email client and server application using sockets in Java. However I have been running into a problem. I have created a jFrame which is basically the Welcome window. The code is too huge to post so I'll post the relevant portions. There is a preferences jDialog. When the OK button on the dialog, an action handler comes in to play. The code:
private void okActionPerformed(java.awt.event.ActionEvent evt) {
Welcome wel = new Welcome();
wel.setStatusBar("Pressed OK");
dispose();
}
Obviously, the setStatusBar() sets the text of the statusLabel. The code for setStatusBar():
public void setStatusBar(String s)
{
statusLabel.setText(s);
}
Also, the preferences dialog is opened through menu item with this code:
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
settings pref=new settings(null,true);
pref.show();
}
The problem is if I set the status label from any other class, for instance settings class, it does not reflect but if I do so from the Welcome class ( the class where the statusLabel is present), it works fine. This problem is not only limited to this setStatus() but virtually pops up whenever I try to use a method of a different class.
If you guys need more of the code, I could post it. I would be grateful if could help a Java beginner out.
Thanks.
private void okActionPerformed(java.awt.event.ActionEvent evt) {
Welcome wel = new Welcome();
wel.setStatusBar("Pressed OK");
dispose();
}
You're creating a new (hence the keyword new) object of type Welcome. This new object is different from the already existing object of type Welcome, that you have created earlier. It thus has its own label, and you're setting the text of this different label, which is not displayed anywhere in the screen.
Java objects work like regular object. Let's say you would like a cool logo on one of your blue t-shirts. You go to a T-shirt vendor and ask him to print a cool logo. The vendor doesn't have your blue t-shirt. If the vendor gets another red t-shirt from his shop and prints the logo on this red t-shirt, your blue t-shirt will still have no logo at all.
For the vendor to be able to print a logo on your blue t-shirt, you need to give him this blue t-shirt. Same in Java: you need to pass the existing Welcome object to the preferences dialog, and the actionPerformed method must set the label on this Welcome object. Not on a new Welcome object.

How to force a Value change on a Vaadin RichTextArea component

I have developed a custom component consist of a layout and two labels within it. This layout is draggable. The code is similar to this :
DragAndDropWrapper boxWrap= new DragAndDropWrapper(layout);
mainLayout.addComponent(boxWrap);
After that I have a RichTextArea that allows the layout to be dropped in it. With this code.
RichTextArea richText= new RichTextArea;
DragAndDropWrapper dndWrapper = new DragAndDropWrapper(richText);
dndWrapper.setDropHandler(new DropHandler() {
public void drop(DragAndDropEvent event) {
//Do whatever you want when something is dropped
}
//Criterio de aceptacion
public AcceptCriterion getAcceptCriterion() {
return AcceptAll.get();
}
});
The code works fine. But when I drop the layout within the RichTextArea y want to get the Text written in this area and add some text but the method richText.getValue() is not updated unless I change the focus to another component or tab out. I guess there is not being communication with the server side so the value is not updated. Is there any way to force a a focus change when mousedown on the layout? I tried with JavaScript but i dont know how to add a onmousedown="function()" attribute to the layout component. I also tried extending RichTextArea and implementing the MouseListener or something or a TextChangeListener, but nothing works.
Any clue? Thank you.
PS: The component cannot be different from a RichTextArea.
Have you set richText.setImmediate(true); ?

How to check if the tab selected is changed in java

As far as i have seen the event:
(1) private void jTabbedPane1StateChanged(javax.swing.event.ChangeEvent evt) {}
Checks whether a new tab is added or an exiting tab is deleted or not.
On googling , i found this code:
(2) ChangeListener changeListener = new ChangeListener() {
public void stateChanged(ChangeEvent changeEvent) {
// my code
}
};
jTabbedPane1.addChangeListener(changeListener);
I guess since it uses stateChanged event , it should do what the same a my first code.
By t way even after using both the codes i could not get the required resuts(ie An event that could be invoked when user changes the tab).
Can anyone suggest me a good event [i am using netbeans GUI environment] for effective action. (I dont want any mouseEvents)
Edit:
I want the following code to be excecuted if the tab changes:
String send3=( jTabbedPane1.getSelectedComponent().getComponentAt(0,0)).getName();
The above code dynamically gets the name of jTextarea (in the current tab) which is created dynamically in the jTabbedPanel.
I just checked my own source code where addChangeListener() works fine. The event is fired whenever the tab is changed by the user or programatically. In stateChanged() itself, the now selected tab is determined by
JTabbedPane p = (JTabbedPane)e.getSource();
int idx = p.getSelectedIndex();

Categories