How to send signals between java swing forms?
I understand the "How to Use Actions" tutorial, but can't figure out how to make it work between multiple JFrame forms. I tried making updateComboBox method public static so it could just be accessed from other forms, but the NetBeans IDE refused to allow it since the auto-generated non-static variable jComboBox cannot be referenced from a static context. The primary form contains a JComboBox that needs to be modified based on user input (menus, buttons, text fields, etc.). Some of the widgets are on the primary form, others are on secondary forms. For example, the primary form makes a secondary form visible; the secondary form makes some changes to the configuration; then the user hides the secondary form by pressing the SAVE button. How can the secondary form best let the primary form know that the co开发者_C百科nfiguration has been updated and changes now need to be applied to the JComboBox? Is an Action a good fit for this or would some other method be more appropriate?
public class Controller extends javax.swing.JFrame {
...
private javax.swing.JComboBox jComboBox;
private void updateComboBox() {
String[] names = Configuration.getNames();
for (String n : names) {
jComboBox.addItem(n);
}
...
How about a controller class which will hold references to your frames and manage the signaling you need? You can also take a look at the Observer pattern, where your primary form will listen the changes made by the secondary form.
Since the second form does some setting modifications, I would assume that while the user is messing around with the settings, you would like to disable the user from using the main application.
What you can do is to create the first form and then create the settings form from within the first form. You can then use thread synchronization (such as locks) to make the 1st form wait until the user has pressed the "OK Button" on the settings form. Once that the "OK button" is pressed, the lock is removed and the 1st form will continue executing by calling methods pertaining to the 2nd form so that it can access the data that the user has just entered.
精彩评论