Try to fix warnings by NetBeans

This commit is contained in:
huangyuhui
2016-01-26 20:17:05 +08:00
parent 409fc83819
commit fee3e5251d
15 changed files with 907 additions and 1063 deletions

View File

@@ -77,7 +77,7 @@ public class ModpackWizard extends WizardBranchController {
service.version(), service.version(),
(String) settings.get(ModpackInitializationPanel.KEY_GAME_VERSION), (String) settings.get(ModpackInitializationPanel.KEY_GAME_VERSION),
blackList); blackList);
progress.finished(Summary.create(C.i18n("modpack.export_finished") + ": " + loc.getAbsolutePath(), null)); progress.finished(new Summary(C.i18n("modpack.export_finished") + ": " + loc.getAbsolutePath(), null));
} catch (IOException | GameException ex) { } catch (IOException | GameException ex) {
HMCLog.err("Failed to export modpack", ex); HMCLog.err("Failed to export modpack", ex);
progress.failed(C.i18n("modpack.export_error") + ": " + ex.getClass().getName() + ", " + ex.getLocalizedMessage(), true); progress.failed(C.i18n("modpack.export_error") + ": " + ex.getClass().getName() + ", " + ex.getLocalizedMessage(), true);

View File

@@ -207,15 +207,13 @@ public abstract class WizardDisplayer {
if (new HashSet(Arrays.asList(s)).size() != s.length) if (new HashSet(Arrays.asList(s)).size() != s.length)
throw new RuntimeException("steps are duplicated: " + Arrays.asList(s)); throw new RuntimeException("steps are duplicated: " + Arrays.asList(s));
if (s.length == 1 && Wizard.UNDETERMINED_STEP.equals(s[0])) if (s.length == 1 && Wizard.UNDETERMINED_STEP.equals(s[0]))
// assert false : "Only ID may not be UNDETERMINED_ID"; //NOI18N // assert false : "Only ID may not be UNDETERMINED_ID";
throw new RuntimeException("Only ID may not be UNDETERMINED_ID"); throw new RuntimeException("Only ID may not be UNDETERMINED_ID");
for (int i = 0; i < s.length; i++) for (int i = 0; i < s.length; i++)
if (Wizard.UNDETERMINED_STEP.equals(s[i]) && i != s.length - 1) if (Wizard.UNDETERMINED_STEP.equals(s[i]) && i != s.length - 1)
// assert false : "UNDETERMINED_ID may only be last element in" + //NOI18N // assert false : "UNDETERMINED_ID may only be last element in" +
// " ids array " + Arrays.asList(s); //NOI18N // " ids array " + Arrays.asList(s);
throw new RuntimeException("UNDETERMINED_ID may only be last element in" throw new RuntimeException("UNDETERMINED_ID may only be last element in ids array " + Arrays.asList(s));
+ //NOI18N
" ids array " + Arrays.asList(s)); //NOI18N)
return true; return true;
} }

View File

@@ -12,7 +12,6 @@ import java.awt.Window;
import java.awt.event.ActionEvent; import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; import java.awt.event.ActionListener;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.logging.Logger;
import javax.swing.Action; import javax.swing.Action;
import javax.swing.BorderFactory; import javax.swing.BorderFactory;
@@ -62,9 +61,6 @@ public class NavButtonManager implements ActionListener {
*/ */
static final String DEFERRED_FAILED = "FAILED_"; static final String DEFERRED_FAILED = "FAILED_";
private static final Logger logger
= Logger.getLogger(NavButtonManager.class.getName());
JButton next = null; JButton next = null;
JButton prev = null; JButton prev = null;
@@ -105,7 +101,7 @@ public class NavButtonManager implements ActionListener {
prev.setName(NAME_PREV); prev.setName(NAME_PREV);
prev.setMnemonic(C.i18n("wizard.prev_mnemonic").charAt(0)); prev.setMnemonic(C.i18n("wizard.prev_mnemonic").charAt(0));
finish = new JButton(C.i18n("wizard.finish")); // NOI18N finish = new JButton(C.i18n("wizard.finish"));
finish.setName(NAME_FINISH); finish.setName(NAME_FINISH);
finish.setMnemonic(C.i18n("wizard.finish_mnemonic").charAt(0)); finish.setMnemonic(C.i18n("wizard.finish_mnemonic").charAt(0));
@@ -127,7 +123,7 @@ public class NavButtonManager implements ActionListener {
help.setVisible(helpAction != null); help.setVisible(helpAction != null);
// Use standard default-button-last order on Aqua L&F // Use standard default-button-last order on Aqua L&F
final boolean aqua = "Aqua".equals(UIManager.getLookAndFeel().getID()); // NOI18N final boolean aqua = "Aqua".equals(UIManager.getLookAndFeel().getID());
buttons = new JPanel() { buttons = new JPanel() {
public void doLayout() { public void doLayout() {
@@ -163,7 +159,7 @@ public class NavButtonManager implements ActionListener {
} }
}; };
buttons.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, UIManager buttons.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, UIManager
.getColor("textText"))); // NOI18N .getColor("textText")));
buttons.add(prev); buttons.add(prev);
buttons.add(next); buttons.add(next);
@@ -494,7 +490,6 @@ public class NavButtonManager implements ActionListener {
boolean closeWindow; boolean closeWindow;
if (reallyCancel && parent.cancel()) { if (reallyCancel && parent.cancel()) {
logger.fine("calling wizard cancel method on " + wizard);
wizard.cancel(settings); wizard.cancel(settings);
return; return;
} }
@@ -530,7 +525,7 @@ public class NavButtonManager implements ActionListener {
if (window != null && parent.receiver == null && window instanceof JDialog) if (window != null && parent.receiver == null && window instanceof JDialog)
((JDialog) window).getRootPane().setDefaultButton(cancel); ((JDialog) window).getRootPane().setDefaultButton(cancel);
cancel.setText(getCloseString()); // NOI18N cancel.setText(getCloseString());
cancel.setMnemonic(C.i18n("wizard.close_mnemonic").charAt(0)); cancel.setMnemonic(C.i18n("wizard.close_mnemonic").charAt(0));
cancel.setName(NAME_CLOSE); cancel.setName(NAME_CLOSE);
deferredStatus = null; // ?? should summary be different deferredStatus = null; // ?? should summary be different

View File

@@ -3,12 +3,12 @@ package org.jackhuang.hellominecraft.utils.views.wizard.api.displayer;
import java.awt.Container; import java.awt.Container;
import java.awt.EventQueue; import java.awt.EventQueue;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.util.logging.Logger;
import javax.swing.JLabel; import javax.swing.JLabel;
import javax.swing.JProgressBar; import javax.swing.JProgressBar;
import javax.swing.border.EmptyBorder; import javax.swing.border.EmptyBorder;
import org.jackhuang.hellominecraft.utils.C; import org.jackhuang.hellominecraft.utils.C;
import org.jackhuang.hellominecraft.utils.logging.HMCLog;
import org.jackhuang.hellominecraft.utils.views.wizard.spi.ResultProgressHandle; import org.jackhuang.hellominecraft.utils.views.wizard.spi.ResultProgressHandle;
import org.jackhuang.hellominecraft.utils.views.wizard.spi.Summary; import org.jackhuang.hellominecraft.utils.views.wizard.spi.Summary;
@@ -28,9 +28,6 @@ import org.jackhuang.hellominecraft.utils.views.wizard.spi.Summary;
*/ */
public class NavProgress implements ResultProgressHandle { public class NavProgress implements ResultProgressHandle {
private static final Logger logger
= Logger.getLogger(NavProgress.class.getName());
JProgressBar progressBar = new JProgressBar(); JProgressBar progressBar = new JProgressBar();
JLabel lbl = new JLabel(); JLabel lbl = new JLabel();
@@ -61,7 +58,7 @@ public class NavProgress implements ResultProgressHandle {
public void setProgress(final String description, final int currentStep, final int totalSteps) { public void setProgress(final String description, final int currentStep, final int totalSteps) {
invoke(() -> { invoke(() -> {
lbl.setText(description == null ? " " : description); // NOI18N lbl.setText(description == null ? " " : description);
setProgress(currentStep, totalSteps); setProgress(currentStep, totalSteps);
}); });
} }
@@ -99,8 +96,7 @@ public class NavProgress implements ResultProgressHandle {
try { try {
EventQueue.invokeAndWait(r); EventQueue.invokeAndWait(r);
} catch (InvocationTargetException | InterruptedException ex) { } catch (InvocationTargetException | InterruptedException ex) {
ex.printStackTrace(); HMCLog.err("NavProgress: Error invoking operation", ex);
logger.severe("Error invoking operation " + ex.getClass().getName() + " " + ex.getMessage());
} }
} }
@@ -127,7 +123,7 @@ public class NavProgress implements ResultProgressHandle {
Runnable r = () -> { Runnable r = () -> {
// cheap word wrap // cheap word wrap
JLabel comp = new JLabel("<html><body>" + message); // NOI18N JLabel comp = new JLabel("<html><body>" + message);
comp.setBorder(new EmptyBorder(5, 5, 5, 5)); comp.setBorder(new EmptyBorder(5, 5, 5, 5));
parent.setCurrentWizardPanel(comp); parent.setCurrentWizardPanel(comp);
parent.getTtlLabel().setText(C.i18n("wizard.failed")); parent.getTtlLabel().setText(C.i18n("wizard.failed"));

View File

@@ -34,8 +34,6 @@ import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent; import java.awt.event.WindowEvent;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.util.Map; import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction; import javax.swing.AbstractAction;
import javax.swing.Action; import javax.swing.Action;
import javax.swing.BorderFactory; import javax.swing.BorderFactory;
@@ -125,7 +123,7 @@ public class WizardDisplayerImpl extends WizardDisplayer {
ttlLabel = new JLabel(wizard.getStepDescription(wizard.getAllSteps()[0])); ttlLabel = new JLabel(wizard.getStepDescription(wizard.getAllSteps()[0]));
ttlLabel.setBorder(BorderFactory.createCompoundBorder(BorderFactory ttlLabel.setBorder(BorderFactory.createCompoundBorder(BorderFactory
.createEmptyBorder(5, 5, 12, 5), BorderFactory.createMatteBorder(0, 0, 1, 0, UIManager .createEmptyBorder(5, 5, 12, 5), BorderFactory.createMatteBorder(0, 0, 1, 0, UIManager
.getColor("textText")))); // NOI18N .getColor("textText"))));
ttlPanel = new JPanel() { ttlPanel = new JPanel() {
public void doLayout() { public void doLayout() {
Dimension d = ttlLabel.getPreferredSize(); Dimension d = ttlLabel.getPreferredSize();
@@ -142,7 +140,7 @@ public class WizardDisplayerImpl extends WizardDisplayer {
ttlPanel.add(ttlLabel); ttlPanel.add(ttlLabel);
Font f = ttlLabel.getFont(); Font f = ttlLabel.getFont();
if (f == null) if (f == null)
f = UIManager.getFont("controlFont"); // NOI18N f = UIManager.getFont("controlFont");
if (f != null) { if (f != null) {
f = f.deriveFont(Font.BOLD); f = f.deriveFont(Font.BOLD);
ttlLabel.setFont(f); ttlLabel.setFont(f);
@@ -173,7 +171,7 @@ public class WizardDisplayerImpl extends WizardDisplayer {
outerPanel = new JPanel(); outerPanel = new JPanel();
if (wizard.getAllSteps().length == 0) if (wizard.getAllSteps().length == 0)
throw new IllegalArgumentException("Wizard has no steps"); // NOI18N throw new IllegalArgumentException("Wizard has no steps");
// initialize the ttl* stuff // initialize the ttl* stuff
buildStepTitle(); buildStepTitle();
@@ -190,8 +188,8 @@ public class WizardDisplayerImpl extends WizardDisplayer {
} }
}; };
outerPanel.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW).put( outerPanel.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "cancel"); //NOI18N KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "cancel");
outerPanel.getActionMap().put("cancel", kbdCancel); //NOI18N outerPanel.getActionMap().put("cancel", kbdCancel);
instructions = createInstructionsPanel(); instructions = createInstructionsPanel();
@@ -202,7 +200,7 @@ public class WizardDisplayerImpl extends WizardDisplayer {
inner.add(ttlPanel, BorderLayout.NORTH); inner.add(ttlPanel, BorderLayout.NORTH);
problem = new JLabel(" "); problem = new JLabel(" ");
Color fg = UIManager.getColor("nb.errorColor"); // NOI18N Color fg = UIManager.getColor("nb.errorColor");
problem.setForeground(fg == null ? Color.BLUE : fg); problem.setForeground(fg == null ? Color.BLUE : fg);
inner.add(problem, BorderLayout.SOUTH); inner.add(problem, BorderLayout.SOUTH);
problem.setPreferredSize(new Dimension(20, 20)); problem.setPreferredSize(new Dimension(20, 20));
@@ -254,10 +252,9 @@ public class WizardDisplayerImpl extends WizardDisplayer {
public Object show(final Wizard awizard, Rectangle bounds, Action helpAction, public Object show(final Wizard awizard, Rectangle bounds, Action helpAction,
Map initialProperties) { Map initialProperties) {
if (!EventQueue.isDispatchThread() && !warned) { if (!EventQueue.isDispatchThread() && !warned) {
Logger.getLogger(WizardDisplayerImpl.class.getName()).log(Level.WARNING, HMCLog.warn("WizardDisplayerImpl: show() should be called from the AWT Event Thread. This "
"show() should be called from the AWT Event Thread. This " + "call may deadlock - c.f. "
+ "call may deadlock - c.f. " + "http://java.net/jira/browse/WIZARD-33", new Throwable());
+ "http://java.net/jira/browse/WIZARD-33", new Throwable());
warned = true; warned = true;
} }
createOuterPanel(awizard, bounds, helpAction, initialProperties); createOuterPanel(awizard, bounds, helpAction, initialProperties);
@@ -364,8 +361,7 @@ public class WizardDisplayerImpl extends WizardDisplayer {
return; return;
default: default:
throw new IllegalArgumentException("Illegal forward " throw new IllegalArgumentException("Illegal forward "
+ // NOI18N + "navigation mode: " + i);
"navigation mode: " + i); // NOI18N
} }
} }
@@ -450,7 +446,7 @@ public class WizardDisplayerImpl extends WizardDisplayer {
} }
} }
else { else {
synchronized (this) { synchronized (WizardDisplayerImpl.this) {
deferredResult = null; deferredResult = null;
} }
buttonManager.getCancel().setEnabled(true); buttonManager.getCancel().setEnabled(true);
@@ -463,7 +459,7 @@ public class WizardDisplayerImpl extends WizardDisplayer {
} }
} }
}; };
Thread runner = new Thread(run, "Wizard Background Result Thread " + r); // NOI18N Thread runner = new Thread(run, "Wizard Background Result Thread " + r);
runner.start(); runner.start();
} }
@@ -553,7 +549,7 @@ public class WizardDisplayerImpl extends WizardDisplayer {
void updateProblem() { void updateProblem() {
String prob = wizard.getProblem(); String prob = wizard.getProblem();
problem.setText(prob == null ? " " : prob); // NOI18N problem.setText(prob == null ? " " : prob);
if (prob != null && prob.trim().length() == 0) if (prob != null && prob.trim().length() == 0)
// Issue 3 - provide ability to disable next w/o // Issue 3 - provide ability to disable next w/o
// showing the error line // showing the error line

View File

@@ -72,7 +72,7 @@ public class InstructionsPanelImpl extends JComponent implements WizardObserver,
public InstructionsPanelImpl(Wizard wiz) { public InstructionsPanelImpl(Wizard wiz) {
this(null, wiz); this(null, wiz);
Font f = UIManager.getFont("Tree.font"); //NOI18N Font f = UIManager.getFont("Tree.font");
if (f != null) if (f != null)
setFont(f); setFont(f);
} }
@@ -123,9 +123,9 @@ public class InstructionsPanelImpl extends JComponent implements WizardObserver,
//In the event of classloader issues, also have a way to get //In the event of classloader issues, also have a way to get
//the image from UIManager - slightly more portable for large //the image from UIManager - slightly more portable for large
//apps //apps
img = (BufferedImage) UIManager.get("wizard.sidebar.image"); //NOI18N img = (BufferedImage) UIManager.get("wizard.sidebar.image");
String imgStr = System.getProperty("wizard.sidebar.image"); //NOI18N String imgStr = System.getProperty("wizard.sidebar.image");
//image has not been loaded and user wishes to supply their own image //image has not been loaded and user wishes to supply their own image
if (img == null && imgStr != null) { if (img == null && imgStr != null) {
//get an URL, works for jars //get an URL, works for jars
@@ -137,21 +137,20 @@ public class InstructionsPanelImpl extends JComponent implements WizardObserver,
img = ImageIO.read(url); img = ImageIO.read(url);
} catch (IOException ioe) { } catch (IOException ioe) {
System.err.println("Could not load wizard image " System.err.println("Could not load wizard image "
+ //NOI18N + ioe.getMessage());
ioe.getMessage()); System.setProperty("wizard.sidebar.image", null);
System.setProperty("wizard.sidebar.image", null); //NOI18N
img = null; //error loading img, set to null to use default img = null; //error loading img, set to null to use default
} }
else { //URL was not successfully parsed, set img to null to use default else { //URL was not successfully parsed, set img to null to use default
System.err.println("Bad URL for wizard image " + imgStr); //NOI18N System.err.println("Bad URL for wizard image " + imgStr);
System.setProperty("wizard.sidebar.image", null); //NOI18N System.setProperty("wizard.sidebar.image", null);
img = null; img = null;
} }
} }
if (img == null) if (img == null)
try { try {
img = ImageIO.read(InstructionsPanelImpl.class.getResourceAsStream( img = ImageIO.read(InstructionsPanelImpl.class.getResourceAsStream(
"/org/jackhuang/hellominecraft/wizard.jpg")); //NOI18N "/org/jackhuang/hellominecraft/wizard.jpg"));
} catch (IOException ioe) { } catch (IOException ioe) {
HMCLog.err("Failed to load wizard.jpg, maybe you fucking modified the launcher", ioe); HMCLog.err("Failed to load wizard.jpg, maybe you fucking modified the launcher", ioe);
} }
@@ -189,7 +188,7 @@ public class InstructionsPanelImpl extends JComponent implements WizardObserver,
public final void paintComponent(Graphics g) { public final void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g; Graphics2D g2d = (Graphics2D) g;
Font f = getFont() != null ? getFont() : UIManager.getFont("controlFont"); //NOI18N Font f = getFont() != null ? getFont() : UIManager.getFont("controlFont");
FontMetrics fm = g.getFontMetrics(f); FontMetrics fm = g.getFontMetrics(f);
Insets ins = getInsets(); Insets ins = getInsets();
int dx = ins.left; int dx = ins.left;
@@ -202,13 +201,13 @@ public class InstructionsPanelImpl extends JComponent implements WizardObserver,
//Don't fetch step list if in summary page, there will //Don't fetch step list if in summary page, there will
//only be the base ones //only be the base ones
steps = wizard.getAllSteps(); steps = wizard.getAllSteps();
String steps[] = this.steps; String[] steps2 = this.steps;
if (inSummaryPage) { if (inSummaryPage) {
String summaryStep = C.i18n("wizard.summary"); String summaryStep = C.i18n("wizard.summary");
String[] nue = new String[steps.length + 1]; String[] nue = new String[steps2.length + 1];
System.arraycopy(steps, 0, nue, 0, steps.length); System.arraycopy(steps2, 0, nue, 0, steps2.length);
nue[nue.length - 1] = summaryStep; nue[nue.length - 1] = summaryStep;
steps = nue; steps2 = nue;
} }
int y = fm.getMaxAscent() + ins.top + MARGIN; int y = fm.getMaxAscent() + ins.top + MARGIN;
int x = ins.left + MARGIN; int x = ins.left + MARGIN;
@@ -228,27 +227,27 @@ public class InstructionsPanelImpl extends JComponent implements WizardObserver,
y += h + 10; y += h + 10;
int first = 0; int first = 0;
int stop = steps.length; int stop = steps2.length;
boolean wontFit = y + (h * (steps.length)) > getHeight(); boolean wontFit = y + (h * (steps2.length)) > getHeight();
if (wontFit) { if (wontFit) {
//try to center the current step //try to center the current step
int availHeight = bottom - y; int availHeight = bottom - y;
int willFit = availHeight / h; int willFit = availHeight / h;
int currStepIndex = Arrays.asList(steps).indexOf(currentStep); int currStepIndex = Arrays.asList(steps2).indexOf(currentStep);
int rangeStart = Math.max(0, currStepIndex - (willFit / 2)); int rangeStart = Math.max(0, currStepIndex - (willFit / 2));
int rangeEnd = Math.min(rangeStart + willFit, steps.length); int rangeEnd = Math.min(rangeStart + willFit, steps2.length);
if (rangeStart + willFit > steps.length) { if (rangeStart + willFit > steps2.length) {
//Don't scroll off if there's room //Don't scroll off if there's room
rangeStart = steps.length - willFit; rangeStart = steps2.length - willFit;
rangeEnd = steps.length; rangeEnd = steps2.length;
} }
steps = (String[]) steps.clone(); steps2 = (String[]) steps2.clone();
if (rangeStart != 0) { if (rangeStart != 0) {
steps[rangeStart] = elipsis; steps2[rangeStart] = elipsis;
first = rangeStart; first = rangeStart;
} }
if (rangeEnd != steps.length && rangeEnd > 0) { if (rangeEnd != steps2.length && rangeEnd > 0) {
steps[rangeEnd - 1] = elipsis; steps2[rangeEnd - 1] = elipsis;
stop = rangeEnd; stop = rangeEnd;
} }
} }
@@ -257,25 +256,25 @@ public class InstructionsPanelImpl extends JComponent implements WizardObserver,
g.setColor(getForeground()); g.setColor(getForeground());
for (int i = first; i < stop; i++) { for (int i = first; i < stop; i++) {
boolean isUndetermined = Wizard.UNDETERMINED_STEP.equals(steps[i]); boolean isUndetermined = Wizard.UNDETERMINED_STEP.equals(steps2[i]);
boolean canOnlyFinish = wizard.getForwardNavigationMode() boolean canOnlyFinish = wizard.getForwardNavigationMode()
== Wizard.MODE_CAN_FINISH; == Wizard.MODE_CAN_FINISH;
if (isUndetermined && canOnlyFinish) if (isUndetermined && canOnlyFinish)
break; break;
String curr; String curr;
if (!elipsis.equals(steps[i])) if (!elipsis.equals(steps2[i]))
if (inSummaryPage && i == this.steps.length) if (inSummaryPage && i == this.steps.length)
curr = (i + 1) + ". " + steps[i]; curr = (i + 1) + ". " + steps2[i];
else else
curr = (i + 1) + ". " + (isUndetermined curr = (i + 1) + ". " + (isUndetermined
? elipsis ? elipsis
: steps[i].equals(elipsis) ? elipsis : steps2[i].equals(elipsis) ? elipsis
: wizard.getStepDescription(steps[i])); : wizard.getStepDescription(steps2[i]));
else else
curr = elipsis; curr = elipsis;
if (curr != null) { if (curr != null) {
boolean selected = (steps[i].equals(currentStep) && !inSummaryPage) boolean selected = (steps2[i].equals(currentStep) && !inSummaryPage)
|| (inSummaryPage && i == steps.length - 1); || (inSummaryPage && i == steps2.length - 1);
if (selected) if (selected)
g.setFont(boldFont); g.setFont(boldFont);
@@ -297,7 +296,7 @@ public class InstructionsPanelImpl extends JComponent implements WizardObserver,
public final Dimension getPreferredSize() { public final Dimension getPreferredSize() {
Font f = getFont() != null ? getFont() Font f = getFont() != null ? getFont()
: UIManager.getFont("controlFont"); //NOI18N : UIManager.getFont("controlFont");
Graphics g = getGraphics(); Graphics g = getGraphics();
if (g == null) if (g == null)
@@ -307,25 +306,24 @@ public class InstructionsPanelImpl extends JComponent implements WizardObserver,
Insets ins = getInsets(); Insets ins = getInsets();
int h = fm.getHeight(); int h = fm.getHeight();
String[] steps = wizard.getAllSteps(); String[] steps2 = wizard.getAllSteps();
int w = Integer.MIN_VALUE; int w = Integer.MIN_VALUE;
for (int i = 0; i < steps.length; i++) { for (int i = 0; i < steps2.length; i++) {
String desc = i + ". " + (Wizard.UNDETERMINED_STEP.equals(steps[i]) String desc = i + ". " + (Wizard.UNDETERMINED_STEP.equals(steps2[i])
? elipsis ? elipsis
: //NOI18N : wizard.getStepDescription(steps2[i]));
wizard.getStepDescription(steps[i]));
if (desc != null) if (desc != null)
w = Math.max(w, fm.stringWidth(desc) + MARGIN); w = Math.max(w, fm.stringWidth(desc) + MARGIN);
} }
if (Integer.MIN_VALUE == w) if (Integer.MIN_VALUE == w)
w = 250; w = 250;
BufferedImage img = getImage(); BufferedImage image = getImage();
if (img != null) if (image != null)
w = Math.max(w, img.getWidth()); w = Math.max(w, image.getWidth());
//Make sure we can grow but not shrink //Make sure we can grow but not shrink
w = Math.max(w, historicWidth); w = Math.max(w, historicWidth);
historicWidth = w; historicWidth = w;
return new Dimension(w, ins.top + ins.bottom + ((h + 3) * steps.length)); return new Dimension(w, ins.top + ins.bottom + ((h + 3) * steps2.length));
} }
private boolean inSummaryPage; private boolean inSummaryPage;

View File

@@ -8,12 +8,11 @@ and include the License file at http://www.netbeans.org/cddl.txt.
If applicable, add the following below the CDDL Header, with the fields If applicable, add the following below the CDDL Header, with the fields
enclosed by brackets [] replaced by your own identifying information: enclosed by brackets [] replaced by your own identifying information:
"Portions Copyrighted [year] [name of copyright owner]" */ "Portions Copyrighted [year] [name of copyright owner]" */
/* /*
* MergeMap.java * MergeMap.java
* *
* Created on February 22, 2005, 4:06 PM * Created on February 22, 2005, 4:06 PM
*/ */
package org.jackhuang.hellominecraft.utils.views.wizard.modules; package org.jackhuang.hellominecraft.utils.views.wizard.modules;
import java.util.ArrayList; import java.util.ArrayList;
@@ -28,38 +27,43 @@ import java.util.Set;
import java.util.Stack; import java.util.Stack;
/** /**
* A map which proxies a collection of sub-maps each of which has a * A map which proxies a collection of sub-maps each of which has a
* unique id. Submaps can be added or removed en banc. Values from * unique id. Submaps can be added or removed en banc. Values from
* removed maps are retained; if push ("someKnownId") happens, the * removed maps are retained; if push ("someKnownId") happens, the
* values previously added to the map while that ID was active reappear. * values previously added to the map while that ID was active reappear.
* <p> * <p>
* This allows us to implement backward/forward semantics for wizards, * This allows us to implement backward/forward semantics for wizards,
* in which each pane (identified with a unique ID) can add its own * in which each pane (identified with a unique ID) can add its own
* settings to the settings map, but if the user presses the Back * settings to the settings map, but if the user presses the Back
* button, the settings from the formerly active pane can disappear - * button, the settings from the formerly active pane can disappear -
* but if the user moves forward again, they are not lost. * but if the user moves forward again, they are not lost.
* <p> * <p>
* Calling remove("someKeyBelongingToAnEarlierId") will completely * Calling remove("someKeyBelongingToAnEarlierId") will completely
* remove that value; calling put ("someKeyBelongingToAnEarlierId", "newValue") * remove that value; calling put ("someKeyBelongingToAnEarlierId", "newValue")
* replaces the earler value permanently. * replaces the earler value permanently.
* <p> * <p>
* <b><i><font color="red">This class is NOT AN API CLASS. There is no * <b><i><font color="red">This class is NOT AN API CLASS. There is no
* commitment that it will remain backward compatible or even exist in the * commitment that it will remain backward compatible or even exist in the
* future. The API of this library is in the packages <code>org.netbeans.api.wizard</code> * future. The API of this library is in the packages
* and <code>org.netbeans.spi.wizard</code></font></i></b>. * <code>org.netbeans.api.wizard</code>
* and <code>org.netbeans.spi.wizard</code></font></i></b>.
* *
* @author Tim Boudreau * @author Tim Boudreau
*/ */
public class MergeMap implements Map { public class MergeMap implements Map {
private Stack order = new Stack();
private Map id2map = new HashMap(); private final Stack order = new Stack();
private final Map id2map = new HashMap();
/** Creates a new instance of MergeMap */
/**
* Creates a new instance of MergeMap
*/
public MergeMap(String currID) { public MergeMap(String currID) {
push (currID); push(currID);
} }
private static final String BASE = "__BASE"; //NOI18N private static final String BASE = "__BASE";
/** /**
* Creates a MergeMap with a set of key/value pairs that are * Creates a MergeMap with a set of key/value pairs that are
* always there (they came from a legacy wizard - used for bridging the * always there (they came from a legacy wizard - used for bridging the
@@ -69,69 +73,64 @@ public class MergeMap implements Map {
*/ */
public MergeMap(String currId, Map everpresent) { public MergeMap(String currId, Map everpresent) {
order.push(BASE); order.push(BASE);
id2map.put (BASE, everpresent); id2map.put(BASE, everpresent);
push (currId); push(currId);
} }
/** /**
* Move to a different ID (meaning add a new named map to proxy which can be * Move to a different ID (meaning add a new named map to proxy which can be
* calved off if necessary). * calved off if necessary).
*/ */
public Map push (String id) { public Map push(String id) {
// assert !order.contains(id) : id + " already present"; //NOI18N // assert !order.contains(id) : id + " already present";
if (order.contains(id)) { if (order.contains(id))
throw new RuntimeException (id + " already present"); //NOI18N throw new RuntimeException(id + " already present");
} // assert !order.contains(id) : id + " already present";
// assert !order.contains(id) : id + " already present"; //NOI18N if (!order.isEmpty() && id.equals(order.peek()))
if (!order.isEmpty() && id.equals(order.peek())) {
return (Map) id2map.get(id); return (Map) id2map.get(id);
}
Map result = (Map) id2map.get(id); Map result = (Map) id2map.get(id);
if (result == null) { if (result == null) {
result = new HashMap(); result = new HashMap();
id2map.put (id, result); id2map.put(id, result);
} }
order.push (id); order.push(id);
return result; return result;
} }
/** /**
* Get the ID of the current sub-map being written into. * Get the ID of the current sub-map being written into.
*/ */
public String currID() { public String currID() {
return (String) order.peek(); return (String) order.peek();
} }
/** /**
* Remove the current sub-map. Removes all of its settings from the * Remove the current sub-map. Removes all of its settings from the
* MergedMap, but if push() is called with the returned value, the * MergedMap, but if push() is called with the returned value, the
* values associated with the ID being removed will be restored. * values associated with the ID being removed will be restored.
*/ */
public String popAndCalve() { public String popAndCalve() {
if (order.size() == 0) { if (order.isEmpty())
throw new NoSuchElementException ("Cannot back out past first " + //NOI18N throw new NoSuchElementException("Cannot back out past first "
"entry"); //NOI18N + "entry");
}
//Get the current map //Get the current map
String result = (String) order.peek(); String result = (String) order.peek();
Map curr = (Map) id2map.get (result); Map curr = (Map) id2map.get(result);
order.pop(); order.pop();
//Though unlikely, it is possible that a later step in a wizard //Though unlikely, it is possible that a later step in a wizard
//overwrote a key/value pair from a previous step of the wizard. //overwrote a key/value pair from a previous step of the wizard.
//We do not want to revert that write, so iterate all the keys //We do not want to revert that write, so iterate all the keys
//we're removing, and if any of them are in steps lower on the //we're removing, and if any of them are in steps lower on the
//stack, change those lower steps values to whatever was written //stack, change those lower steps values to whatever was written
//into the map we're calving off //into the map we're calving off
Set keysForCurr = curr.keySet(); Set keysForCurr = curr.keySet();
for (Iterator i=orderIterator(); i.hasNext();) { for (Iterator i = orderIterator(); i.hasNext();) {
Map other = (Map) id2map.get(i.next()); Map other = (Map) id2map.get(i.next());
for (Iterator j=curr.keySet().iterator(); j.hasNext();) { for (Iterator j = curr.keySet().iterator(); j.hasNext();) {
Object key = j.next(); Object key = j.next();
if (other.containsKey(key)) { if (other.containsKey(key))
other.put (key, curr.get(key)); other.put(key, curr.get(key));
}
} }
} }
return result; return result;
@@ -144,9 +143,8 @@ public class MergeMap implements Map {
public boolean containsKey(Object obj) { public boolean containsKey(Object obj) {
for (Iterator i = orderIterator(); i.hasNext();) { for (Iterator i = orderIterator(); i.hasNext();) {
Map curr = (Map) id2map.get(i.next()); Map curr = (Map) id2map.get(i.next());
if (curr.containsKey(obj)) { if (curr.containsKey(obj))
return true; return true;
}
} }
return false; return false;
} }
@@ -154,9 +152,8 @@ public class MergeMap implements Map {
public boolean containsValue(Object obj) { public boolean containsValue(Object obj) {
for (Iterator i = orderIterator(); i.hasNext();) { for (Iterator i = orderIterator(); i.hasNext();) {
Map curr = (Map) id2map.get(i.next()); Map curr = (Map) id2map.get(i.next());
if (curr.containsValue(obj)) { if (curr.containsValue(obj))
return true; return true;
}
} }
return false; return false;
} }
@@ -165,7 +162,7 @@ public class MergeMap implements Map {
HashSet result = new HashSet(); HashSet result = new HashSet();
for (Iterator i = orderIterator(); i.hasNext();) { for (Iterator i = orderIterator(); i.hasNext();) {
Map curr = (Map) id2map.get(i.next()); Map curr = (Map) id2map.get(i.next());
result.addAll (curr.entrySet()); result.addAll(curr.entrySet());
} }
return result; return result;
} }
@@ -175,9 +172,8 @@ public class MergeMap implements Map {
String id = (String) i.next(); String id = (String) i.next();
Map curr = (Map) id2map.get(id); Map curr = (Map) id2map.get(id);
Object result = curr.get(obj); Object result = curr.get(obj);
if (result != null) { if (result != null)
return result; return result;
}
} }
return null; return null;
} }
@@ -190,42 +186,39 @@ public class MergeMap implements Map {
HashSet result = new HashSet(); HashSet result = new HashSet();
for (Iterator i = orderIterator(); i.hasNext();) { for (Iterator i = orderIterator(); i.hasNext();) {
Map curr = (Map) id2map.get(i.next()); Map curr = (Map) id2map.get(i.next());
result.addAll (curr.keySet()); result.addAll(curr.keySet());
} }
return result; return result;
} }
public Object put(Object obj, Object obj1) { public Object put(Object obj, Object obj1) {
Map curr = (Map) id2map.get (order.peek()); Map curr = (Map) id2map.get(order.peek());
return curr.put (obj, obj1); return curr.put(obj, obj1);
} }
public void putAll(Map map) { public void putAll(Map map) {
Map curr = (Map) id2map.get (order.peek()); Map curr = (Map) id2map.get(order.peek());
curr.putAll (map); curr.putAll(map);
} }
private Object doRemove(Object obj) { private Object doRemove(Object obj) {
Map curr = (Map) id2map.get (order.peek()); Map curr = (Map) id2map.get(order.peek());
Object result = curr.remove (obj); Object result = curr.remove(obj);
if (result == null) { if (result == null)
for (Iterator i = orderIterator(); i.hasNext();) { for (Iterator i = orderIterator(); i.hasNext();) {
curr = (Map) id2map.get(i.next()); curr = (Map) id2map.get(i.next());
result = curr.remove (obj); result = curr.remove(obj);
if (result != null) { if (result != null)
break; break;
}
} }
}
return result; return result;
} }
public Object remove(Object obj) { public Object remove(Object obj) {
//Ensure we remove any duplicates in upper arrays //Ensure we remove any duplicates in upper arrays
Object result = get(obj); Object result = get(obj);
while (get(obj) != null) { while (get(obj) != null)
doRemove (obj); doRemove(obj);
}
return result; return result;
} }
@@ -237,54 +230,40 @@ public class MergeMap implements Map {
public Collection values() { public Collection values() {
HashSet result = new HashSet(); HashSet result = new HashSet();
Set keys = keySet(); Set keys = keySet();
for (Iterator i = keys.iterator(); i.hasNext();) { for (Iterator i = keys.iterator(); i.hasNext();)
result.add (get(i.next())); result.add(get(i.next()));
}
return result; return result;
} }
private Iterator orderIterator() { private Iterator orderIterator() {
return new ReverseIterator(order); return new ReverseIterator(order);
} }
private static final class ReverseIterator implements Iterator { private static final class ReverseIterator implements Iterator {
private int pos; private int pos;
private List l; private final List l;
public ReverseIterator (Stack s) {
pos = s.size()-1; public ReverseIterator(Stack s) {
pos = s.size() - 1;
l = new ArrayList(s); l = new ArrayList(s);
} }
public boolean hasNext() { public boolean hasNext() {
return pos != -1; return pos != -1;
} }
public Object next() { public Object next() {
if (pos < 0) { if (pos < 0)
throw new NoSuchElementException(); throw new NoSuchElementException();
}
Object result = l.get(pos); Object result = l.get(pos);
pos--; pos--;
return result; return result;
} }
public void remove() { public void remove() {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
} }
public String toString() {
StringBuffer sb = new StringBuffer();
for (Iterator i = keySet().iterator(); i.hasNext();) {
Object key = (Object) i.next();
sb.append ('[');
sb.append (key);
sb.append('=');
sb.append(get(key));
sb.append(']');
if (i.hasNext()) sb.append (',');
}
return sb.toString();
}
} }

View File

@@ -9,12 +9,11 @@ If applicable, add the following below the CDDL Header, with the fields
enclosed by brackets [] replaced by your own identifying information: enclosed by brackets [] replaced by your own identifying information:
"Portions Copyrighted [year] [name of copyright owner]" */ "Portions Copyrighted [year] [name of copyright owner]" */
/* /*
* BranchingWizard.java * BranchingWizard.java
* *
* Created on March 4, 2005, 10:56 PM * Created on March 4, 2005, 10:56 PM
*/ */
package org.jackhuang.hellominecraft.utils.views.wizard.spi; package org.jackhuang.hellominecraft.utils.views.wizard.spi;
import javax.swing.*; import javax.swing.*;
@@ -25,7 +24,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
* A Wizard with indeterminate branches. The actual branch decision-making * A Wizard with indeterminate branches. The actual branch decision-making
* is done by the WizardBranchController passed to the constructor. * is done by the WizardBranchController passed to the constructor.
* <p/> * <p/>
* Wizards with arbitrary numbers of branches can be handled by a * Wizards with arbitrary numbers of branches can be handled by a
@@ -38,8 +37,9 @@ import java.util.Map;
* @author Tim Boudreau * @author Tim Boudreau
*/ */
final class BranchingWizard implements WizardImplementation { final class BranchingWizard implements WizardImplementation {
private final List listenerList = Collections.synchronizedList (
new LinkedList()); private final List listenerList = Collections.synchronizedList(
new LinkedList());
private final WizardBranchController brancher; private final WizardBranchController brancher;
final WizardImplementation initialSteps; final WizardImplementation initialSteps;
@@ -63,70 +63,63 @@ final class BranchingWizard implements WizardImplementation {
} }
private void checkForSecondary() { private void checkForSecondary() {
if (wizardData == null) { if (wizardData == null)
return; return;
}
WizardImplementation newSecondary = createSecondary(wizardData); WizardImplementation newSecondary = createSecondary(wizardData);
/* /*
* johnflournoy 7/20/07 * johnflournoy 7/20/07
* check for secondary should be adding the secondary to the activeWizard * check for secondary should be adding the secondary to the activeWizard
* not the initial wizard. Adding it to the initial wizard was breaking * not the initial wizard. Adding it to the initial wizard was breaking
* multiple branching - to accomplish this created a new method: * multiple branching - to accomplish this created a new method:
* setSecondary() * setSecondary()
*/ */
if (activeWizard instanceof BranchingWizard) { if (activeWizard instanceof BranchingWizard)
((BranchingWizard) activeWizard).setSecondary(newSecondary); ((BranchingWizard) activeWizard).setSecondary(newSecondary);
} else { else
this.setSecondary(newSecondary); this.setSecondary(newSecondary);
}
} }
/** /**
* Set the secondary for this <code>BranchingWizard</code>. * Set the secondary for this <code>BranchingWizard</code>.
*
* @param newSecondary is a WizardImplementation. * @param newSecondary is a WizardImplementation.
*/ */
private void setSecondary(WizardImplementation newSecondary) { private void setSecondary(WizardImplementation newSecondary) {
/* johnflournoy added additional condition: secondary != this */ /* johnflournoy added additional condition: secondary != this */
if ((((subsequentSteps == null) != (newSecondary == null)) if ((((subsequentSteps == null) != (newSecondary == null))
|| (subsequentSteps != null && !subsequentSteps.equals(newSecondary))) || (subsequentSteps != null && !subsequentSteps.equals(newSecondary)))
&& !this.equals(newSecondary)) { && !this.equals(newSecondary))
/* /*
* johnflournoy: only set the subsequent steps if it * johnflournoy: only set the subsequent steps if it
* this wizard owns the current step. * this wizard owns the current step.
*/ */
if (Arrays.asList(initialSteps.getAllSteps()).contains(currStep)) { if (Arrays.asList(initialSteps.getAllSteps()).contains(currStep)) {
subsequentSteps = newSecondary; subsequentSteps = newSecondary;
fireStepsChanged(); fireStepsChanged();
} }
}
} }
public int getForwardNavigationMode() { public int getForwardNavigationMode() {
return activeWizard.getForwardNavigationMode(); return activeWizard.getForwardNavigationMode();
} }
private void setCurrent(WizardImplementation wizard) { private void setCurrent(WizardImplementation wizard) {
if (activeWizard == wizard) { if (activeWizard == wizard)
return; return;
}
if (wizard == null) { if (wizard == null)
throw new NullPointerException("Can't set current wizard to null"); throw new NullPointerException("Can't set current wizard to null");
}
if ((activeWizard != null) && (wl != null)) { if ((activeWizard != null) && (wl != null))
activeWizard.removeWizardObserver(wl); activeWizard.removeWizardObserver(wl);
}
activeWizard = wizard; activeWizard = wizard;
if (wl == null) { if (wl == null)
wl = new WL(); wl = new WL();
}
activeWizard.addWizardObserver(wl); activeWizard.addWizardObserver(wl);
} }
@@ -140,17 +133,15 @@ final class BranchingWizard implements WizardImplementation {
Object result = activeWizard.finish(settings); Object result = activeWizard.finish(settings);
initialSteps.removeWizardObserver(wl); initialSteps.removeWizardObserver(wl);
//Can be null, we allow bail-out with finish mid-wizard now //Can be null, we allow bail-out with finish mid-wizard now
if (subsequentSteps != null) { if (subsequentSteps != null)
subsequentSteps.removeWizardObserver(wl); subsequentSteps.removeWizardObserver(wl);
}
return result; return result;
} catch (WizardException we) { } catch (WizardException we) {
if (we.getStepToReturnTo() != null) { if (we.getStepToReturnTo() != null) {
initialSteps.addWizardObserver(wl); initialSteps.addWizardObserver(wl);
//Can be null, we allow bail-out with finish mid-wizard now //Can be null, we allow bail-out with finish mid-wizard now
if (subsequentSteps != null) { if (subsequentSteps != null)
subsequentSteps.addWizardObserver(wl); subsequentSteps.addWizardObserver(wl);
}
} }
throw we; throw we;
} }
@@ -179,46 +170,40 @@ final class BranchingWizard implements WizardImplementation {
public final String getNextStep() { public final String getNextStep() {
String result; String result;
if (currStep == null) { if (currStep == null)
result = getAllSteps()[0]; result = getAllSteps()[0];
} else { else {
String[] steps = getAllSteps(); String[] steps = getAllSteps();
int idx = Arrays.asList(steps).indexOf(currStep); int idx = Arrays.asList(steps).indexOf(currStep);
if (idx == -1) { if (idx == -1)
throw new IllegalStateException("Current step not in" + //NOI18N throw new IllegalStateException("Current step not in"
" available steps: " + currStep + " not in " + //NOI18N + " available steps: " + currStep + " not in "
Arrays.asList(steps)); + Arrays.asList(steps));
} else { else if (idx == steps.length - 1)
if (idx == steps.length - 1) { if (subsequentSteps == null)
if (subsequentSteps == null) { result = UNDETERMINED_STEP;
else
result = subsequentSteps.getNextStep();
else {
WizardImplementation w = ownerOf(currStep);
if (w == initialSteps && idx == initialSteps.getAllSteps().length - 1) {
checkForSecondary();
if (subsequentSteps != null)
result = subsequentSteps.getAllSteps()[0];
else
result = UNDETERMINED_STEP; result = UNDETERMINED_STEP;
} else { } else
result = subsequentSteps.getNextStep(); result = w.getNextStep();
}
} else {
WizardImplementation w = ownerOf(currStep);
if (w == initialSteps && idx == initialSteps.getAllSteps().length - 1) {
checkForSecondary();
if (subsequentSteps != null) {
result = subsequentSteps.getAllSteps()[0];
} else {
result = UNDETERMINED_STEP;
}
} else {
result = w.getNextStep();
}
}
} }
} }
return getProblem() == null ? result : UNDETERMINED_STEP.equals(result) ? result : null; return getProblem() == null ? result : UNDETERMINED_STEP.equals(result) ? result : null;
} }
public final String getPreviousStep() { public final String getPreviousStep() {
if (activeWizard == subsequentSteps && subsequentSteps.getAllSteps()[0].equals(currStep)) { if (activeWizard == subsequentSteps && subsequentSteps.getAllSteps()[0].equals(currStep))
return initialSteps.getAllSteps()[initialSteps.getAllSteps().length - 1]; return initialSteps.getAllSteps()[initialSteps.getAllSteps().length - 1];
} else { else
return activeWizard.getPreviousStep(); return activeWizard.getPreviousStep();
}
} }
public final String getProblem() { public final String getProblem() {
@@ -227,17 +212,15 @@ final class BranchingWizard implements WizardImplementation {
public final String getStepDescription(String id) { public final String getStepDescription(String id) {
WizardImplementation w = ownerOf(id); WizardImplementation w = ownerOf(id);
if (w == null) { if (w == null)
return null; return null;
}
return w.getStepDescription(id); return w.getStepDescription(id);
} }
public final String getLongDescription(String id) { public final String getLongDescription(String id) {
WizardImplementation w = ownerOf(id); WizardImplementation w = ownerOf(id);
if (w == null) { if (w == null)
return null; return null;
}
return w.getLongDescription(id); return w.getLongDescription(id);
} }
@@ -246,24 +229,22 @@ final class BranchingWizard implements WizardImplementation {
checkForSecondary(); checkForSecondary();
return subsequentSteps; return subsequentSteps;
} }
if (Arrays.asList(initialSteps.getAllSteps()).contains(id)) { if (Arrays.asList(initialSteps.getAllSteps()).contains(id))
return initialSteps; return initialSteps;
} else { else {
/* /*
* johnflournoy * johnflournoy
* need to check an existing subsequentsteps to see if * need to check an existing subsequentsteps to see if
* we can find the owner of "id", otherwise we were losing * we can find the owner of "id", otherwise we were losing
* a wizard if we had multiple branches and we backed up to an * a wizard if we had multiple branches and we backed up to an
* earlier wizard and then went down the same path again. * earlier wizard and then went down the same path again.
*/ */
if (subsequentSteps != null) { if (subsequentSteps != null) {
if (!Arrays.asList(subsequentSteps.getAllSteps()).contains(id)) { if (!Arrays.asList(subsequentSteps.getAllSteps()).contains(id))
checkForSecondary(); checkForSecondary();
} } else
} else {
checkForSecondary(); checkForSecondary();
}
return subsequentSteps; return subsequentSteps;
} }
} }
@@ -273,35 +254,32 @@ final class BranchingWizard implements WizardImplementation {
} }
public final JComponent navigatingTo(String id, Map settings) { public final JComponent navigatingTo(String id, Map settings) {
if (id == null) { if (id == null)
throw new NullPointerException(); throw new NullPointerException();
}
currStep = id; currStep = id;
wizardData = settings; wizardData = settings;
WizardImplementation impl = ownerOf (id); WizardImplementation impl = ownerOf(id);
if (impl == null) { if (impl == null)
throw new NullPointerException ("No owning WizardImplementation for" + throw new NullPointerException("No owning WizardImplementation for"
" id " + id); + " id " + id);
}
setCurrent(impl); setCurrent(impl);
return activeWizard.navigatingTo(id, settings); return activeWizard.navigatingTo(id, settings);
} }
public final void removeWizardObserver (WizardObserver observer) { public final void removeWizardObserver(WizardObserver observer) {
listenerList.remove(observer); listenerList.remove(observer);
} }
public final void addWizardObserver (WizardObserver observer) { public final void addWizardObserver(WizardObserver observer) {
listenerList.add(observer); listenerList.add(observer);
} }
private void fireStepsChanged() { private void fireStepsChanged() {
WizardObserver[] listeners = (WizardObserver[]) WizardObserver[] listeners = (WizardObserver[]) listenerList.toArray(new WizardObserver[0]);
listenerList.toArray (new WizardObserver[0]);
for (int i = listeners.length - 1; i >= 0; i --) { for (int i = listeners.length - 1; i >= 0; i--) {
WizardObserver l = (WizardObserver) listeners[i]; WizardObserver l = (WizardObserver) listeners[i];
l.stepsChanged(null); l.stepsChanged(null);
} }
@@ -310,20 +288,18 @@ final class BranchingWizard implements WizardImplementation {
private void fireNavigabilityChanged() { private void fireNavigabilityChanged() {
checkForSecondary(); checkForSecondary();
WizardObserver[] listeners = (WizardObserver[]) WizardObserver[] listeners = (WizardObserver[]) listenerList.toArray(new WizardObserver[0]);
listenerList.toArray (new WizardObserver[0]);
for (int i = listeners.length - 1; i >= 0; i --) { for (int i = listeners.length - 1; i >= 0; i--) {
WizardObserver l = (WizardObserver) listeners[i]; WizardObserver l = (WizardObserver) listeners[i];
l.navigabilityChanged(null); l.navigabilityChanged(null);
} }
} }
private void fireSelectionChanged() { private void fireSelectionChanged() {
WizardObserver[] listeners = (WizardObserver[]) WizardObserver[] listeners = (WizardObserver[]) listenerList.toArray(new WizardObserver[0]);
listenerList.toArray (new WizardObserver[0]);
for (int i = listeners.length - 1; i >= 0; i --) { for (int i = listeners.length - 1; i >= 0; i--) {
WizardObserver l = (WizardObserver) listeners[i]; WizardObserver l = (WizardObserver) listeners[i];
l.selectionChanged(null); l.selectionChanged(null);
} }
@@ -334,6 +310,7 @@ final class BranchingWizard implements WizardImplementation {
} }
private class WL implements WizardObserver { private class WL implements WizardObserver {
public void stepsChanged(Wizard wizard) { public void stepsChanged(Wizard wizard) {
fireStepsChanged(); fireStepsChanged();
} }

View File

@@ -9,12 +9,11 @@ If applicable, add the following below the CDDL Header, with the fields
enclosed by brackets [] replaced by your own identifying information: enclosed by brackets [] replaced by your own identifying information:
"Portions Copyrighted [year] [name of copyright owner]" */ "Portions Copyrighted [year] [name of copyright owner]" */
/* /*
* GenericListener.java * GenericListener.java
* *
* Created on October 5, 2004, 12:36 AM * Created on October 5, 2004, 12:36 AM
*/ */
package org.jackhuang.hellominecraft.utils.views.wizard.spi; package org.jackhuang.hellominecraft.utils.views.wizard.spi;
import java.awt.Component; import java.awt.Component;
@@ -30,8 +29,6 @@ import java.util.EventObject;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Set; import java.util.Set;
import java.util.logging.Logger;
import java.util.logging.Level;
import javax.swing.*; import javax.swing.*;
import javax.swing.table.*; import javax.swing.table.*;
import javax.swing.tree.*; import javax.swing.tree.*;
@@ -56,17 +53,15 @@ import javax.swing.tree.TreeSelectionModel;
* validate its contents. * validate its contents.
* *
* If you use subclasses of the swing components, you will also need to subclass * If you use subclasses of the swing components, you will also need to subclass
* this listener and override at least the methods isProbablyContainer, attachTo and detachFrom. * this listener and override at least the methods isProbablyContainer, attachTo
* and detachFrom.
* *
* @author Tim Boudreau * @author Tim Boudreau
*/ */
final class GenericListener final class GenericListener
implements ActionListener, PropertyChangeListener, ItemListener, implements ActionListener, PropertyChangeListener, ItemListener,
ContainerListener, DocumentListener, ChangeListener, ContainerListener, DocumentListener, ChangeListener,
ListSelectionListener, TreeSelectionListener, TableModelListener { ListSelectionListener, TreeSelectionListener, TableModelListener {
private static final Logger logger =
Logger.getLogger(GenericListener.class.getName());
private final WizardPage wizardPage; private final WizardPage wizardPage;
@@ -76,218 +71,191 @@ final class GenericListener
* Set of components that we're listening to models of, so we can look * Set of components that we're listening to models of, so we can look
* up the component from the model as needed * up the component from the model as needed
*/ */
private Set listenedTo = new HashSet(); private final Set listenedTo = new HashSet();
private final WizardPage.CustomComponentListener extListener; private final WizardPage.CustomComponentListener extListener;
private final WizardPage.CustomComponentNotifier extNotifier; private final WizardPage.CustomComponentNotifier extNotifier;
public GenericListener(WizardPage wizardPage, WizardPage.CustomComponentListener l, public GenericListener(WizardPage wizardPage, WizardPage.CustomComponentListener l,
WizardPage.CustomComponentNotifier n) { WizardPage.CustomComponentNotifier n) {
this.extListener = l; this.extListener = l;
this.extNotifier = n; this.extNotifier = n;
if ((extListener == null) != (extNotifier == null)) { if ((extListener == null) != (extNotifier == null))
throw new RuntimeException(); throw new RuntimeException();
} // assert wizardPage != null : "WizardPage may not be null";
// assert wizardPage != null : "WizardPage may not be null"; // NOI18N if (wizardPage == null)
if (wizardPage == null) { throw new IllegalArgumentException("WizardPage may not be null");
throw new IllegalArgumentException("WizardPage may not be null"); // NOI18N)
}
this.wizardPage = wizardPage; this.wizardPage = wizardPage;
wizardPage.addContainerListener(this); wizardPage.addContainerListener(this);
} }
public GenericListener (WizardPage page) { public GenericListener(WizardPage page) {
this (page, null, null); this(page, null, null);
} }
/** /**
* Return true if the given component is likely to be a container such the each * Return true if the given component is likely to be a container such the
* each
* component within the container should be be considered as a user input. * component within the container should be be considered as a user input.
* *
* @param c * @param c
*
* @return true if the component children should have this listener added. * @return true if the component children should have this listener added.
*/ */
protected boolean isProbablyAContainer (Component c) { protected boolean isProbablyAContainer(Component c) {
boolean result = extListener != null ? extListener.isContainer(c) : false; boolean result = extListener != null ? extListener.isContainer(c) : false;
if (!result) { if (!result) {
boolean isSwing = isSwingClass(c); boolean isSwing = isSwingClass(c);
if (isSwing) { if (isSwing)
result = c instanceof JPanel || c instanceof JSplitPane || c instanceof result = c instanceof JPanel || c instanceof JSplitPane || c instanceof JToolBar || c instanceof JViewport || c instanceof JScrollPane
JToolBar || c instanceof JViewport || c instanceof JScrollPane || || c instanceof JFrame || c instanceof JRootPane || c instanceof Window || c instanceof Frame || c instanceof Dialog
c instanceof JFrame || c instanceof JRootPane || c instanceof || c instanceof JTabbedPane || c instanceof JInternalFrame
Window || c instanceof Frame || c instanceof Dialog || || c instanceof JDesktopPane || c instanceof JLayeredPane
c instanceof JTabbedPane || c instanceof JInternalFrame || || c instanceof Box;
c instanceof JDesktopPane || c instanceof JLayeredPane || else
c instanceof Box;
} else {
result = c instanceof Container; result = c instanceof Container;
}
} }
return result; return result;
} }
/** /**
* Return true if the given component is likely to be a swing primitive or a subclass. * Return true if the given component is likely to be a swing primitive or a
* The default implmentation here just checks for the package of the component to be "javax.swing" * subclass.
* If you use subclasses of swing components, you will need to override this method * The default implmentation here just checks for the package of the
* component to be "javax.swing"
* If you use subclasses of swing components, you will need to override this
* method
* to get proper behavior. * to get proper behavior.
* *
* @param c * @param c
* @return true if the component should be examined more closely (see isProbablyAContainer) *
* @return true if the component should be examined more closely (see
* isProbablyAContainer)
*/ */
protected boolean isSwingClass (Component c) protected boolean isSwingClass(Component c) {
{
String packageName = c.getClass().getPackage().getName(); String packageName = c.getClass().getPackage().getName();
boolean swing = packageName.equals ("javax.swing"); //NOI18N boolean swing = packageName.equals("javax.swing");
return swing; return swing;
} }
protected void attachTo(Component jc) { protected void attachTo(Component jc) {
if (extListener != null && extListener.accept (jc)) { if (extListener != null && extListener.accept(jc)) {
extListener.startListeningTo(jc, extNotifier); extListener.startListeningTo(jc, extNotifier);
listenedTo.add (jc); listenedTo.add(jc);
if (wizardPage.getMapKeyFor(jc) != null) { if (wizardPage.getMapKeyFor(jc) != null)
wizardPage.maybeUpdateMap(jc); wizardPage.maybeUpdateMap(jc);
}
return; return;
} }
if (isProbablyAContainer(jc)) { if (isProbablyAContainer(jc))
attachToHierarchyOf((Container) jc); attachToHierarchyOf((Container) jc);
} else if (jc instanceof JList) { else if (jc instanceof JList) {
listenedTo.add(jc); listenedTo.add(jc);
((JList) jc).addListSelectionListener(this); ((JList) jc).addListSelectionListener(this);
} else if (jc instanceof JComboBox) { } else if (jc instanceof JComboBox)
((JComboBox) jc).addActionListener(this); ((JComboBox) jc).addActionListener(this);
} else if (jc instanceof JTree) { else if (jc instanceof JTree) {
listenedTo.add(jc); listenedTo.add(jc);
((JTree) jc).getSelectionModel().addTreeSelectionListener(this); ((JTree) jc).getSelectionModel().addTreeSelectionListener(this);
} else if (jc instanceof JToggleButton) { } else if (jc instanceof JToggleButton)
((AbstractButton) jc).addItemListener(this); ((AbstractButton) jc).addItemListener(this);
} else if (jc instanceof JFormattedTextField) { //JFormattedTextField must be tested before JTextCompoent else if (jc instanceof JFormattedTextField) //JFormattedTextField must be tested before JTextCompoent
jc.addPropertyChangeListener("value", this); jc.addPropertyChangeListener("value", this);
} else if (jc instanceof JTextComponent) { else if (jc instanceof JTextComponent) {
listenedTo.add(jc); listenedTo.add(jc);
((JTextComponent) jc).getDocument().addDocumentListener(this); ((JTextComponent) jc).getDocument().addDocumentListener(this);
} else if (jc instanceof JColorChooser) { } else if (jc instanceof JColorChooser) {
listenedTo.add(jc); listenedTo.add(jc);
((JColorChooser) jc).getSelectionModel().addChangeListener(this); ((JColorChooser) jc).getSelectionModel().addChangeListener(this);
} else if (jc instanceof JSpinner) { } else if (jc instanceof JSpinner)
((JSpinner) jc).addChangeListener(this); ((JSpinner) jc).addChangeListener(this);
} else if (jc instanceof JSlider) { else if (jc instanceof JSlider)
((JSlider) jc).addChangeListener(this); ((JSlider) jc).addChangeListener(this);
} else if (jc instanceof JTable) { else if (jc instanceof JTable) {
listenedTo.add(jc); listenedTo.add(jc);
((JTable) jc).getSelectionModel().addListSelectionListener(this); ((JTable) jc).getSelectionModel().addListSelectionListener(this);
} else {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Don't know how to listen to a " + // NOI18N
jc.getClass().getName());
}
} }
if (accept(jc) && !(jc instanceof JPanel)) { if (accept(jc) && !(jc instanceof JPanel)) {
jc.addPropertyChangeListener("name", this); jc.addPropertyChangeListener("name", this);
if (wizardPage.getMapKeyFor(jc) != null) { if (wizardPage.getMapKeyFor(jc) != null)
wizardPage.maybeUpdateMap(jc); wizardPage.maybeUpdateMap(jc);
}
}
if (logger.isLoggable(Level.FINE) && accept(jc)) {
logger.fine("Begin listening to " + jc); // NOI18N
} }
} }
protected void detachFrom(Component jc) { protected void detachFrom(Component jc) {
listenedTo.remove(jc); listenedTo.remove(jc);
if (extListener != null && extListener.accept (jc)) { if (extListener != null && extListener.accept(jc))
extListener.stopListeningTo(jc); extListener.stopListeningTo(jc);
} if (isProbablyAContainer(jc))
if (isProbablyAContainer(jc)) {
detachFromHierarchyOf((Container) jc); detachFromHierarchyOf((Container) jc);
} else if (jc instanceof JList) { else if (jc instanceof JList)
((JList) jc).removeListSelectionListener(this); ((JList) jc).removeListSelectionListener(this);
} else if (jc instanceof JComboBox) { else if (jc instanceof JComboBox)
((JComboBox) jc).removeActionListener(this); ((JComboBox) jc).removeActionListener(this);
} else if (jc instanceof JTree) { else if (jc instanceof JTree)
((JTree) jc).getSelectionModel().removeTreeSelectionListener(this); ((JTree) jc).getSelectionModel().removeTreeSelectionListener(this);
} else if (jc instanceof JToggleButton) { else if (jc instanceof JToggleButton)
((AbstractButton) jc).removeActionListener(this); ((AbstractButton) jc).removeActionListener(this);
} else if (jc instanceof JTextComponent) { else if (jc instanceof JTextComponent) {
} else if (jc instanceof JFormattedTextField) { //JFormattedTextField must be tested before JTextCompoent } else if (jc instanceof JFormattedTextField) { //JFormattedTextField must be tested before JTextCompoent
jc.removePropertyChangeListener("value", this); jc.removePropertyChangeListener("value", this);
((JTextComponent) jc).getDocument().removeDocumentListener(this); ((JTextComponent) jc).getDocument().removeDocumentListener(this);
} else if (jc instanceof JColorChooser) { } else if (jc instanceof JColorChooser)
((JColorChooser) jc).getSelectionModel().removeChangeListener(this); ((JColorChooser) jc).getSelectionModel().removeChangeListener(this);
} else if (jc instanceof JSpinner) { else if (jc instanceof JSpinner)
((JSpinner) jc).removeChangeListener(this); ((JSpinner) jc).removeChangeListener(this);
} else if (jc instanceof JSlider) { else if (jc instanceof JSlider)
((JSlider) jc).removeChangeListener(this); ((JSlider) jc).removeChangeListener(this);
} else if (jc instanceof JTable) { else if (jc instanceof JTable)
((JTable) jc).getSelectionModel().removeListSelectionListener(this); ((JTable) jc).getSelectionModel().removeListSelectionListener(this);
}
if (accept(jc) && !(jc instanceof JPanel)) { if (accept(jc) && !(jc instanceof JPanel)) {
jc.removePropertyChangeListener("name", this); jc.removePropertyChangeListener("name", this);
Object key = wizardPage.getMapKeyFor(jc); Object key = wizardPage.getMapKeyFor(jc);
if (key != null) { if (key != null)
if (logger.isLoggable(Level.FINE)) {
logger.fine("Named component removed from hierarchy: " + // NOI18N
key + ". Removing any corresponding " + // NOI18N
"value from the wizard settings map."); // NOI18N
}
wizardPage.removeFromMap(key); wizardPage.removeFromMap(key);
}
}
if (logger.isLoggable(Level.FINE) && accept(jc)) {
logger.fine("Stop listening to " + jc); // NOI18N
} }
} }
private void detachFromHierarchyOf(Container container) { private void detachFromHierarchyOf(Container container) {
container.removeContainerListener(this); container.removeContainerListener(this);
Component[] components = container.getComponents(); Component[] components = container.getComponents();
for (int i = 0; i < components.length; i++) { for (Component component : components)
detachFrom(components[i]); // Will callback recursively any nested JPanels detachFrom(component); // Will callback recursively any nested JPanels
}
} }
void attachToHierarchyOf(Container container) { void attachToHierarchyOf(Container container) {
if (!Arrays.asList (container.getContainerListeners()).contains(this)) { if (!Arrays.asList(container.getContainerListeners()).contains(this))
container.addContainerListener(this); container.addContainerListener(this);
}
Component[] components = container.getComponents(); Component[] components = container.getComponents();
for (int i = 0; i < components.length; i++) { for (Component component : components)
attachTo(components[i]); // Will recursively add any child components in attachTo(component); // Will recursively add any child components in
}
} }
protected boolean accept(Component jc) { protected boolean accept(Component jc) {
if (extListener != null && extListener.accept(jc)) { if (extListener != null && extListener.accept(jc))
return true; return true;
} if (!(jc instanceof JComponent))
if (!(jc instanceof JComponent)) {
return false; return false;
} if (jc instanceof TableCellEditor || jc instanceof TreeCellEditor
if (jc instanceof TableCellEditor || jc instanceof TreeCellEditor || || SwingUtilities.getAncestorOfClass(JTable.class, jc) != null
SwingUtilities.getAncestorOfClass(JTable.class, jc) != null || || SwingUtilities.getAncestorOfClass(JTree.class, jc) != null
SwingUtilities.getAncestorOfClass(JTree.class, jc) != null || || SwingUtilities.getAncestorOfClass(JList.class, jc) != null)
SwingUtilities.getAncestorOfClass(JList.class, jc) != null){
//Don't listen to cell editors, we can end up listening to them //Don't listen to cell editors, we can end up listening to them
//multiple times, and the tree/table model will give us the event //multiple times, and the tree/table model will give us the event
//we need //we need
return false; return false;
} return isProbablyAContainer(jc)
return isProbablyAContainer (jc) || || jc instanceof JList
jc instanceof JList || || jc instanceof JComboBox
jc instanceof JComboBox || || jc instanceof JTree
jc instanceof JTree || || jc instanceof JToggleButton
jc instanceof JToggleButton || //covers toggle, radio, checkbox || //covers toggle, radio, checkbox
jc instanceof JTextComponent || jc instanceof JTextComponent
jc instanceof JColorChooser || || jc instanceof JColorChooser
jc instanceof JSpinner || || jc instanceof JSpinner
jc instanceof JSlider; || jc instanceof JSlider;
} }
void setIgnoreEvents(boolean val) { void setIgnoreEvents(boolean val) {
@@ -299,59 +267,40 @@ final class GenericListener
setIgnoreEvents(true); setIgnoreEvents(true);
try { try {
//XXX this could be prettier... //XXX this could be prettier...
if (logger.isLoggable(Level.FINE)) { if (e instanceof EventObject && ((EventObject) e).getSource() instanceof Component)
logger.fine("Event received: " + e); // NOI18N
}
if (e instanceof EventObject && ((EventObject) e).getSource() instanceof Component) {
wizardPage.userInputReceived((Component) ((EventObject) e).getSource(), e); wizardPage.userInputReceived((Component) ((EventObject) e).getSource(), e);
} else if (e instanceof TreeSelectionEvent) { else if (e instanceof TreeSelectionEvent) {
logger.fine("Looking for a tree for a tree selection event"); // NOI18N
TreeSelectionModel mdl = (TreeSelectionModel) ((TreeSelectionEvent) e).getSource(); TreeSelectionModel mdl = (TreeSelectionModel) ((TreeSelectionEvent) e).getSource();
for (Iterator i = listenedTo.iterator(); i.hasNext();) { for (Iterator i = listenedTo.iterator(); i.hasNext();) {
Object o = i.next(); Object o = i.next();
if (o instanceof JTree && ((JTree) o).getSelectionModel() == mdl) { if (o instanceof JTree && ((JTree) o).getSelectionModel() == mdl) {
if (logger.isLoggable(Level.FINE)) {
logger.fine(" found it: " + o); // NOI18N
}
wizardPage.userInputReceived((Component) o, e); wizardPage.userInputReceived((Component) o, e);
break; break;
} }
} }
} else if (e instanceof DocumentEvent) { } else if (e instanceof DocumentEvent) {
logger.fine("Looking for a JTextComponent for a DocumentEvent"); // NOI18N
Document document = ((DocumentEvent) e).getDocument(); Document document = ((DocumentEvent) e).getDocument();
for (Iterator i = listenedTo.iterator(); i.hasNext();) { for (Iterator i = listenedTo.iterator(); i.hasNext();) {
Object o = i.next(); Object o = i.next();
if (o instanceof JTextComponent && ((JTextComponent) o).getDocument() == document) { if (o instanceof JTextComponent && ((JTextComponent) o).getDocument() == document) {
if (logger.isLoggable(Level.FINE)) {
logger.fine(" found it: " + o); // NOI18N
}
wizardPage.userInputReceived((Component) o, e); wizardPage.userInputReceived((Component) o, e);
break; break;
} }
} }
} else if (e instanceof ListSelectionEvent) { } else if (e instanceof ListSelectionEvent) {
logger.fine("Looking for a JList or JTable for a ListSelectionEvent"); // NOI18N
ListSelectionModel model = (ListSelectionModel) ((ListSelectionEvent) e).getSource(); ListSelectionModel model = (ListSelectionModel) ((ListSelectionEvent) e).getSource();
for (Iterator i = listenedTo.iterator(); i.hasNext();) { for (Iterator i = listenedTo.iterator(); i.hasNext();) {
Object o = i.next(); Object o = i.next();
if (o instanceof JList && ((JList) o).getSelectionModel() == model) { if (o instanceof JList && ((JList) o).getSelectionModel() == model) {
if (logger.isLoggable(Level.FINE)) {
logger.fine(" found it: " + o); // NOI18N
}
wizardPage.userInputReceived((Component) o, e); wizardPage.userInputReceived((Component) o, e);
break; break;
} else if (o instanceof JTable && ((JTable) o).getSelectionModel() == model) { } else if (o instanceof JTable && ((JTable) o).getSelectionModel() == model) {
if (logger.isLoggable(Level.FINE)) {
logger.fine(" found it: " + o); // NOI18N
}
wizardPage.userInputReceived((Component) o, e); wizardPage.userInputReceived((Component) o, e);
break; break;
} }
} }
} else { } else
wizardPage.userInputReceived(null, e); wizardPage.userInputReceived(null, e);
}
} finally { } finally {
setIgnoreEvents(false); setIgnoreEvents(false);
} }
@@ -366,19 +315,8 @@ final class GenericListener
if (e.getSource() instanceof JComponent && "name".equals(e.getPropertyName())) { if (e.getSource() instanceof JComponent && "name".equals(e.getPropertyName())) {
// Note - most components do NOT fire a property change on // Note - most components do NOT fire a property change on
// setName(), but it is possible for this to be done intentionally // setName(), but it is possible for this to be done intentionally
if (e.getOldValue() instanceof String) { if (e.getOldValue() instanceof String)
if (logger.isLoggable(Level.FINE)) {
logger.fine("Name of component changed from " + e.getOldValue() + // NOI18N
" to " + e.getNewValue() + ". Removing any values for " + // NOI18N
e.getOldValue() + " from the wizard data map"); // NOI18N
}
wizardPage.removeFromMap(e.getOldValue()); wizardPage.removeFromMap(e.getOldValue());
}
if (logger.isLoggable(Level.FINE)) {
logger.fine("Possibly update map for renamed component " + // NOI18N
e.getSource());
}
} else if (e.getSource() instanceof JFormattedTextField && "value".equals(e.getPropertyName())) { } else if (e.getSource() instanceof JFormattedTextField && "value".equals(e.getPropertyName())) {
fire(e); fire(e);
@@ -395,18 +333,16 @@ final class GenericListener
// extListener.startListeningTo(e.getChild(), extNotifier); // extListener.startListeningTo(e.getChild(), extNotifier);
// listenedTo.add (e.getChild()); // listenedTo.add (e.getChild());
// } else if (accept(e.getChild())) { // } else if (accept(e.getChild())) {
if (accept (e.getChild())) { if (accept(e.getChild()))
attachTo(e.getChild()); attachTo(e.getChild());
}
} }
public void componentRemoved(ContainerEvent e) { public void componentRemoved(ContainerEvent e) {
if (extListener != null && extListener.accept (e.getChild())) { if (extListener != null && extListener.accept(e.getChild())) {
extListener.stopListeningTo (e.getChild()); extListener.stopListeningTo(e.getChild());
listenedTo.remove (e.getChild()); listenedTo.remove(e.getChild());
} else if (accept(e.getChild())) { } else if (accept(e.getChild()))
detachFrom(e.getChild()); detachFrom(e.getChild());
}
} }
public void insertUpdate(DocumentEvent e) { public void insertUpdate(DocumentEvent e) {

View File

@@ -172,11 +172,8 @@ final class SimpleWizardInfo implements WizardControllerImplementation {
} }
private int index() { private int index() {
SimpleWizard wizard = getWizard(); SimpleWizard a = getWizard();
if (wizard != null) return a == null ? 0 : a.currentStepIndex();
return wizard.currentStepIndex();
else
return 0;
} }
public final void setBusy(boolean value) { public final void setBusy(boolean value) {
@@ -281,11 +278,9 @@ final class SimpleWizardInfo implements WizardControllerImplementation {
// lookup the step by name // lookup the step by name
boolean containsStep(String name) { boolean containsStep(String name) {
for (int i = 0; i < steps.length; i++) { for (String step : steps)
String step = steps[i];
if (name.equals(step)) if (name.equals(step))
return true; return true;
}
return false; return false;
} }
@@ -308,7 +303,7 @@ final class SimpleWizardInfo implements WizardControllerImplementation {
return Arrays.equals(info.descriptions, descriptions) return Arrays.equals(info.descriptions, descriptions)
&& Arrays.equals(info.steps, steps) && Arrays.equals(info.steps, steps)
&& info.title == title; && (info.title == null ? title == null : info.title.equals(title));
} else } else
return false; return false;
} }
@@ -323,9 +318,4 @@ final class SimpleWizardInfo implements WizardControllerImplementation {
boolean cancel(Map settings) { boolean cancel(Map settings) {
return provider.cancel(settings); return provider.cancel(settings);
} }
public String toString() {
return "SimpleWizardInfo@" + System.identityHashCode(this) + " for "
+ provider;
}
} }

View File

@@ -8,7 +8,7 @@ and include the License file at http://www.netbeans.org/cddl.txt.
If applicable, add the following below the CDDL Header, with the fields If applicable, add the following below the CDDL Header, with the fields
enclosed by brackets [] replaced by your own identifying information: enclosed by brackets [] replaced by your own identifying information:
"Portions Copyrighted [year] [name of copyright owner]" */ "Portions Copyrighted [year] [name of copyright owner]" */
/* /*
* Summary.java * Summary.java
* *
* Created on September 24, 2006, 4:05 AM * Created on September 24, 2006, 4:05 AM
@@ -16,7 +16,6 @@ enclosed by brackets [] replaced by your own identifying information:
* To change this template, choose Tools | Template Manager * To change this template, choose Tools | Template Manager
* and open the template in the editor. * and open the template in the editor.
*/ */
package org.jackhuang.hellominecraft.utils.views.wizard.spi; package org.jackhuang.hellominecraft.utils.views.wizard.spi;
import java.awt.Component; import java.awt.Component;
@@ -27,122 +26,114 @@ import javax.swing.JTextArea;
import javax.swing.UIManager; import javax.swing.UIManager;
/** /**
* Object which may be returned from <code>WizardPage.WizardResultProducer.finish()</code> * Object which may be returned from
* or <code>WizardPanelProvider.finish()</code>, or passed to * <code>WizardPage.WizardResultProducer.finish()</code>
* <code>DeferredWizardResult.ResultProgressHandle.finish()</code>. If an * or <code>WizardPanelProvider.finish()</code>, or passed to
* instance of <code>Summary</code> is used, then the UI should, rather * <code>DeferredWizardResult.ResultProgressHandle.finish()</code>. If an
* than disappearing, show the component provided by the <code>Summary</code> * instance of <code>Summary</code> is used, then the UI should, rather
* object. Convenience constructors are provided for plain text and list style * than disappearing, show the component provided by the <code>Summary</code>
* object. Convenience constructors are provided for plain text and list style
* views. * views.
* *
* @author Tim Boudreau * @author Tim Boudreau
*/ */
public class Summary { public class Summary {
private final Component comp; private final Component comp;
private Object result; private Object result;
//constructors package private - only unit tests should be able to subclass /**
//Summary * Create a <code>Summary</code> object which will display the
* passed <code>String</code> in a text component of some sort.
Summary(String text, Object result) { *
* @param text The text to display - must be non-null, greater than zero
* length and not completely whitespace
* @param result The result that should be returned when the Wizard is
* closed
*
* @return the requested <code>Summary</code> object
*/
public Summary(String text, Object result) {
//XXX this is creating components off the AWT thread - needs to change //XXX this is creating components off the AWT thread - needs to change
//to use invokeAndWait where appropriate //to use invokeAndWait where appropriate
if (text == null) { if (text == null)
throw new NullPointerException ("Text is null"); //NOI18N throw new NullPointerException("Text is null");
} if (text.trim().length() == 0)
if (text.trim().length() == 0) { throw new IllegalArgumentException("Text is empty or all whitespace");
throw new IllegalArgumentException ("Text is empty or all " + //NOI18N
"whitespace"); //NOI18N
}
this.result = result; this.result = result;
JTextArea jta = new JTextArea(); JTextArea jta = new JTextArea();
jta.setText (text); jta.setText(text);
jta.setWrapStyleWord(true); jta.setWrapStyleWord(true);
jta.setLineWrap(true); jta.setLineWrap(true);
jta.getCaret().setBlinkRate(0); jta.getCaret().setBlinkRate(0);
jta.setEditable(false); jta.setEditable(false);
jta.getCaret().setVisible(true); jta.getCaret().setVisible(true);
Font f = UIManager.getFont ("Label.font"); Font f = UIManager.getFont("Label.font");
if (f != null) { //may be on old GTK L&F, etc. if (f != null) //may be on old GTK L&F, etc.
jta.setFont (f); jta.setFont(f);
} comp = new JScrollPane(jta);
comp = new JScrollPane (jta);
} }
Summary(String[] items, Object result) { /**
if (items == null) { * Create a <code>Summary</code> object that will display the passed
throw new NullPointerException ("Items array null"); //NOI18N * <code>String</code>s in a <code>JList</code> or similar.
} *
if (items.length == 0) { * @param items A non-null list of one or more Strings to be displayed
throw new IllegalArgumentException ("Items array empty"); //NOI18N * @param result The result that should be returned when the Wizard is
} * closed
*
* @return the requested <code>Summary</code> object
*/
public Summary(String[] items, Object result) {
if (items == null)
throw new NullPointerException("Items array null");
if (items.length == 0)
throw new IllegalArgumentException("Items array empty");
this.result = result; this.result = result;
JList list = new JList(items); JList list = new JList(items);
comp = new JScrollPane (list); comp = new JScrollPane(list);
} }
Summary(Component comp, Object result) { /**
* Create a <code>Summary</code> object that will display the passed
* component.
*
* @param comp A custom component to show on the summary page after the
* Wizard has been completed
* @param result The result that should be returned when the
* <code>Wizard</code> is
* closed
*
* @return the requested <code>Summary</code> object
*/
public Summary(Component comp, Object result) {
this.result = result; this.result = result;
this.comp = comp; this.comp = comp;
if (comp == null) { if (comp == null)
throw new NullPointerException ("Null component"); //NOI18N throw new NullPointerException("Null component");
}
} }
/**
* Create a <code>Summary</code> object that will display the passed
* <code>String</code>s in a <code>JList</code> or similar.
* @param items A non-null list of one or more Strings to be displayed
* @param result The result that should be returned when the Wizard is
* closed
* @return the requested <code>Summary</code> object
*/
public static Summary create (String[] items, Object result) {
return new Summary (items, result);
}
/**
* Create a <code>Summary</code> object that will display the passed component.
* @param comp A custom component to show on the summary page after the
* Wizard has been completed
* @param result The result that should be returned when the <code>Wizard</code> is
* closed
* @return the requested <code>Summary</code> object
*/
public static Summary create (Component comp, Object result) {
return new Summary (comp, result);
}
/**
* Create a <code>Summary</code> object which will display the
* passed <code>String</code> in a text component of some sort.
* @param text The text to display - must be non-null, greater than zero
* length and not completely whitespace
* @param result The result that should be returned when the Wizard is
* closed
* @return the requested <code>Summary</code> object
*/
public static Summary create (String text, Object result) {
return new Summary (text, result);
}
/** /**
* Get the component that will display the summary information. * Get the component that will display the summary information.
*
* @return an appropriate component, the type of which may differ depending * @return an appropriate component, the type of which may differ depending
* on the factory method used to create this component * on the factory method used to create this component
*/ */
public Component getSummaryComponent() { public Component getSummaryComponent() {
return comp; return comp;
} }
/** /**
* Get the object that represents the actual result of whatever the <code>Wizard</code> * Get the object that represents the actual result of whatever the
* that created this <code>Summary</code> object computes. Note this method may not * <code>Wizard</code>
* return another instance of <code>Summary</code> or an instance of * that created this <code>Summary</code> object computes. Note this method
* may not
* return another instance of <code>Summary</code> or an instance of
* <code>DeferredWizardResult</code>. * <code>DeferredWizardResult</code>.
* @return the object passed to the factory method that created this *
* Summary object, or null. * @return the object passed to the factory method that created this
*/ * Summary object, or null.
*/
public Object getResult() { public Object getResult() {
return result; return result;
} }

View File

@@ -2,7 +2,6 @@
* To change this template, choose Tools | Templates * To change this template, choose Tools | Templates
* and open the template in the editor. * and open the template in the editor.
*/ */
package org.jackhuang.hellominecraft.utils.views.wizard.spi; package org.jackhuang.hellominecraft.utils.views.wizard.spi;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
@@ -16,8 +15,10 @@ import java.util.Set;
* @author Tim Boudreau * @author Tim Boudreau
*/ */
final class Util { final class Util {
private Util(){}
private Util() {
}
/** /**
* Get an array of step ids from an array of WizardPages * Get an array of step ids from an array of WizardPages
*/ */
@@ -28,22 +29,21 @@ final class Util {
for (int i = 0; i < pages.length; i++) { for (int i = 0; i < pages.length; i++) {
result[i] = pages[i].id(); result[i] = pages[i].id();
if (result[i] == null || uniqueNames.contains(result[i])) { if (result[i] == null || uniqueNames.contains(result[i])) {
result[i] = uniquify (getIDFromStaticMethod(pages[i].getClass()), result[i] = uniquify(getIDFromStaticMethod(pages[i].getClass()),
uniqueNames); uniqueNames);
pages[i].id = result[i]; pages[i].id = result[i];
} }
uniqueNames.add (result[i]); uniqueNames.add(result[i]);
} }
return result; return result;
} }
static String uniquify (String s, Set /* <String> */ used) { static String uniquify(String s, Set /* <String> */ used) {
String test = s; String test = s;
if (test != null) { if (test != null) {
int ix = 0; int ix = 0;
while (used.contains(test)) { while (used.contains(test))
test = s + "_" + ix++; test = s + "_" + ix++;
}
} }
return test; return test;
} }
@@ -56,24 +56,22 @@ final class Util {
for (int i = 0; i < pages.length; i++) { for (int i = 0; i < pages.length; i++) {
result[i] = pages[i].description(); result[i] = pages[i].description();
if (result[i] == null) { if (result[i] == null)
result[i] = getDescriptionFromStaticMethod (pages[i].getClass()); result[i] = getDescriptionFromStaticMethod(pages[i].getClass());
}
} }
return result; return result;
} }
static String getIDFromStaticMethod (Class clazz) { static String getIDFromStaticMethod(Class clazz) {
// System.err.println("GetID by method for " + clazz); // System.err.println("GetID by method for " + clazz);
String result = null; String result = null;
try { try {
Method m = clazz.getDeclaredMethod("getStep", new Class[] {}); Method m = clazz.getDeclaredMethod("getStep", new Class[] {});
// assert m.getReturnType() == String.class; // assert m.getReturnType() == String.class;
result = (String) m.invoke(clazz, (Object[]) null); result = (String) m.invoke(clazz, (Object[]) null);
if (result == null) { if (result == null)
throw new NullPointerException ("getStep may not return null"); throw new NullPointerException("getStep may not return null");
}
} catch (Exception ex) { } catch (Exception ex) {
//do nothing //do nothing
} }
@@ -85,27 +83,23 @@ final class Util {
* class object passed * class object passed
*/ */
static String[] getSteps(Class[] pages) { static String[] getSteps(Class[] pages) {
if (pages == null) { if (pages == null)
throw new NullPointerException("Null array of classes"); //NOI18N throw new NullPointerException("Null array of classes");
}
String[] result = new String[pages.length]; String[] result = new String[pages.length];
Set used = new HashSet (pages.length); Set used = new HashSet(pages.length);
for (int i = 0; i < pages.length; i++) { for (int i = 0; i < pages.length; i++) {
if (pages[i] == null) { if (pages[i] == null)
throw new NullPointerException("Null at " + i + " in array " + //NOI18N throw new NullPointerException("Null at " + i + " in array "
"of panel classes"); //NOI18N + "of panel classes");
}
if (!WizardPage.class.isAssignableFrom(pages[i])) { if (!WizardPage.class.isAssignableFrom(pages[i]))
throw new IllegalArgumentException(pages[i] + throw new IllegalArgumentException(pages[i]
" is not a subclass of WizardPage"); //NOI18N + " is not a subclass of WizardPage");
} result[i] = uniquify(getIDFromStaticMethod(pages[i]), used);
result[i] = uniquify (getIDFromStaticMethod (pages[i]), used); if (result[i] == null)
if (result[i] == null) {
result[i] = pages[i].getName(); result[i] = pages[i].getName();
}
} }
// System.err.println("Returning " + Arrays.asList(result)); // System.err.println("Returning " + Arrays.asList(result));
return result; return result;
@@ -120,7 +114,6 @@ final class Util {
// return false; // return false;
// } // }
// } // }
/** /**
* Get an array of descriptions by looking for the static method * Get an array of descriptions by looking for the static method
* getDescription() on each passed class object * getDescription() on each passed class object
@@ -128,9 +121,8 @@ final class Util {
static String[] getDescriptions(Class[] pages) { static String[] getDescriptions(Class[] pages) {
String[] result = new String[pages.length]; String[] result = new String[pages.length];
for (int i = 0; i < pages.length; i++) { for (int i = 0; i < pages.length; i++)
result[i] = getDescriptionFromStaticMethod(pages[i]); result[i] = getDescriptionFromStaticMethod(pages[i]);
}
return result; return result;
} }
@@ -139,35 +131,33 @@ final class Util {
String result = null; String result = null;
Method m; Method m;
try { try {
m = clazz.getDeclaredMethod("getDescription", (Class[]) null); //NOI18N m = clazz.getDeclaredMethod("getDescription", (Class[]) null);
} catch (Exception e) { } catch (Exception e) {
throw new IllegalArgumentException("Could not find or access " + //NOI18N throw new IllegalArgumentException("Could not find or access "
"public static String " + clazz.getName() + //NOI18N + "public static String " + clazz.getName()
".getDescription() - make sure it exists"); //NOI18N + ".getDescription() - make sure it exists");
} }
if (m.getReturnType() != String.class) { if (m.getReturnType() != String.class)
throw new IllegalArgumentException("getStep has wrong " //NOI18N throw new IllegalArgumentException("getStep has wrong "
+ " return type: " + m.getReturnType() + " on " + //NOI18N + " return type: " + m.getReturnType() + " on "
clazz); + clazz);
}
if (!Modifier.isStatic(m.getModifiers())) { if (!Modifier.isStatic(m.getModifiers()))
throw new IllegalArgumentException("getStep is not " + //NOI18N throw new IllegalArgumentException("getStep is not "
"static on " + clazz); //NOI18N + "static on " + clazz);
}
try { try {
m.setAccessible(true); m.setAccessible(true);
result= (String) m.invoke(null, (Object[]) null); result = (String) m.invoke(null, (Object[]) null);
} catch (InvocationTargetException ite) { } catch (InvocationTargetException ite) {
throw new IllegalArgumentException("Could not invoke " + //NOI18N throw new IllegalArgumentException("Could not invoke "
"public static String " + clazz.getName() + //NOI18N + "public static String " + clazz.getName()
".getDescription() - make sure it exists."); //NOI18N + ".getDescription() - make sure it exists.");
} catch (IllegalAccessException iae) { } catch (IllegalAccessException iae) {
throw new IllegalArgumentException("Could not invoke " + //NOI18N throw new IllegalArgumentException("Could not invoke "
"public static String " + clazz.getName() + //NOI18N + "public static String " + clazz.getName()
".getDescription() - make sure it exists."); //NOI18N + ".getDescription() - make sure it exists.");
} }
return result; return result;
} }

View File

@@ -8,7 +8,6 @@ and include the License file at http://www.netbeans.org/cddl.txt.
If applicable, add the following below the CDDL Header, with the fields If applicable, add the following below the CDDL Header, with the fields
enclosed by brackets [] replaced by your own identifying information: enclosed by brackets [] replaced by your own identifying information:
"Portions Copyrighted [year] [name of copyright owner]" */ "Portions Copyrighted [year] [name of copyright owner]" */
package org.jackhuang.hellominecraft.utils.views.wizard.spi; package org.jackhuang.hellominecraft.utils.views.wizard.spi;
import java.awt.Rectangle; import java.awt.Rectangle;
@@ -21,33 +20,35 @@ import javax.swing.JComponent;
import org.jackhuang.hellominecraft.utils.views.wizard.api.WizardDisplayer; import org.jackhuang.hellominecraft.utils.views.wizard.api.WizardDisplayer;
/** /**
* Encapsulates the logic and state of a Wizard. A Wizard gathers information * Encapsulates the logic and state of a Wizard. A Wizard gathers information
* into a Map, and then performs some action with that information when the * into a Map, and then performs some action with that information when the
* user clicks Finish. To display a wizard, pass it to one of the methods * user clicks Finish. To display a wizard, pass it to one of the methods
* on <code>WizardDisplayer.getDefault()</code>. * on <code>WizardDisplayer.getDefault()</code>.
* <p> * <p>
* A Wizard is a series of one or more steps represented * A Wizard is a series of one or more steps represented
* by panels in the user interface. Each step is identified by a unique String ID. * by panels in the user interface. Each step is identified by a unique String
* ID.
* Panels are created, usually on-demand, as the user navigates through * Panels are created, usually on-demand, as the user navigates through
* the UI of the wizard. Panels typically listen on components they contain * the UI of the wizard. Panels typically listen on components they contain
* and put values into the Map where the wizard gathers data. Note that if the * and put values into the Map where the wizard gathers data. Note that if the
* user navigates <i>backward</i>, data entered on pages after the current one * user navigates <i>backward</i>, data entered on pages after the current one
* disappears from the Map. * disappears from the Map.
* <p> * <p>
* To create a Wizard, you do not implement or instantiate this class directly, * To create a Wizard, you do not implement or instantiate this class directly,
* but rather, use one of the convenience classes in this package. There are * but rather, use one of the convenience classes in this package. There are
* three: * three:
* <ul> * <ul>
* <li><code>WizardPage</code> - use or subclass WizardPage, and pass an array * <li><code>WizardPage</code> - use or subclass WizardPage, and pass an array
* of instances, or an array of the <code>Class</code> objects of your subclasses * of instances, or an array of the <code>Class</code> objects of your
* to <code>WizardPage.createWizard()</code>. This class offers the added * subclasses
* to <code>WizardPage.createWizard()</code>. This class offers the added
* convenience that standard Swing components will be listened to automatically, * convenience that standard Swing components will be listened to automatically,
* and if their Name property is set, the value from the component will be * and if their Name property is set, the value from the component will be
* automatically put into the settings map. * automatically put into the settings map.
* </li> * </li>
* *
* <li><code>WizardPanelProvider</code> - subclass this to create a Wizard * <li><code>WizardPanelProvider</code> - subclass this to create a Wizard
* with a fixed set of steps. You provide a set of unique ID strings to the * with a fixed set of steps. You provide a set of unique ID strings to the
* constructor, for all of the steps in the wizard, and override * constructor, for all of the steps in the wizard, and override
* createPanel() to create the GUI component that should be displayed for * createPanel() to create the GUI component that should be displayed for
* each step - it will be called on demand as the user moves through the * each step - it will be called on demand as the user moves through the
@@ -55,12 +56,12 @@ import org.jackhuang.hellominecraft.utils.views.wizard.api.WizardDisplayer;
* *
* <li><code>WizardBranchController</code> - this is for creating complex * <li><code>WizardBranchController</code> - this is for creating complex
* wizards with decision points after which the future steps change, depending * wizards with decision points after which the future steps change, depending
* on what the user chooses. Create a simple wizard using WizardPage or * on what the user chooses. Create a simple wizard using WizardPage or
* WizardPanelProvider to represent the initial steps. * WizardPanelProvider to represent the initial steps.
* Then override <code>getWizardForStep()</code> or * Then override <code>getWizardForStep()</code> or
* <code>getPanelProviderForStep()</code> to return a different Wizard to * <code>getPanelProviderForStep()</code> to return a different Wizard to
* represent the remaining steps at any point where the set of future steps * represent the remaining steps at any point where the set of future steps
* changes. You can have as many branch points as you want, simply by * changes. You can have as many branch points as you want, simply by
* using WizardBranchController to create the wizards for different decision * using WizardBranchController to create the wizards for different decision
* points. * points.
* <p> * <p>
@@ -81,58 +82,63 @@ import org.jackhuang.hellominecraft.utils.views.wizard.api.WizardDisplayer;
* @author Timothy Boudreau * @author Timothy Boudreau
*/ */
public final class Wizard { public final class Wizard {
/** /**
* Constant that can be returned by <code>getForwardNavigationMode()</code> * Constant that can be returned by <code>getForwardNavigationMode()</code>
* to indicate that the Next button can be enabled (or the Finish button * to indicate that the Next button can be enabled (or the Finish button
* if the current panel is the last one in the wizard). * if the current panel is the last one in the wizard).
*/ */
public static final int MODE_CAN_CONTINUE = public static final int MODE_CAN_CONTINUE
WizardController.MODE_CAN_CONTINUE; = WizardController.MODE_CAN_CONTINUE;
/** /**
* Constant that can be returned by <code>getForwardNavigationMode</code> to indicate * Constant that can be returned by <code>getForwardNavigationMode</code> to
* indicate
* that the Finish button can be enabled if the problem string is null. * that the Finish button can be enabled if the problem string is null.
*/ */
public static final int MODE_CAN_FINISH = public static final int MODE_CAN_FINISH
WizardController.MODE_CAN_FINISH; = WizardController.MODE_CAN_FINISH;
/** /**
* Constant that can be returned by <code>getForwardNavigationMode</code> to indicate * Constant that can be returned by <code>getForwardNavigationMode</code> to
* that both the Finish and Next buttons can be enabled if the problem * indicate
* string is null. This value is a bitmask - i.e. * that both the Finish and Next buttons can be enabled if the problem
* <code>MODE_CAN_CONTINUE_OR_FINISH == MODE_CAN_CONTINUE | * string is null. This value is a bitmask - i.e.
* <code>MODE_CAN_CONTINUE_OR_FINISH == MODE_CAN_CONTINUE |
* MODE_CAN_FINISH</code> * MODE_CAN_FINISH</code>
*/ */
public static final int MODE_CAN_CONTINUE_OR_FINISH = public static final int MODE_CAN_CONTINUE_OR_FINISH
WizardController.MODE_CAN_CONTINUE_OR_FINISH; = WizardController.MODE_CAN_CONTINUE_OR_FINISH;
/** /**
* Special panel ID key indicating a branch point in the wizard, * Special panel ID key indicating a branch point in the wizard,
* after which the next step(s) are unknown. * after which the next step(s) are unknown.
*/ */
public static final String UNDETERMINED_STEP = "_#UndeterminedStep"; public static final String UNDETERMINED_STEP = "_#UndeterminedStep";
final WizardImplementation impl; //package private for unit tests final WizardImplementation impl; //package private for unit tests
/** Creates a new instance of Wizard */ /**
* Creates a new instance of Wizard
*/
Wizard(WizardImplementation impl) { Wizard(WizardImplementation impl) {
this.impl = impl; this.impl = impl;
if (impl == null) { if (impl == null)
throw new NullPointerException(); throw new NullPointerException();
}
} }
/** /**
* Notify the wizard that the user is navigating to a different panel, * Notify the wizard that the user is navigating to a different panel,
* as identified by the passed <code>id</code>. * as identified by the passed <code>id</code>.
* @param id The id of the panel being navigated to *
* @param id The id of the panel being navigated to
* @param wizardData The data gathered thus far as the user has progressed * @param wizardData The data gathered thus far as the user has progressed
* through the wizard. The contents of this map should not contain any * through the wizard. The contents of this map should not contain any
* key/values that were assigned on future panels, if the user is * key/values that were assigned on future panels, if the user is
* navigating backward. * navigating backward.
*
* @return The component that should be shown for step <code>id</code> * @return The component that should be shown for step <code>id</code>
* of the <code>Wizard</code> * of the <code>Wizard</code>
*/ */
public JComponent navigatingTo(String id, Map wizardData) { public JComponent navigatingTo(String id, Map wizardData) {
return impl.navigatingTo(id, wizardData); return impl.navigatingTo(id, wizardData);
} }
@@ -140,7 +146,7 @@ public final class Wizard {
/** /**
* Get the current step the wizard is on, as determined by the most recent * Get the current step the wizard is on, as determined by the most recent
* call to <code>navigatingTo()</code>. * call to <code>navigatingTo()</code>.
*/ */
public String getCurrentStep() { public String getCurrentStep() {
return impl.getCurrentStep(); return impl.getCurrentStep();
} }
@@ -148,31 +154,34 @@ public final class Wizard {
/** /**
* Get the id of the step that comes after current step returned by * Get the id of the step that comes after current step returned by
* <code>getCurrentStep()</code>. * <code>getCurrentStep()</code>.
* @return Null if this is the last step of the wizard; *
* <code>UNDETERMINED_STEP</code> if this is a branch point and the * @return Null if this is the last step of the wizard;
* user yet needs to do some interaction with the UI of the current * <code>UNDETERMINED_STEP</code> if this is a branch point and the
* panel to trigger computation of the id of the next step; otherwise, * user yet needs to do some interaction with the UI of the current
* the unique id of the next step. * panel to trigger computation of the id of the next step; otherwise,
*/ * the unique id of the next step.
*/
public String getNextStep() { public String getNextStep() {
return impl.getNextStep(); return impl.getNextStep();
} }
/** /**
* Get the id of the preceding step to the current one as returned by * Get the id of the preceding step to the current one as returned by
* <code>getCurrentStep()</code>, or null if the current step is the * <code>getCurrentStep()</code>, or null if the current step is the
* first page of the wizard. * first page of the wizard.
*
* @return the id of the previous step or null * @return the id of the previous step or null
*/ */
public String getPreviousStep() { public String getPreviousStep() {
return impl.getPreviousStep(); return impl.getPreviousStep();
} }
/** /**
* Get the problem string that should be displayed to the user. * Get the problem string that should be displayed to the user.
*
* @return A string describing what the user needs to do to enable * @return A string describing what the user needs to do to enable
* the Next or Finish buttons, or null if the buttons may be enabled * the Next or Finish buttons, or null if the buttons may be enabled
*/ */
public String getProblem() { public String getProblem() {
return impl.getProblem(); return impl.getProblem();
} }
@@ -181,43 +190,49 @@ public final class Wizard {
* Get the string IDs of all known steps in this wizard, terminating * Get the string IDs of all known steps in this wizard, terminating
* with <code>UNDETERMINED_STEP</code> if subsequent steps of the * with <code>UNDETERMINED_STEP</code> if subsequent steps of the
* wizard depend on the user's interaction beyond that point. * wizard depend on the user's interaction beyond that point.
*
* @return an array of strings which may individually be passed to * @return an array of strings which may individually be passed to
* <code>navigatingTo</code> to change the current step of the wizard * <code>navigatingTo</code> to change the current step of the wizard
*/ */
public String[] getAllSteps() { public String[] getAllSteps() {
return impl.getAllSteps(); return impl.getAllSteps();
} }
/** /**
* Get a long description for this panel. The long description should be * Get a long description for this panel. The long description should be
* used in preference to the short description in the top of a wizard * used in preference to the short description in the top of a wizard
* panel in the UI, if it returns non-null. * panel in the UI, if it returns non-null.
*
* @param stepId The ID of the step for which a description is requested * @param stepId The ID of the step for which a description is requested
*
* @return A more detailed localized description or null * @return A more detailed localized description or null
*/ */
public String getLongDescription(String stepId) { public String getLongDescription(String stepId) {
return impl.getLongDescription (stepId); return impl.getLongDescription(stepId);
} }
/** /**
* Get a localized String description of the step for the passed id, * Get a localized String description of the step for the passed id,
* which may be displayed in the UI of the wizard. * which may be displayed in the UI of the wizard.
*
* @param id A step id among those returned by <code>getAllSteps()</code> * @param id A step id among those returned by <code>getAllSteps()</code>
*/ */
public String getStepDescription(String id) { public String getStepDescription(String id) {
return impl.getStepDescription(id); return impl.getStepDescription(id);
} }
/** /**
* Called when the user has clicked the finish button. This method * Called when the user has clicked the finish button. This method
* computes whatever the result of the wizard is. * computes whatever the result of the wizard is.
*
* @param settings The complete set of key-value pairs gathered by the * @param settings The complete set of key-value pairs gathered by the
* various panels as the user proceeded through the wizard * various panels as the user proceeded through the wizard
*
* @return An implementation-dependent object that is the outcome of * @return An implementation-dependent object that is the outcome of
* the wizard. May be null. Special return values are instances of * the wizard. May be null. Special return values are instances of
* DeferredWizardResult and Summary which will affect the behavior of * DeferredWizardResult and Summary which will affect the behavior of
* the UI. * the UI.
*/ */
public Object finish(Map settings) throws WizardException { public Object finish(Map settings) throws WizardException {
return impl.finish(settings); return impl.finish(settings);
} }
@@ -225,20 +240,24 @@ public final class Wizard {
/** /**
* Called when the user has clicked the Cancel button in the wizard UI * Called when the user has clicked the Cancel button in the wizard UI
* or otherwise closed the UI component without completing the wizard. * or otherwise closed the UI component without completing the wizard.
* @param settings The (possibly incomplete) set of key-value pairs gathered by the *
* various panels as the user proceeded through the wizard * @param settings The (possibly incomplete) set of key-value pairs gathered
* by the
* various panels as the user proceeded through the wizard
*
* @return true if the UI may indeed be closed, false if closing should * @return true if the UI may indeed be closed, false if closing should
* not be permitted * not be permitted
*/ */
public boolean cancel (Map settings) { public boolean cancel(Map settings) {
return impl.cancel(settings); return impl.cancel(settings);
} }
/** /**
* Get the title of the Wizard that should be displayed in its dialog * Get the title of the Wizard that should be displayed in its dialog
* titlebar (if any). * titlebar (if any).
*
* @return A localized string * @return A localized string
*/ */
public String getTitle() { public String getTitle() {
return impl.getTitle(); return impl.getTitle();
} }
@@ -246,8 +265,9 @@ public final class Wizard {
/** /**
* Determine if the wizard is busy doing work in a background thread and * Determine if the wizard is busy doing work in a background thread and
* all navigation controls should be disabled. * all navigation controls should be disabled.
*
* @return whether or not the wizard is busy * @return whether or not the wizard is busy
*/ */
public boolean isBusy() { public boolean isBusy() {
return impl.isBusy(); return impl.isBusy();
} }
@@ -255,23 +275,27 @@ public final class Wizard {
/** /**
* Get the navigation mode, which determines the enablement state of * Get the navigation mode, which determines the enablement state of
* the Next and Finish buttons. * the Next and Finish buttons.
*
* @return one of the constants <code>MODE_CAN_CONTINUE</code>, * @return one of the constants <code>MODE_CAN_CONTINUE</code>,
* <code>MODE_CAN_FINISH</code>, or <code>MODE_CAN_CONTINUE_OR_FINISH</code>. * <code>MODE_CAN_FINISH</code>, or
*/ * <code>MODE_CAN_CONTINUE_OR_FINISH</code>.
*/
public int getForwardNavigationMode() { public int getForwardNavigationMode() {
return impl.getForwardNavigationMode(); return impl.getForwardNavigationMode();
} }
private volatile boolean listeningToImpl = false; private volatile boolean listeningToImpl = false;
private final List listeners = Collections.synchronizedList ( private final List listeners = Collections.synchronizedList(
new LinkedList()); new LinkedList());
private WizardObserver l = null; private WizardObserver l = null;
/** /**
* Add a WizardObserver that will be notified of navigability and step * Add a WizardObserver that will be notified of navigability and step
* changes. * changes.
*
* @param observer A WizardObserver * @param observer A WizardObserver
*/ */
public void addWizardObserver(WizardObserver observer) { public void addWizardObserver(WizardObserver observer) {
listeners.add(observer); listeners.add(observer);
if (!listeningToImpl) { if (!listeningToImpl) {
@@ -283,11 +307,12 @@ public final class Wizard {
/** /**
* Remove a WizardObserver. * Remove a WizardObserver.
*
* @param observer A WizardObserver * @param observer A WizardObserver
*/ */
public void removeWizardObserver(WizardObserver observer) { public void removeWizardObserver(WizardObserver observer) {
listeners.remove(observer); listeners.remove(observer);
if (listeningToImpl && listeners.size() == 0) { if (listeningToImpl && listeners.isEmpty()) {
impl.removeWizardObserver(l); impl.removeWizardObserver(l);
l = null; l = null;
listeningToImpl = false; listeningToImpl = false;
@@ -295,28 +320,26 @@ public final class Wizard {
} }
private class ImplL implements WizardObserver { private class ImplL implements WizardObserver {
public void stepsChanged(Wizard wizard) { public void stepsChanged(Wizard wizard) {
WizardObserver[] l = (WizardObserver[]) listeners.toArray( WizardObserver[] l = (WizardObserver[]) listeners.toArray(
new WizardObserver[listeners.size()]); new WizardObserver[listeners.size()]);
for (int i = 0; i < l.length; i++) { for (WizardObserver l1 : l)
l[i].stepsChanged(Wizard.this); l1.stepsChanged(Wizard.this);
}
} }
public void navigabilityChanged(Wizard wizard) { public void navigabilityChanged(Wizard wizard) {
WizardObserver[] l = (WizardObserver[]) listeners.toArray( WizardObserver[] l = (WizardObserver[]) listeners.toArray(
new WizardObserver[listeners.size()]); new WizardObserver[listeners.size()]);
for (int i = 0; i < l.length; i++) { for (WizardObserver l1 : l)
l[i].navigabilityChanged(Wizard.this); l1.navigabilityChanged(Wizard.this);
}
} }
public void selectionChanged(Wizard wizard) { public void selectionChanged(Wizard wizard) {
WizardObserver[] l = (WizardObserver[]) listeners.toArray( WizardObserver[] l = (WizardObserver[]) listeners.toArray(
new WizardObserver[listeners.size()]); new WizardObserver[listeners.size()]);
for (int i = 0; i < l.length; i++) { for (WizardObserver l1 : l)
l[i].selectionChanged(Wizard.this); l1.selectionChanged(Wizard.this);
}
} }
} }
@@ -324,41 +347,40 @@ public final class Wizard {
return impl.hashCode() * 17; return impl.hashCode() * 17;
} }
public boolean equals (Object o) { public boolean equals(Object o) {
if (o == this) { if (o == this)
return true; return true;
} else if (o instanceof Wizard) { else if (o instanceof Wizard)
return impl.equals (((Wizard)o).impl); return impl.equals(((Wizard) o).impl);
} else { else
return false; return false;
}
} }
/** /**
* Delegates to WizardDisplayer.showWizard() * Delegates to WizardDisplayer.showWizard()
*/ */
public void show () { public void show() {
WizardDisplayer.showWizard(this); WizardDisplayer.showWizard(this);
} }
/** /**
* Delegates to WizardDisplayer.showWizard() * Delegates to WizardDisplayer.showWizard()
*/ */
public Object show (Wizard wizard, Action help) { public Object show(Wizard wizard, Action help) {
return WizardDisplayer.showWizard (wizard, help); return WizardDisplayer.showWizard(wizard, help);
} }
/** /**
* Delegates to WizardDisplayer.showWizard() * Delegates to WizardDisplayer.showWizard()
*/ */
public Object show (Wizard wizard, Rectangle r) { public Object show(Wizard wizard, Rectangle r) {
return WizardDisplayer.showWizard (wizard, r); return WizardDisplayer.showWizard(wizard, r);
} }
/** /**
* Delegates to WizardDisplayer.showWizard() * Delegates to WizardDisplayer.showWizard()
*/ */
public Object show (Wizard wizard, Rectangle r, Action help) { public Object show(Wizard wizard, Rectangle r, Action help) {
return WizardDisplayer.showWizard (wizard, r, help, null); return WizardDisplayer.showWizard(wizard, r, help, null);
} }
} }

View File

@@ -5,8 +5,7 @@ compliance with the License.
or http://www.netbeans.org/cddl.txt. or http://www.netbeans.org/cddl.txt.
When distributing Covered Code, include this CDDL Header Notice in each file When distributing Covered Code, include this CDDL Header Notice in each file
and include the License file at http://www.netbeans.org/cddl.txt. and include the License file at http://www.netbeans.org/cddl.txt.
*/ */
package org.jackhuang.hellominecraft.utils.views.wizard.spi; package org.jackhuang.hellominecraft.utils.views.wizard.spi;
import java.util.Map; import java.util.Map;
@@ -14,76 +13,85 @@ import java.util.Map;
/** /**
* This is an optional interface for panels that want to be notified when * This is an optional interface for panels that want to be notified when
* the next and back buttons are pressed. * the next and back buttons are pressed.
* *
* The WizardPanelProvider is NOT required to create panels that implement * The WizardPanelProvider is NOT required to create panels that implement
* this interface. * this interface.
* *
* Each of these methods returns a WizardPanelNavResult that can be used to * Each of these methods returns a WizardPanelNavResult that can be used to
* indicate PROCEED or REMAIN_ON_PAGE. * indicate PROCEED or REMAIN_ON_PAGE.
* *
* The result can also be an instance of a subclass of WizardPanelNavResult * The result can also be an instance of a subclass of WizardPanelNavResult
* that implements the <code>start</code> method to use a background thread * that implements the <code>start</code> method to use a background thread
* to determine if the next page can be shown. * to determine if the next page can be shown.
* *
* @author stanley@stanleyknutson.com * @author stanley@stanleyknutson.com
*/ */
public interface WizardPanel public interface WizardPanel {
{
/** /**
* This method is invoked when the "next" button has been pushed, * This method is invoked when the "next" button has been pushed,
* to do a final validation of input (such as doing a database login). * to do a final validation of input (such as doing a database login).
* *
* If this method return false, then the "next" button will not change the * If this method return false, then the "next" button will not change the
* displayed panel. Presumably some error will have been shown to the user. * displayed panel. Presumably some error will have been shown to the user.
* *
* @param stepName * @param stepName
* @param settings * @param settings
* @param wizard * @param wizard
*
* @return WizardPanelNavResult.PROCEED if the "next" button should proceed, * @return WizardPanelNavResult.PROCEED if the "next" button should proceed,
* WizardPanelNavResult.REMAIN_ON_PAGE if "next" should not proceed, * WizardPanelNavResult.REMAIN_ON_PAGE if "next" should not proceed,
* or a instance of subclass of WizardPanelResult that will do some background computation * or a instance of subclass of WizardPanelResult that will do some
* and call the progress.finished method with one of those constants * background computation
* (or call progress.failed with the error message) * and call the progress.finished method with one of those constants
* (or call progress.failed with the error message)
*/ */
public WizardPanelNavResult allowNext (String stepName, Map settings, Wizard wizard); public WizardPanelNavResult allowNext(String stepName, Map settings, Wizard wizard);
/** /**
* This method is invoked when the "back" button has been pushed, * This method is invoked when the "back" button has been pushed,
* to discard any data from the setings that will not been needed and for which the * to discard any data from the setings that will not been needed and for
* which the
* normal "just hide that data" is not the desired behavior. * normal "just hide that data" is not the desired behavior.
* (See MergeMap for discussion of the "hide the data" behavior) * (See MergeMap for discussion of the "hide the data" behavior)
* *
* If this method return false, then the "next" button will not change the * If this method return false, then the "next" button will not change the
* displayed panel. Presumably some error will have been shown to the user. * displayed panel. Presumably some error will have been shown to the user.
* *
* @param stepName * @param stepName
* @param settings * @param settings
* @param wizard * @param wizard
*
* @return WizardPanelNavResult.PROCEED if the "back" button should proceed, * @return WizardPanelNavResult.PROCEED if the "back" button should proceed,
* WizardPanelNavResult.REMAIN_ON_PAGE if "back" should not proceed, * WizardPanelNavResult.REMAIN_ON_PAGE if "back" should not proceed,
* or a instance of subclass of WizardPanelResult that will do some background computation * or a instance of subclass of WizardPanelResult that will do some
* and call the progress.finished method with one of those constants. * background computation
* (or call progress.failed with the error message) * and call the progress.finished method with one of those constants.
* (or call progress.failed with the error message)
*/ */
public WizardPanelNavResult allowBack (String stepName, Map settings, Wizard wizard); public WizardPanelNavResult allowBack(String stepName, Map settings, Wizard wizard);
/** /**
* This method is invoked when the "finish" button has been pushed, * This method is invoked when the "finish" button has been pushed,
* to allow veto of the finish action BEFORE the wizard finish method is invoked. * to allow veto of the finish action BEFORE the wizard finish method is
* * invoked.
* If this method return false, then the "finish" button will have no effect. *
* If this method return false, then the "finish" button will have no
* effect.
* Presumably some error will have been shown to the user. * Presumably some error will have been shown to the user.
* *
* @param stepName * @param stepName
* @param settings * @param settings
* @param wizard * @param wizard
* @return WizardPanelNavResult.PROCEED if the "finish" button should proceed, *
* WizardPanelNavResult.REMAIN_ON_PAGE if "finish" should not proceed, * @return WizardPanelNavResult.PROCEED if the "finish" button should
* or a instance of subclass of WizardPanelResult that will do some background computation * proceed,
* and call the progress.finished method with one of those constants. * WizardPanelNavResult.REMAIN_ON_PAGE if "finish" should not proceed,
* (or call progress.failed with the error message) * or a instance of subclass of WizardPanelResult that will do some
* background computation
* and call the progress.finished method with one of those constants.
* (or call progress.failed with the error message)
*/ */
public WizardPanelNavResult allowFinish (String stepName, Map settings, Wizard wizard); public WizardPanelNavResult allowFinish(String stepName, Map settings, Wizard wizard);
} }