下面列出了怎么用java.awt.Window的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Loads a project inside a thread.
*
* @param parent Parent window used for dialogs.
* @param project Project to load.
* @param projectTree Project tree to expand on project loading. This argument can be null.
*/
private static void loadProjectThreaded(final Window parent, final INaviProject project,
final JTree projectTree) {
Preconditions.checkNotNull(parent, "IE00005: Parent argument can not be null");
Preconditions.checkNotNull(project, "IE01284: Project argument can not be null");
if (project.isLoading()) {
return;
}
new Thread() {
@Override
public void run() {
loadProjectInternal(parent, project, projectTree);
}
}.start();
}
private void showRichErrorDialog(String msg) {
final JTextArea area = new JTextArea();
area.setFont(errorMessageFont);
//area.setPreferredSize(new Dimension(520, 180));
area.setEditable(false);
area.setText(msg);
// Make the JOptionPane resizable using the HierarchyListener
area.addHierarchyListener(new HierarchyListener() {
public void hierarchyChanged(HierarchyEvent e) {
Window window = SwingUtilities.getWindowAncestor(area);
if (window instanceof Dialog) {
Dialog dialog = (Dialog)window;
if (!dialog.isResizable()) {
dialog.setResizable(true);
}
}
}
});
JScrollPane scroller = new JScrollPane(area);
scroller.setPreferredSize(new Dimension(520, 180));
JOptionPane.showMessageDialog(Wandora.getWandora(), scroller, "Errors", JOptionPane.PLAIN_MESSAGE);
}
public static void main(String[] args) throws AWTException {
robot = new Robot();
// test escape after selection
start();
click(KeyEvent.VK_ESCAPE);
toolkit.realSync();
// test double escape after editing
start();
click(KeyEvent.VK_1);
click(KeyEvent.VK_0);
click(KeyEvent.VK_ESCAPE);
click(KeyEvent.VK_ESCAPE);
toolkit.realSync();
// all windows should be closed
for (Window window : Window.getWindows()) {
if (window.isVisible()) {
throw new Error("found visible window: " + window.getName());
}
}
}
private JDialog createDialog(Component parentComponent, String title,
int style)
throws HeadlessException {
final JDialog dialog;
Window window = JOptionPane.getWindowForComponent(parentComponent);
if (window instanceof Frame) {
dialog = new JDialog((Frame)window, title, true);
} else {
dialog = new JDialog((Dialog)window, title, true);
}
if (window instanceof SwingUtilities.SharedOwnerFrame) {
WindowListener ownerShutdownListener =
SwingUtilities.getSharedOwnerFrameShutdownListener();
dialog.addWindowListener(ownerShutdownListener);
}
initDialog(dialog, style, parentComponent);
return dialog;
}
void addListeners(Component ancestor, boolean addToFirst) {
Component a;
firstInvisibleAncestor = null;
for (a = ancestor;
firstInvisibleAncestor == null;
a = a.getParent()) {
if (addToFirst || a != ancestor) {
a.addComponentListener(this);
if (a instanceof JComponent) {
JComponent jAncestor = (JComponent)a;
jAncestor.addPropertyChangeListener(this);
}
}
if (!a.isVisible() || a.getParent() == null || a instanceof Window) {
firstInvisibleAncestor = a;
}
}
if (firstInvisibleAncestor instanceof Window &&
firstInvisibleAncestor.isVisible()) {
firstInvisibleAncestor = null;
}
}
private void editGroup() {
Window window = SwingUtilities.getWindowAncestor(add);
Object obj = JOptionPane.showInputDialog(window,
Messages.getString(ID + ".edit.message"),
Messages.getString(ID + ".edit.title"), JOptionPane.QUESTION_MESSAGE,
null, null, list.getSelectedValue().getName());
String str;
if (obj != null && (str = obj.toString()).length() > 0) {
try {
AppGroup ag = list.getSelectedValue();
if (!ag.getName().equals(str)) {
ag.setName(str);
DatabaseManager dbm = globals.get(DatabaseManager.class);
dbm.get(AppGroupDao.class).update(ag);
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(window,
Messages.getString(ID + ".failure"));
// e.printStackTrace();
}
reload();
}
}
@Override
public boolean filterEvent(Window window, int eventId) {
/*
* Note that we are only interested in the closing of the gateway splash
* frame, because that indicates that the gateway is now in a position to
* start handling menu commands.
*
* Note also that the splash frame's window title is repeatedly changed during
* gateway initialisation, and it's only the last title value that we use for
* recognising it
*/
switch (eventId) {
case WindowEvent.WINDOW_CLOSED:
return true;
default:
return false;
}
}
private synchronized void notifyClientWindowChange(Window window) {
if (inputMethod == null) {
return;
}
// if the window is invisible or iconified, send null to the input method.
if (!window.isVisible() ||
((window instanceof Frame) && ((Frame)window).getState() == Frame.ICONIFIED)) {
clientWindowLocation = null;
inputMethod.notifyClientWindowChange(null);
return;
}
Rectangle location = window.getBounds();
if (clientWindowLocation == null || !clientWindowLocation.equals(location)) {
clientWindowLocation = location;
inputMethod.notifyClientWindowChange(clientWindowLocation);
}
}
/*************************************************
* END OF FOCUS STUFF
*************************************************/
public void setVisible(boolean b) {
if (b) {
focusLog.fine("A component " + getTarget().getClass().getName()
+ " is going to be shown. Put the window on the waiting list: " +
((Window)XToolkit.windowToXWindow(getWindow()).getToplevelXWindow().getTarget()).getClass().getName() +
"; windowId : " + Long.toHexString(getWindow()));
if (getTarget() instanceof javax.swing.Popup) {
WindowStateMachine.get().waitForNotifyAfterRaise(getWindow());
}
}
xSetVisible(b);
}
@Override
public void actionPerformed(ActionEvent event) {
Window windowAncestor = null;
if (event.getSource() instanceof JComponent) {
JComponent eventSource = (JComponent) event.getSource();
windowAncestor = SwingUtilities.getWindowAncestor(eventSource);
}
final JFileChooser chooser = FileChooserFactory.getInstance().createDirChooser(model.getProductDir());
chooser.setDialogTitle("Select Target Directory");
if (chooser.showDialog(windowAncestor, APPROVE_BUTTON_TEXT) == JFileChooser.APPROVE_OPTION) {
final File selectedDir = chooser.getSelectedFile();
if (selectedDir != null) {
model.setProductDir(selectedDir);
} else {
model.setProductDir(new File("."));
}
}
}
public static void main(String[] args) throws Exception {
final Window rootWindow = createWindow(null);
new Thread(() -> {
for (int i = 0; i < WINDOWS_COUNT; i++) {
createWindow(rootWindow);
}
}).start();
boolean alwaysOnTop = true;
for (int i = 0; i < STEPS_COUNT; i++) {
Thread.sleep(10);
rootWindow.setAlwaysOnTop(alwaysOnTop);
alwaysOnTop = !alwaysOnTop;
}
}
/**
* Display the dialog.
* @param target text component (its Window will be the parent)
*/
public void displayFor(JTextComponent target) {
try {
int dot = target.getSelectionStart();
Window window = SwingUtilities.getWindowAncestor(target);
Rectangle rt = target.modelToView(dot);
Point loc = new Point(rt.x, rt.y);
// convert the location from Text Componet coordinates to
// Frame coordinates...
loc = SwingUtilities.convertPoint(target, loc, window);
// and then to Screen coordinates
SwingUtilities.convertPointToScreen(loc, window);
setLocationRelativeTo(window);
setLocation(loc);
} catch (BadLocationException ex) {
Logger.getLogger(ReflectCompletionDialog.class.getName()).log(Level.SEVERE, null, ex);
} finally {
setFonts(target.getFont());
updateItems();
jTxtItem.setText(target.getSelectedText());
setVisible(true);
}
}
/**
* <p>创建窗体鼠标监听器, 处理窗体的移动和拖拽事件</p>
*
* <p>Create Window mouse listener, handle window move and drag event.</p>
*
* @param root <code>JRootPane</code>
* @return <code>MouseInputListener</code> window move and drag event listener.
*/
protected MouseInputListener installWindowListeners(JRootPane root)
{
Window window = SwingUtilities.getWindowAncestor(root);
if (window != null)
{
if (mouseInputListener == null)
{
mouseInputListener = new WindowMouseHandler(root);
}
window.addMouseListener(mouseInputListener);
window.addMouseMotionListener(mouseInputListener);
}
return mouseInputListener;
}
public void doBrowseForFile(AudioPlayerComponent apc) {
Window w = SwingUtilities.getWindowAncestor(apc);
if (!(w instanceof Frame))
throw new RuntimeException(
"cannot invoke a FileDialog if the player is not in a java.awt.Frame");
// the button shouldn't be enabled if w isn't a Frame...
Frame f = (Frame) w;
FileDialog fd = new FileDialog(f);
fd.pack();
fd.setLocationRelativeTo(null);
fd.setVisible(true);
if (fd.getFile() == null)
throw new UserCancelledException();
File file = new File(fd.getDirectory() + fd.getFile());
try {
apc.setSource(file.toURI().toURL());
} catch (MalformedURLException e) {
e.printStackTrace();
apc.setSource(null);
}
}
public static void showMessages(Component parent, List<String> messages) {
if ((messages == null) || (messages.size() == 0)){
return;
}
Window window = SwingUtilities.windowForComponent(parent);
StringBuilder sb = new StringBuilder();
if (messages != null) {
for (int i = 0, size = messages.size(); i < size; i++) {
sb.append(messages.get(i));
if (i < size - 1) {
sb.append("\r\n");
}
}
}
JOptionPane.showMessageDialog(window, sb.toString());
}
void addListeners(Component ancestor, boolean addToFirst) {
Component a;
firstInvisibleAncestor = null;
for (a = ancestor;
firstInvisibleAncestor == null;
a = a.getParent()) {
if (addToFirst || a != ancestor) {
a.addComponentListener(this);
if (a instanceof JComponent) {
JComponent jAncestor = (JComponent)a;
jAncestor.addPropertyChangeListener(this);
}
}
if (!a.isVisible() || a.getParent() == null || a instanceof Window) {
firstInvisibleAncestor = a;
}
}
if (firstInvisibleAncestor instanceof Window &&
firstInvisibleAncestor.isVisible()) {
firstInvisibleAncestor = null;
}
}
private JDialog createDialog(Component parentComponent, String title,
int style)
throws HeadlessException {
final JDialog dialog;
Window window = JOptionPane.getWindowForComponent(parentComponent);
if (window instanceof Frame) {
dialog = new JDialog((Frame)window, title, true);
} else {
dialog = new JDialog((Dialog)window, title, true);
}
if (window instanceof SwingUtilities.SharedOwnerFrame) {
WindowListener ownerShutdownListener =
SwingUtilities.getSharedOwnerFrameShutdownListener();
dialog.addWindowListener(ownerShutdownListener);
}
initDialog(dialog, style, parentComponent);
return dialog;
}
/**
* Shows a dialog where the user can resolve a function.
*
* @param parent Parent window used for dialogs.
* @param database Database the function belongs to.
* @param function Function to be forwarded to another module.
*/
public static void resolveFunction(final Window parent, final IDatabase database,
final INaviFunction function) {
final CFunctionSelectionDialog dlg = new CFunctionSelectionDialog(parent, database);
GuiHelper.centerChildToParent(parent, dlg, true);
dlg.setVisible(true);
final INaviFunction selectedFunction = dlg.getSelectedFunction();
if (selectedFunction != null) {
try {
function.setForwardedFunction(selectedFunction);
} catch (final CouldntSaveDataException e) {
CUtilityFunctions.logException(e);
}
}
}
private boolean accept(Component aComponent) {
if (!(aComponent.isVisible() && aComponent.isDisplayable() &&
aComponent.isFocusable() && aComponent.isEnabled())) {
return false;
}
// Verify that the Component is recursively enabled. Disabling a
// heavyweight Container disables its children, whereas disabling
// a lightweight Container does not.
if (!(aComponent instanceof Window)) {
for (Container enableTest = aComponent.getParent();
enableTest != null;
enableTest = enableTest.getParent())
{
if (!(enableTest.isEnabled() || enableTest.isLightweight())) {
return false;
}
if (enableTest instanceof Window) {
break;
}
}
}
return true;
}
@Override
public boolean requestWindowFocus(CausedFocusEvent.Cause cause) {
if (!focusAllowedFor()) {
return false;
}
if (getPlatformWindow().rejectFocusRequest(cause)) {
return false;
}
Window opposite = LWKeyboardFocusManagerPeer.getInstance().
getCurrentFocusedWindow();
changeFocusedWindow(true, opposite);
return true;
}
public static void main(String[] args) throws AWTException {
robot = new Robot();
// test escape after selection
start();
click(KeyEvent.VK_ESCAPE);
toolkit.realSync();
// test double escape after editing
start();
click(KeyEvent.VK_1);
click(KeyEvent.VK_0);
click(KeyEvent.VK_ESCAPE);
click(KeyEvent.VK_ESCAPE);
toolkit.realSync();
// all windows should be closed
for (Window window : Window.getWindows()) {
if (window.isVisible()) {
throw new Error("found visible window: " + window.getName());
}
}
}
@Override
public ExitCode showSetupDialog(Window parent, boolean valueCheckRequired) {
PeakList selectedPeakLists[] = getParameter(peakLists).getValue().getMatchingPeakLists();
if (selectedPeakLists.length > 0) {
RawDataFile plDataFiles[] = selectedPeakLists[0].getRawDataFiles();
getParameter(dataFiles).setChoices(plDataFiles);
}
return super.showSetupDialog(parent, valueCheckRequired);
}
public PrintRequestAttributeSet
showDocumentProperties(PrinterJob job,
Window owner,
PrintService service,
PrintRequestAttributeSet aset) {
if (!(job instanceof WPrinterJob)) {
return null;
}
WPrinterJob wJob = (WPrinterJob)job;
return wJob.showDocumentProperties(owner, service, aset);
}
@Override
public void addNotify() {
super.addNotify();
//#205194 - cannot minimize floating tab group
Window w = SwingUtilities.getWindowAncestor( displayer );
boolean isFloating = w != WindowManager.getDefault().getMainWindow();
if( isFloating )
setVisible( false );
}
public void removeDropTarget(DropTarget dt) {
Component comp = target;
while(!(comp == null || comp instanceof Window)) {
comp = comp.getParent();
}
if (comp instanceof Window) {
XWindowPeer wpeer = (XWindowPeer)(comp.getPeer());
if (wpeer != null) {
wpeer.removeDropTarget();
}
}
}
/**
* Kills all children. Hiding under the covers won't save them.
*/
private void killAllChildren() {
for (Window child : childWindows) {
child.dispose();
}
childWindows.clear();
}
public void adjustSize() { // overrides its super
String size = getProperty("size"); //$NON-NLS-1$
((Window) getComponent()).validate();
if((size!=null)&&size.trim().toLowerCase().equals("pack")) { //$NON-NLS-1$
((Window) getComponent()).pack();
} else {
super.adjustSize();
}
}
private boolean adjustExitSessionTime(Window window) {
Date newLogoffTime =new Date(System.currentTimeMillis() - 5 * 60 * 1000);
Calendar cal = Calendar.getInstance();
cal.setTime(newLogoffTime);
String newLogoffTimeText = new SimpleDateFormat("hh:mm").format(newLogoffTime);
SwingUtils.setTextField(window, 0, newLogoffTimeText);
if (cal.get(Calendar.AM_PM) == Calendar.AM) {
if (! SwingUtils.setRadioButtonSelected(window, "AM" /*, true*/)) return false;
} else {
if (! SwingUtils.setRadioButtonSelected(window, "PM" /*, true*/)) return false;
}
if (SwingUtils.clickButton(window, "Update")) {
} else if (SwingUtils.clickButton(window, "Apply")) { // TWS 974
} else if (SwingUtils.clickButton(window, "Aktualisieren")) {
} else {
return false;
}
if (SwingUtils.clickButton(window, "Close")) {
} else if (SwingUtils.clickButton(window, "OK")) { // TWS 974
} else if (SwingUtils.clickButton(window, "Schliessen")) {
} else {
return false;
}
Utils.logToConsole("AutoLogoff time changed to " +
newLogoffTimeText +
(cal.get(Calendar.AM_PM) == Calendar.AM ? "AM" : "PM"));
return true;
}
public static void showViewsAndPerformCallBack(final Window parent,
final IViewContainer container, final INaviView[] views, final CGraphWindow window,
final FutureCallback<Boolean> callBack) {
for (final INaviView view : views) {
CViewOpener.showViewAndCallBack(parent, container, view, window, callBack);
}
}
@Override
public boolean filterEvent(Window window, int eventId) {
switch (eventId) {
case WindowEvent.WINDOW_OPENED:
if (ConfigDialogManager.configDialogManager().getApiConfigChangeConfirmationExpected()) return true;
return false;
default:
return false;
}
}