Link Java textbox to string in external class - java

I am currently working on a project in which I have a Java GUI class and another class which contains its relevant methods.
I want a text area in the GUI to be updated with the content of a string in the other class whenever it changes. What is the easiest way to watch for these changes?
Cheers!

You're looking for data binding. Java unfortunately has no own support for that, but there are several libraries to choose from, like for example JGoodies data binding.
If you want to roll your own, there's the ubiquitous observer pattern which you doubtless already know from Swing :). Just add listener support to the class holding the strings and add a listener to it that updates the text area, when an event comes.

Make the "other class" a proper bean that supports PropertyChangeListeners. Then create a PropertyChangeLister which acts on changes in the "other class" and which updates the textarea.
Something like this:
otherClass.addPropertyChangeListener("propertyname", new PropertyChangeListener() {
void propertyChange(PropertyChangeEvent evt) {
textarea.setText(evt.getNewValue());
}
}
See
https://docs.oracle.com/javase/1.5.0/docs/api/java/beans/PropertyChangeListener.html
https://docs.oracle.com/javase/1.5.0/docs/api/java/beans/PropertyChangeSupport.html
http://java.sun.com/docs/books/tutorial/javabeans/properties/bound.html

Have a look at BeansBinding
It does almost exactly what you need. Only thing is that your otherClass must support Java Beans listeners, as described by #ordnungswidrig

Related

Making several synth LookAndFeels coexist at the same time in a java swing application

I am working on a java swing application using synth Look and Feel.
There are already styles for every possible swing component
I must change the whole application's LookAndFeel, redefining different styles for every possible swing component.
I am now working on a sandbox, launched outside of the application. The sandbox loads my new set of styles, while the application still loads the old ones. No problems for now
However, I must then integrate it 'progressively' in the application. Meaning that in the same java application, some HMIs must use the old set of styles, while some must use the new ones
The difficulty being that each set of styles define synth "region" styles that automatically apply to the corresponding component, and I don't know how deal with several region styles that correspond to the same component type
Anybody has an idea of how I can do this ?
I saw that in swing's UIManager, one can change the LookAndFeel, but it then changes for the whole application
Only workaround I saw on the internet was to change the LookAndFeel before instanciating a Component, then change it back, which looks like an awful solution
Thanks in advance
Only workaround I saw on the internet was to change the LookAndFeel before instanciating a Component, then change it back, which looks like an awful solution
This is a very very very x 10 times bad solution.
I'm the author of the material-ui-swing and with the material style, you need to work with this concept of different style, and this is the main focus that I had during my development with the library, also because at the same time we integrate the library in one of the famous swing application called JMars where we need to respect a design system given by the UX team.
To make an example, material-ui-swing give two types of API:
one it the Material Theme System to define in a declarative way the theme around the App, and
the second is to give the lower-level API to implement the UI component with a different style.
In your case, we need the second power of material-ui-swing which is the lower-level API, and I will add an example also reported inside the repository online at the following link, and the complete doc is available here
A possible example of customization is the following on
public class ContainedButtonUI extends MaterialButtonUI {
//The propriety order inside the method installUI is important
//because some propriety should be override
#Override
public void installUI(JComponent c) {
super.mouseHoverEnabled = false;
super.installUI(c);
super.mouseHoverEnabled = true;
super.colorMouseHoverNormalButton = MaterialColors.PURPLE_500;
super.background = MaterialColors.PURPLE_700;
c.setBackground(super.background);
if(super.mouseHoverEnabled){
c.addMouseListener(
MaterialUIMovement.getMovement(c, this.colorMouseHoverNormalButton)
);
}
//If you want use this style also for Default button
// super.defaultBackground = MaterialColors.PURPLE_700;
//super.colorMouseHoverDefaultButton = MaterialColors.PURPLE_500;
super.borderEnabled = false;
}
After that to keep all your app architecture clean you can add the following specialization of JButton
/** #author https://github.com/vincenzopalazzo */
public class ContainedButton extends JButton {
public ContainedButton() {}
public ContainedButton(Icon icon) {
super(icon);
}
public ContainedButton(String text) {
super(text);
}
public ContainedButton(Action a) {
super(a);
}
public ContainedButton(String text, Icon icon) {
super(text, icon);
}
#Override
protected void init(String text, Icon icon) {
super.init(text, icon);
// When you don't want anymore you just delete the
// following line
setUI(new ContainedButtonUI());
}
Of curse, maybe the library can not help you in all your component styles, but nobody said that the library can not evolve with the help of the community.
A not complete description of components can be found here
Thank you all for your answers and sorry for my lack of reactivity during the holidays
I think I found a solution, which is not exactly what I asked for but answers my problem :
I will not make several LookAndFeels coexist.
Instead, I will load all styles, new and old, in the same LookAndFeel, and use different setName() for new and old components
For region styles (which was the problematic here), I will make a custom SynthStyleFactory which will redirect to the correct region style
Once all HMIs are migrated, I will delete the old styles and the custom factory which won't be needed anymore

Create a MultipageEditor for XML

I am working on an eclipse Plugin, and I would like to use an Editor, set some listeners on the current page(good terminology?), and remove these listeners when the user switches on another page (basically, the user is editing several files, as you could do with the default JAVA editor).
For the moment I have written a class extending StructuredTextEditor. The behavior of the plugin was the one expected, but when I try to work on several files, many problems occur. The main problem, according to me, is that I am not able to get notified when the user opens another page.
I read (and tested) a few things about MultiPageEditor, but it seems like it doesn't integrate an XML editor as default editor. How should I proceed in order to get a MultiPageEditor, with XML syntax coloring, and get notified when the user changes the current page to adjust my listeners ?
Thanks for reading.
the code is not perfect but at least you will have an example of a MultiPageEditor integrating an XMLEditor: https://github.com/fusesource/fuseide/blob/8.0.0.Beta2/editor/plugins/org.fusesource.ide.camel.editor/src/org/fusesource/ide/camel/editor/CamelEditor.java
The idea is to call addPage(new StructuredTextEditor()) inside createPages() method.
regards,
In your editor you can listen to selection changes in the editor text using:
getSelectionProvider().addSelectionChangedListener(listener);
where listener implements ISelectionChangedListener.
This applies to any editor derived from AbstractTextEditor (which includes StructuredTextEditor.
You need to do this fairly late in the editor creation. In the createPartControl method works:
#Override
public void createPartControl(final Composite parent)
{
super.createPartControl(parent);
getSelectionProvider().addSelectionChangedListener(listener);
}

How to get values from a JPanel?

I've created a JPanel using the NetBeans designer filled with JTextFields and a submit button. I would like to get the values from those JTextFields and use them in my main class. How can I do that?
Also, what are some good tutorials that can help me further understand this? Thank you.
I'm guessing you mean JTextField and not TextField. Use the getText() method.
String text = yourTextField.getText();
Also works with the TextField class, actually.
You'll need an ActionListener on your submit button if you want to grab the text fields' values when a user clicks the button.
public void actionPerformed(ActionEvent e) {
if (e.getSource() == yourButtonsName) {
text = yourTextField.getText();
}
}
Don't forget to add the ActionListener!
yourButtonsName.addActionerListener(this);
Or you could use Java 8 lambda expression:
yourButtonsName.addActionerListener(e -> text = yourTextField.getText);
If you'd like to learn more about Java's graphical capabilities, I recommend the Oracle docs: http://docs.oracle.com/javase/tutorial/uiswing/.
"I've created a JPanel using the NetBeans designer filled with JTextFields and a submit button. I would like to get the values from those JTextFields and use them in my main class. How can I do that?"
Sounds like to me you're facing the class problem of how do I reference instance variables from one, in another.
An easy way would be to pass one class as reference to another and use proper getters and setters. You can see a solution here.
A better solution though would be to create an interface that one of the classes implements and pass that class as an interface to the second class. You can see an example here.
If you feel you're ready for more advanced topics, you should look into MCV Design patterns for this type of problem. MVC is designed for multi-component interaction.

Add extended control to form - NetBeans

I'm new to Java, so need a little bit help:
Programming in Java I use NetBeans. So, in making forms, I use already existing swing controls just placing them on the form. But, for example, I want to improve control as a point add some new action listeners, so good solution would be override it.
I can create new class and write:
public class ExtendedControl extends Control
{
}
But, is it possible to add ExtendedControl to form automatically (like original controls)?
You will need to write your own JavaBean Components. This can be easily done with Netbeans.
Once you are done you can add your JavaBean to the Beans Folder, or wherever you wish, in the Palette Manager.
Here is the manual and here is an example that shows you how to proceed.
These are the few steps, necessary in order to add to the Palette.

How to dynamicly build up a gui

currently im building an application which is supposed for some sound processing. I'm doing this in java/eclipse with swt/jface.
The processing itself need some options/properties for the algorithem inside. At this time, i have a .properties file which holds all options like:
trimLeadingSilence=20
trimtrailingSilence=20
trimhold=5
fftFrameSize=512
...
I don't want the user to edit these options in a texteditor like notepad++, but within the gui of my app.
Now I think about how to do this. I have 2 "ideas":
Create a class for each option set, and manualy code all these boring gui code lines. Like here for just one option ;-)
Spinner spinnerSilenceBack = new Spinner(shell, SWT.BORDER);
spinnerSilenceBack.setMinimum(0);
spinnerSilenceBack.setMaximum(200);
selection = Integer.valueOf(PropertyManager.getPropertyValue("trimming", "trailingSilence"));
spinnerSilenceBack.setSelection(selection);
spinnerSilenceBack.setIncrement(5);
spinnerSilenceBack.setPageIncrement(20);
spinnerSilenceBack.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
int selection = ((Spinner) e.getSource()).getSelection();
int digits = ((Spinner) e.getSource()).getDigits();
int result = (int) (selection / Math.pow(10, digits));
PropertyManager.setPropertyValue("trimming", "trailingSilence", String
.valueOf(result));
}
});
This takes a lot of time due to the fact that there are a lot of different options. So I thought about how I can dynamicly create such gui code, or just dynamicly create these gui windows when starting up the application. At least I would need a config file for the "gui creator" but I don't want to reinvent such a thing-thats why i ask you guys :)
I couldn't get clearly what you are asking.
But, since your question was How to dynamicly build up a gui, i have a a suggestion:
You could use Java Template Engine
library like Freemarker. This
would help you create GUI's that can
be built to work on the fly. With
freemarker you can have one single
template file and then replace the
values accordingly.
I have used it to generate HTML files on the fly. You could evaluate if you can use it otherwise. The API Documentation is rich. So you could go through that once.
Do you mean, you want to make an UI which will have all options you specified? It doesn't matter its a form OR a menu, its up to you. But yeah you can surely configure the names and types in .properties file.
See, you build a Menu OR form in AWT/Swing OR Servlet, but you can read it from properties file right?
You can also configure the same using Spring bean XML definitions, which can provide more support like you can specify all details in some Map OR List etc...
thanks.
I didn't use Swing for a lot of time, so here is just a basic principle.
Config should be done in xml, .properties file is bad here, cuz it doesn't describe objects out-of-the-box.
Add button ("Apply config"), attach actionListener, which 1)parses xml config, 2)then creates form or change settings of existing form, textarea, colors etc.
example for xml config:
found - check it's x_coordinate, y_coord (or use layoutManager, depends on logic), action, than jframe.getLayout().add(new Button(x_coord, y_coord, action).
found - the same.
than jframe.setVisible(true);

Categories