下面列出了javax.swing.SwingUtilities#windowForComponent ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
*
*/
public void updateTitle()
{
JFrame frame = (JFrame) SwingUtilities.windowForComponent(this);
if (frame != null)
{
String title = (currentFile != null) ? currentFile
.getAbsolutePath() : mxResources.get("newDiagram");
if (modified)
{
title += "*";
}
frame.setTitle(title + " - " + appTitle);
}
}
@Override
public void actionPerformed(ActionContext context) {
CompEditorModel editorModel = (CompEditorModel) model;
DataTypeComponent dtComponent = getUnalignedBitFieldComponent();
if (dtComponent == null) {
return;
}
BitFieldEditorDialog dlg = new BitFieldEditorDialog(editorModel.viewComposite,
provider.dtmService, dtComponent.getOrdinal(),
ordinal -> refreshTableAndSelection(editorModel, ordinal));
Component c = provider.getComponent();
Window w = SwingUtilities.windowForComponent(c);
DockingWindowManager.showDialog(w, dlg, c);
requestTableFocus();
}
/**
* Shows a modal font-chooser dialog and blocks until the dialog is
* hidden. If the user presses the "OK" button, then this method
* hides/disposes the dialog and returns the selected color. If the
* user presses the "Cancel" button or closes the dialog without
* pressing "OK", then this method hides/disposes the dialog and
* returns <code>null</code>.
*
* @param parent the parent <code>Component</code> for the
* dialog
* @param title the String containing the dialog's title
* @param initialFont the initial Font set when the font-chooser is
* shown
* @return the selected font or <code>null</code> if the user
* opted out
* @exception java.awt.HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static Font showDialog(Component parent, String title, Font initialFont) {
BaseDialog dialog;
Window window = (parent == null?JOptionPane.getRootFrame():SwingUtilities
.windowForComponent(parent));
if (window instanceof Frame) {
dialog = new BaseDialog((Frame)window, title, true);
} else {
dialog = new BaseDialog((Dialog)window, title, true);
}
dialog.setDialogMode(BaseDialog.OK_CANCEL_DIALOG);
dialog.getBanner().setVisible(false);
JFontChooser chooser = new JFontChooser();
chooser.setSelectedFont(initialFont);
dialog.getContentPane().setLayout(new BorderLayout());
dialog.getContentPane().add("Center", chooser);
dialog.pack();
dialog.setLocationRelativeTo(parent);
if (dialog.ask()) {
return chooser.getSelectedFont();
} else {
return null;
}
}
public void show(Point location) {
Rectangle screenBounds = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gds = ge.getScreenDevices();
for (GraphicsDevice device : gds) {
GraphicsConfiguration gc = device.getDefaultConfiguration();
screenBounds = gc.getBounds();
if (screenBounds.contains(location)) {
break;
}
}
// showing the popup tooltip
cp = new TooltipContentPanel(master.getTextComponent());
Window w = SwingUtilities.windowForComponent(master.getTextComponent());
contentWindow = new JWindow(w);
contentWindow.add(cp);
contentWindow.pack();
Dimension dim = contentWindow.getSize();
if (location.y + dim.height + SCREEN_BORDER > screenBounds.y + screenBounds.height) {
dim.height = (screenBounds.y + screenBounds.height) - (location.y + SCREEN_BORDER);
}
if (location.x + dim.width + SCREEN_BORDER > screenBounds.x + screenBounds.width) {
dim.width = (screenBounds.x + screenBounds.width) - (location.x + SCREEN_BORDER);
}
contentWindow.setSize(dim);
contentWindow.setLocation(location.x, location.y - 1); // slight visual adjustment
contentWindow.setVisible(true);
Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.MOUSE_EVENT_MASK | AWTEvent.KEY_EVENT_MASK);
w.addWindowFocusListener(this);
contentWindow.addWindowFocusListener(this);
}
public void mouseDragged(MouseEvent e)
{
int x=e.getX(),y=e.getY(),deltaX=x-this.lastX,deltaY=y-this.lastY;
//目的组件未设置就默认认为是它的父窗口吧
Component win=(destCom==null?SwingUtilities.windowForComponent(srcCom):destCom);
if(win!=null)
// win.setLocation((int)(win.getLocation().getX()+deltaX)
// , (int)(win.getLocation().getY()+deltaY));
setLocationImpl(win,deltaX,deltaY);
}
private void closeToolbar() {
if ( toolBar == null ) {
return;
}
if ( toolBar.getParent() != toolbarHolder ) {
// ha!, we detected that the toolbar is floating ...
// Log.debug (currentToolbar.getParent());
final Window w = SwingUtilities.windowForComponent( toolBar );
if ( w != null ) {
w.setVisible( false );
w.dispose();
}
}
toolBar.setVisible( false );
}
private static boolean willPopupBeContained(JPopupMenu popup, Point origin) {
if (!popup.isShowing()) {
return false;
}
Window w = SwingUtilities.windowForComponent(popup.getInvoker());
Rectangle r = new Rectangle(origin, popup.getSize());
return (w != null) && w.getBounds().contains(r);
}
/** Creates new form Import9Patch */
public Import9Patch(java.awt.Component parent, EditableResources res, String theme) {
super((java.awt.Frame)SwingUtilities.windowForComponent(parent), true);
this.res = res;
this.theme = theme;
initComponents();
AddThemeEntry.initUIIDComboBox(uiidCombo);
pack();
setLocationByPlatform(true);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent ev) {
JComponent c = (JComponent)ev.getSource();
Window w = SwingUtilities.windowForComponent(c);
if (w != null) {
w.dispose();
}
Installer.RP.post(this);
}
/** Computes width of string up to maxCharCount, with font of given JComponent
* and with maximum percentage of owning Window that can be taken */
private static int computeWidth (JComponent comp, int maxCharCount, int percent) {
FontMetrics fm = comp.getFontMetrics(comp.getFont());
int charW = fm.charWidth('X');
int result = charW * maxCharCount;
// limit width to 50% of containing window
Window w = SwingUtilities.windowForComponent(comp);
if (w != null) {
result = Math.min(result, w.getWidth() * percent / 100);
}
return result;
}
/**
* Creates the popup, calculates position and sets focus
*/
private void showPopup(Component source) {
actionSource = source;
actionSource.addComponentListener(this);
if (actionSource instanceof JToggleButton) {
JToggleButton toggleSource = (JToggleButton) actionSource;
toggleSource.setSelected(true);
}
containingWindow = SwingUtilities.windowForComponent(actionSource);
containingWindow.addComponentListener(this);
Point position = calculatePosition(source);
popupComponent.setLocation(position);
popupComponent.setVisible(true);
popup = new ContainerPopupDialog(containingWindow, popupComponent, position);
popup.setVisible(true);
popup.requestFocus();
popupComponent.startTracking(containingWindow);
if (propertyChangeListener != null) {
popupComponent.getComponent().removePropertyChangeListener(PACK_EVENT, propertyChangeListener);
}
propertyChangeListener = e -> {
if (popup != null) {
popup.pack();
// best position may change due to changed dimensions, recalculate and set
Point popupPosition = calculatePosition(source);
popup.setLocation(popupPosition);
}
};
popupComponent.getComponent().addPropertyChangeListener(PACK_EVENT, propertyChangeListener);
}
public static Double showEditNumber(Component parent, String title, String message, Icon icon) {
Window window = SwingUtilities.windowForComponent(parent);
JNumberDialog myMsg;
if (window instanceof Frame) {
myMsg = new JNumberDialog((Frame) window, true);
} else {
myMsg = new JNumberDialog((Dialog) window, true);
}
myMsg.setTitle(title, message, icon);
myMsg.setVisible(true);
return myMsg.m_value;
}
public static SelectPrinter getSelectPrinter(Component parent, String[] printers) {
Window window = SwingUtilities.windowForComponent(parent);
SelectPrinter myMsg;
if (window instanceof Frame) {
myMsg = new SelectPrinter((Frame) window, true);
} else {
myMsg = new SelectPrinter((Dialog) window, true);
}
myMsg.init(printers);
myMsg.applyComponentOrientation(parent.getComponentOrientation());
return myMsg;
}
private void turnTransparencyOff() {
NativeWindowSystem nws = NativeWindowSystem.getDefault();
for( ModeImpl m : WindowManagerImpl.getInstance().getModes() ) {
if( m.getState() != Constants.MODE_STATE_SEPARATED
|| m.getKind() == Constants.MODE_KIND_EDITOR )
continue;
TopComponent tc = m.getSelectedTopComponent();
if( null != tc ) {
Window w = SwingUtilities.windowForComponent(tc);
if( null != w ) {
nws.setWindowAlpha( w, 1.0f );
}
}
}
}
/** Creates new form About */
public About(java.awt.Component parent) {
super((Frame)SwingUtilities.windowForComponent(parent), true);
initComponents();
Properties p = new Properties();
try {
p.load(getClass().getResourceAsStream("/version.properties"));
} catch (IOException ex) {
ex.printStackTrace();
}
buildNumber.setText(p.getProperty("build", "1"));
pack();
setLocationRelativeTo(parent);
setVisible(true);
}
/** Computes width of string up to maxCharCount, with font of given JComponent
* and with maximum percentage of owning Window that can be taken */
private static int computeWidth (JComponent comp, int maxCharCount, int percent) {
FontMetrics fm = comp.getFontMetrics(comp.getFont());
int charW = fm.charWidth('X');
int result = charW * maxCharCount;
// limit width to 50% of containing window
Window w = SwingUtilities.windowForComponent(comp);
if (w != null) {
result = Math.min(result, w.getWidth() * percent / 100);
}
return result;
}
private void setSizeAndDimensions(@NotNull JTable table,
@NotNull JBPopup popup,
@NotNull RelativePoint popupPosition,
@NotNull List<UsageNode> data) {
JComponent content = popup.getContent();
Window window = SwingUtilities.windowForComponent(content);
Dimension d = window.getSize();
int width = calcMaxWidth(table);
width = (int)Math.max(d.getWidth(), width);
Dimension headerSize = ((AbstractPopup)popup).getHeaderPreferredSize();
width = Math.max((int)headerSize.getWidth(), width);
width = Math.max(myWidth, width);
if (myWidth == -1) myWidth = width;
int newWidth = Math.max(width, d.width + width - myWidth);
myWidth = newWidth;
int rowsToShow = Math.min(30, data.size());
Dimension dimension = new Dimension(newWidth, table.getRowHeight() * rowsToShow);
Rectangle rectangle = fitToScreen(dimension, popupPosition, table);
dimension = rectangle.getSize();
Point location = window.getLocation();
if (!location.equals(rectangle.getLocation())) {
window.setLocation(rectangle.getLocation());
}
if (!data.isEmpty()) {
TableScrollingUtil.ensureSelectionExists(table);
}
table.setSize(dimension);
//table.setPreferredSize(dimension);
//table.setMaximumSize(dimension);
//table.setPreferredScrollableViewportSize(dimension);
Dimension footerSize = ((AbstractPopup)popup).getFooterPreferredSize();
int newHeight = (int)(dimension.height + headerSize.getHeight() + footerSize.getHeight()) + 4/* invisible borders, margins etc*/;
Dimension newDim = new Dimension(dimension.width, newHeight);
window.setSize(newDim);
window.setMinimumSize(newDim);
window.setMaximumSize(newDim);
window.validate();
window.repaint();
table.revalidate();
table.repaint();
}
protected void showTipWindow() {
if(insideComponent == null || !insideComponent.isShowing())
return;
cancelled = false;
LOG.fine("cancelled=false"); //NOI18N
for (Container p = insideComponent.getParent(); p != null; p = p.getParent()) {
if (p instanceof JPopupMenu) break;
if (p instanceof Window) {
if (!((Window)p).isFocused()) {
return;
}
break;
}
}
if (enabled) {
Dimension size;
// Just to be paranoid
hideTipWindow();
tip = createToolTip();
tip.setTipText(toolTipText);
size = tip.getPreferredSize();
Point location = provider.getToolTipLocation( mouseEvent.getPoint(), size );
// we do not adjust x/y when using awt.Window tips
if (popupRect == null){
popupRect = new Rectangle();
}
popupRect.setBounds( location.x, location.y, size.width, size.height );
PopupFactory popupFactory = PopupFactory.getSharedInstance();
tipWindow = popupFactory.getPopup(insideComponent, tip,
location.x,
location.y);
tipWindow.show();
Window componentWindow = SwingUtilities.windowForComponent(
insideComponent);
window = SwingUtilities.windowForComponent(tip);
if (window != null && window != componentWindow) {
window.addMouseListener(this);
}
else {
window = null;
}
Toolkit.getDefaultToolkit().addAWTEventListener( getAWTListener(), AWTEvent.KEY_EVENT_MASK );
tipShowing = true;
}
}
@RandomlyFails
public void testLeafDialog () throws Exception {
boolean leaf = true;
DialogDescriptor ownerDD = new DialogDescriptor (pane, "Owner", true, new Object[] {closeOwner}, null, 0, null, null, leaf);
final Dialog owner = DialogDisplayer.getDefault ().createDialog (ownerDD);
// make leaf visible
postInAwtAndWaitOutsideAwt (new Runnable () {
@Override
public void run () {
owner.setVisible (true);
}
});
assertShowing("Owner should be visible", true, owner);
child = DialogDisplayer.getDefault ().createDialog (childDD);
// make the child visible
postInAwtAndWaitOutsideAwt (new Runnable () {
@Override
public void run () {
child.setVisible (true);
}
});
assertShowing("Child will be visible", true, child);
Window w = SwingUtilities.windowForComponent(child);
assertFalse ("No dialog is owned by leaf dialog.", owner.equals (w.getOwner ()));
assertEquals ("The leaf dialog has no child.", 0, owner.getOwnedWindows ().length);
assertTrue ("Leaf is visible", owner.isVisible ());
assertTrue ("Child is visible", child.isVisible ());
// close the leaf window
postInAwtAndWaitOutsideAwt (new Runnable () {
@Override
public void run () {
owner.setVisible (false);
}
});
assertShowing("Disappear", false, owner);
assertFalse ("Leaf is dead", owner.isVisible ());
assertTrue ("Child is visible still", child.isVisible ());
// close the child dialog
postInAwtAndWaitOutsideAwt (new Runnable () {
@Override
public void run () {
child.setVisible (false);
}
});
assertShowing("Child is invisible", false, child);
assertFalse ("Child is dead too", child.isVisible ());
}
public AddImageResource(java.awt.Component c, EditableResources res) {
this((java.awt.Frame)SwingUtilities.windowForComponent(c), true, res);
}