Java (JFace Application Window) Setting external label text - java

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.

Related

Buttons Generating other Buttons

So, i'm asking cause i searched and didn't found nothing about this, i don't know if i'm only searching it wrong.
I'm building a POS (Point of Sale) for my final School work but instead off adding the buttons manually i wanted to make an interface for the admn where he could add the buttons to the main project (ex. I want to add the button for Meat, Fish, etc.)
It's much likely to be easy to do it, my other doubt becomes with, if the button is generated how it will be called so i can use it later on?
With the NetBeans form designer you can see what code must be created.
Then instead of jButton1, jButton2 use List<JButton> buttons = new ArrayList<>();
In the initComponents (or after its call) create the buttons dynamically, using some list with button data: caption Meat / Fish / ... and so on. These data could come from a file you generated, so they are persist even if quitting the application.
A file can be read as:
Path path = Paths.get("buttons.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
for (String line : lines) {
String[] words = line.split(";\\s*");
if (words.length > 2 && words[0].equals("button")) {
JButton button = new JButton(word[1]);
button.addActionListener(this); ...
... add(button);
buttons.add(button);
}
}
I think you shouldn't generate new buttons. The best way is to hide the buttons you've created by calling button.setVisibility(View.Gone). So just create buttons and call setVisibility(View.Gone) in onCreate. And where needed make them visible by calling button.setVisibility(View.visible).

How call a JFrame from my Application Window SWT Builder

Here is my code in my ApplicationWindow. I have a widgetSelected happening for a bottom called "Welcome" that I want to open a new window with text, which I already have programmed.
//Welcome was clicked
mntmWelcome.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
Welcome2 newWindow = new Welcome2();
newWindow.setVisible(true);
}
});
And the welcome is a JDialog only showing some text and stuff, but when I use this the program crashes and I get
java.lang.IllegalArgumentException: defaultCloseOperation must be one of: DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE, or DISPOSE_ON_CLOSE
and I have no idea where to set this, i tried within the override but the window never opens. I just want it to open and the previous window should still be there behind. How can I solve this?
Try adding this:
newWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Please, refer to: https://chortle.ccsu.edu/java5/Notes/chap56/ch56_9.html
and read this https://docs.oracle.com/javase/7/docs/api/javax/swing/WindowConstants.html.
Documentations are really useful for beginners.

How to name application and give it an icon?

I'm working in eclipse and I have made an application without name and icon. When i start the application it's a really creepy name displaying in the upper left corner (Mac). It's some thing like. I wonder how I can change this to my own name. Second question is how i can change the icon. Can I do that in eclipse?
If you're using JFrames, you can try setting the icon image as follows.
frame.setIconImage(img);
Also, by name it sounds a bit like you mean the frame's title. When you create the a frame, you can set the title as follows:
Frame frame = new JFrame("Title goes here");
To change name: How to change an Android app's name?
To change icon: How to change the icon of an Android app in Eclipse?
It's already here at stackoverflow, please check if your answers are here before posting.
The prefered method would be to create a Mac OS application bundle (and the bundler), but if this seems like to much work, you can supply custom properties to, for example, you could supply the Xdock:name property when running the application, for example...
-DXdock:name="Application Name"
If you can't do that, you can set it when your application runs, for example...
public static void main(String[] args) {
try {
// Sets the application name on the menu bar
System.setProperty("Xdock:name", "Application Name");
// Set the applications dock icon...
Application application = Application.getApplication();
application.setDockIconImage(ImageIO.read(TestDockIcon.class.getResource("/Icon.png")));
// Start the application...
new TestDockIcon();
} catch (IOException exp) {
exp.printStackTrace();
}
}

JLabel does not update when using setText method

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

Java GUI, Multiple Frames

How do I go about creating what I describe below?
First, here is the basic look of my GUI:
When I click on Add New Account I want to have the GUI pop up a small window where the user can enter log-in credentials. I would need this information to be passed back into the main GUI, so I am lost as how to approach this.
The same goes for Preferences or Remove Account. How do I go about creating a "GUI Overlay" of sorts. Sorry, I can't figure out the correct terminology for the effect I am looking for.
I wanted to attempt to use JOptionPane's, but after some research this seemed like it was not the route to be taking.
I was also toying with the idea of creating a new JFrame when the action was preformed. How should this be approached?
Start by using dialogs over frames. Dialogs are designed to gather small pieces of information from the user.
I would create a separate component for each operation you want to perform. Within these components I would provide setters and getters to allow you to gain access to the information managed by the component.
From there I would either use a JOptionPane or JDialog to display the component to the user. The reason for using one over the other for me comes down to begin able to control the action buttons (Okay and Cancel for example). For something like the login dialog, I want to restrict the user from begin able to hit the Login button until they've provided enough information to make the attempt.
The basic follow would be something like this...
LoginDialog dialog = new LoginDialog(SwingUtilities.getWindowAncestor(this)); // this is a reference any valid Component
dialog.setModal(true); // I would have already done this internally to the LoginDialog class...
dialog.setVisible(true); // A modal dialog will block at this point until the window is closed
if (dialog.isSuccessfulLogin()) {
login = dialog.getLogin(); // Login is a simple class containing the login information...
}
The LoginDialog might look something like this...
public class LoginDialog extends JDialog {
private LoginPanel loginPane;
public LoginDialog(Window wnd) {
super(wnd);
setModal(true);
loginPane = new LoginPanel();
setLayout(new BorderLayout());
add(loginPane);
// Typically, I create another panel and add the buttons I want to use to it.
// These buttons would call dispose once they've completed there work
}
public Login getLogin() {
return loginPane.getLogin();
}
public boolean isSuccessfulLogin() {
return loginPane.isSuccessfulLogin();
}
}
The dialog is simply acting as proxy/container for the login pane.
This is, of course an overview, you will need to fill in the blanks ;)
Now, if you don't want to go to the trouble of creating your own dialog, you can take advantage of the JOptionPane instead.
LoginPanel loginPane = new LoginPanel();
int option = JOptionPane.showOptionDialog(
this, // A reference to the parent component
loginPane,
"Login", // Title
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, // You can supply your own icon it if you want
new Object[]{"Login", "Cancel"}, // The available options to the user
"Login" // The "initial" option
);
if (option == 0) {
// Attempt login...
}

Categories