下面列出了怎么用java.awt.event.ComponentListener的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Creates and returns a scroll panel which wraps the specified view component.<br>
* The returned scroll panel disables vertical scroll bar, and only displays the horizontal scroll bar when the view does not fit
* into the size of the view port. When the view fits into the view port, the scroll pane will not claim the space of the scroll bar.
*
* @param view view to wrap in the scroll pane
* @param parentToRevalidate parent to revalidate when the scroll pane decides to change its size
*
* @return the created self managed scroll pane
*/
public static JScrollPane createSelfManagedScrollPane( final Component view, final JComponent parentToRevalidate ) {
final JScrollPane scrollPane = new JScrollPane( view );
scrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_NEVER );
scrollPane.getHorizontalScrollBar().setPreferredSize( new Dimension( 0, 12 ) ); // Only want to restrict the height, width doesn't matter (it takes up whole width)
scrollPane.getHorizontalScrollBar().setUnitIncrement( 10 );
final ComponentListener scrollPaneComponentListener = new ComponentAdapter() {
@Override
public void componentResized( final ComponentEvent event ) {
scrollPane.setHorizontalScrollBarPolicy( view.getWidth() < scrollPane.getWidth() ? JScrollPane.HORIZONTAL_SCROLLBAR_NEVER : JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
scrollPane.setPreferredSize( null );
scrollPane.setPreferredSize( new Dimension( 10, scrollPane.getPreferredSize().height ) );
parentToRevalidate.revalidate();
}
};
scrollPane.addComponentListener( scrollPaneComponentListener );
return scrollPane;
}
private void showPopupPanel() {
if (mPopup == null)
mPopup = new ComponentUtils.ModalPopup(this);
PopupPanel panel = this.getPanel().orElse(null);
if (panel == null)
return;
mPopup.removeAll();
panel.onShow();
for (ComponentListener cl : panel.getComponentListeners())
panel.removeComponentListener(cl);
panel.addComponentListener(new ComponentAdapter() {
@Override
public void componentHidden(ComponentEvent e) {
mPopup.close();
}
});
mPopup.add(panel);
mPopup.showPopup();
}
/**
* Constructs new {@link WebMultiSplitPaneModel}.
*/
public WebMultiSplitPaneModel ()
{
this.views = new ArrayList<MultiSplitView> ();
this.dividers = new ArrayList<WebMultiSplitPaneDivider> ( 2 );
this.listeners = new EventListenerList ();
this.listeners.add ( ComponentListener.class, new ComponentAdapter ()
{
@Override
public void componentResized ( final ComponentEvent e )
{
// Informing about operation
onOperation ( Operation.splitPaneResized );
}
} );
draggedDividerIndex = -1;
dragStart = null;
}
/**
* This Method is responsible for removing the old MouseGrabber from the AppContext, to be able to add our own
* implementation for it that is a bit more generous with closing the popup.
*/
public static void uninstallOldMouseGrabber(final ChangeListener oldMouseGrabber) {
if (oldMouseGrabber == null) return;
MenuSelectionManager menuSelectionManager = MenuSelectionManager.defaultManager();
menuSelectionManager.removeChangeListener(oldMouseGrabber);
if (oldMouseGrabber instanceof AWTEventListener) {
Toolkit tk = Toolkit.getDefaultToolkit();
java.security.AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
tk.removeAWTEventListener((AWTEventListener) oldMouseGrabber);
return null;
});
}
MenuElement[] path = menuSelectionManager.getSelectedPath();
if (path.length != 0 && path[0] != null) {
Component invoker = path[0].getComponent();
if (invoker instanceof JPopupMenu) {
invoker = ((JPopupMenu) invoker).getInvoker();
}
Window grabbedWindow = DarkUIUtil.getWindow(invoker);
if (oldMouseGrabber instanceof WindowListener) {
grabbedWindow.removeWindowListener((WindowListener) oldMouseGrabber);
}
if (oldMouseGrabber instanceof ComponentListener) {
grabbedWindow.removeComponentListener((ComponentListener) oldMouseGrabber);
}
}
}
/** Create a component listener to handle size changes if the table model
* is large-model */
private ComponentListener getComponentListener() {
if (componentListener == null) {
componentListener = new SizeManager();
}
return componentListener;
}
@Override
public void removeNotify() {
super.removeNotify();
for (ComponentListener l : getComponentListeners()) {
super.removeComponentListener(l);
}
}
/**
* Maps {@code Component.addComponentListener(ComponentListener)}
* through queue
*/
public void addComponentListener(final ComponentListener componentListener) {
runMapping(new MapVoidAction("addComponentListener") {
@Override
public void map() {
getSource().addComponentListener(componentListener);
}
});
}
/**
* Maps {@code Component.removeComponentListener(ComponentListener)}
* through queue
*/
public void removeComponentListener(final ComponentListener componentListener) {
runMapping(new MapVoidAction("removeComponentListener") {
@Override
public void map() {
getSource().removeComponentListener(componentListener);
}
});
}
/**
* Create a new ScrolledViewport.
*
* @param view child component. The border that view has at the moment when
* the ScrolledViewport is created is used when ant least one of the scroll
* bars is visible.
*/
public ScrolledViewport(JComponent view) {
this.view = view;
originalBorder = view.getBorder();
scrollPane = new JScrollPane(view);
ComponentListener listener = new ScrollBarVisibilityChangeListener();
scrollPane.getHorizontalScrollBar().addComponentListener(listener);
scrollPane.getVerticalScrollBar().addComponentListener(listener);
}
private void pressAskQuestionButtonOnVisible() {
ComponentListener listener = new ComponentAdapter() {
// this method is called after componentShown and performs the click
// otherwise the component may get moved/resized after clicking
@Override
public void componentResized(ComponentEvent e) {
askQuestion.doClick();
}
};
this.addComponentListener(listener);
}
/**
* Adds the specified component listener to receive component events from
* this component. If listener l is null, no exception is thrown and no
* action is performed.
*
* @param l the component listener
*/
public void addComponentListener(ComponentListener l) {
if (frame != null) {
frame.addComponentListener(l);
} else {
component.addComponentListener(l);
}
}
protected ComponentListener createComponentListener() {
if (UIManager.getBoolean("InternalFrame.useTaskBar")) {
return new ComponentHandler() {
public void componentResized(ComponentEvent e) {
if (frame != null && frame.isMaximum()) {
JDesktopPane desktop = (JDesktopPane) e.getSource();
for (Component comp : desktop.getComponents()) {
if (comp instanceof SeaGlassDesktopPaneUI.TaskBar) {
frame.setBounds(0, 0, desktop.getWidth(), desktop.getHeight() - comp.getHeight());
frame.revalidate();
break;
}
}
}
// Update the new parent bounds for next resize, but don't
// let the super method touch this frame
JInternalFrame f = frame;
frame = null;
super.componentResized(e);
frame = f;
}
};
} else {
return super.createComponentListener();
}
}
@Override
public void install ( @NotNull final WebMultiSplitPane multiSplitPane, @Nullable final List<MultiSplitView> views,
@Nullable final List<WebMultiSplitPaneDivider> dividers )
{
if ( this.multiSplitPane == null )
{
this.initialized = false;
this.multiSplitPane = multiSplitPane;
this.multiSplitPane.addPropertyChangeListener ( this );
for ( final ComponentListener listener : listeners.getListeners ( ComponentListener.class ) )
{
this.multiSplitPane.addComponentListener ( listener );
}
if ( CollectionUtils.notEmpty ( views ) )
{
this.views.addAll ( views );
}
if ( CollectionUtils.notEmpty ( dividers ) )
{
this.dividers.addAll ( dividers );
}
onOperation ( Operation.splitPaneModelInstalled );
}
else if ( this.multiSplitPane == multiSplitPane )
{
throw new IllegalStateException ( "This MultiSplitPaneModel is already installed in specified WebMultiSplitPane" );
}
else
{
throw new IllegalStateException ( "MultiSplitPaneModel can only be installed into single WebMultiSplitPane at a time" );
}
}
@Override
public void uninstall ( @NotNull final WebMultiSplitPane multiSplitPane )
{
if ( this.multiSplitPane != null && this.multiSplitPane == multiSplitPane )
{
// Informing about operation
onOperation ( Operation.splitPaneModelUninstalled );
// Clearing data
this.views.clear ();
this.dividers.clear ();
for ( final ComponentListener listener : listeners.getListeners ( ComponentListener.class ) )
{
this.multiSplitPane.removeComponentListener ( listener );
}
this.multiSplitPane.removePropertyChangeListener ( this );
this.multiSplitPane = null;
this.initialized = false;
}
else if ( this.multiSplitPane == null )
{
throw new IllegalStateException ( "This MultiSplitPaneModel is not yet installed in any WebMultiSplitPane" );
}
else
{
throw new IllegalStateException ( "This MultiSplitPaneModel is installed in different WebMultiSplitPane" );
}
}
@Nonnull
private static WindowStateAdapter getAdapter(@Nonnull Window window) {
for (ComponentListener listener : window.getComponentListeners()) {
if (listener instanceof WindowStateAdapter) {
return (WindowStateAdapter)listener;
}
}
return new WindowStateAdapter(window);
}
private static FrameState findFrameState(@Nonnull Component component) {
for (ComponentListener listener : component.getComponentListeners()) {
if (listener instanceof FrameState) {
return (FrameState)listener;
}
}
return null;
}
public ExpandableSupport(@Nonnull Source source, Function<? super String, String> onShow, Function<? super String, String> onHide) {
this.source = source;
this.onShow = onShow != null ? onShow : Function.ID;
this.onHide = onHide != null ? onHide : Function.ID;
source.putClientProperty(Expandable.class, this);
source.addAncestorListener(create(AncestorListener.class, this, "collapse"));
source.addComponentListener(create(ComponentListener.class, this, "collapse"));
}
public void addTransformListener( ComponentListener transformListener ) {
}
/** Overridden to do nothing */
public void addComponentListener(ComponentListener l) {
}
/** Overridden to do nothing */
public void addComponentListener(ComponentListener l) {
}
public @Override void propertyChange(PropertyChangeEvent evt) {
String propName = evt.getPropertyName();
if ("document".equals(propName)) { // NOI18N
BaseDocument newDoc = (evt.getNewValue() instanceof BaseDocument)
? (BaseDocument)evt.getNewValue() : null;
modelChanged(listenDoc, newDoc);
} else if (EditorUI.OVERWRITE_MODE_PROPERTY.equals(propName)) {
Boolean b = (Boolean)evt.getNewValue();
overwriteMode = (b != null) ? b.booleanValue() : false;
updateType();
} else if ("ancestor".equals(propName) && evt.getSource() == component) { // NOI18N
// The following code ensures that when the width of the line views
// gets computed on background after the file gets opened
// (so the horizontal scrollbar gets added after several seconds
// for larger files) that the suddenly added horizontal scrollbar
// will not hide the caret laying on the last line of the viewport.
// A component listener gets installed into horizontal scrollbar
// and if it's fired the caret's bounds will be checked whether
// they intersect with the horizontal scrollbar
// and if so the view will be scrolled.
Container parent = component.getParent();
if (parent instanceof JViewport) {
parent = parent.getParent(); // parent of viewport
if (parent instanceof JScrollPane) {
JScrollPane scrollPane = (JScrollPane)parent;
JScrollBar hScrollBar = scrollPane.getHorizontalScrollBar();
if (hScrollBar != null) {
// Add weak listener so that editor pane could be removed
// from scrollpane without being held by scrollbar
hScrollBar.addComponentListener(
(ComponentListener)WeakListeners.create(
ComponentListener.class, listenerImpl, hScrollBar));
}
}
}
} else if ("enabled".equals(propName)) {
Boolean enabled = (Boolean) evt.getNewValue();
if(component.isFocusOwner()) {
if(enabled == Boolean.TRUE) {
if(component.isEditable()) {
setVisible(true);
}
setSelectionVisible(true);
} else {
setVisible(false);
setSelectionVisible(false);
}
}
} else if (RECTANGULAR_SELECTION_PROPERTY.equals(propName)) {
boolean origRectangularSelection = rectangularSelection;
rectangularSelection = Boolean.TRUE.equals(component.getClientProperty(RECTANGULAR_SELECTION_PROPERTY));
if (rectangularSelection != origRectangularSelection) {
if (rectangularSelection) {
setRectangularSelectionToDotAndMark();
RectangularSelectionTransferHandler.install(component);
} else { // No rectangular selection
RectangularSelectionTransferHandler.uninstall(component);
}
fireStateChanged();
}
}
}
public @Override void propertyChange(PropertyChangeEvent evt) {
String propName = evt.getPropertyName();
JTextComponent c = component;
if ("document".equals(propName)) { // NOI18N
if (c != null) {
modelChanged(activeDoc, c.getDocument());
}
} else if (EditorUtilities.CARET_OVERWRITE_MODE_PROPERTY.equals(propName)) {
Boolean b = (Boolean) evt.getNewValue();
overwriteMode = (b != null) ? b : false;
updateOverwriteModeLayer(true);
updateType();
} else if ("ancestor".equals(propName) && evt.getSource() == component) { // NOI18N
// The following code ensures that when the width of the line views
// gets computed on background after the file gets opened
// (so the horizontal scrollbar gets added after several seconds
// for larger files) that the suddenly added horizontal scrollbar
// will not hide the caret laying on the last line of the viewport.
// A component listener gets installed into horizontal scrollbar
// and if it's fired the caret's bounds will be checked whether
// they intersect with the horizontal scrollbar
// and if so the view will be scrolled.
final JViewport viewport = getViewport();
if (viewport != null) {
Component parent = viewport.getParent();
if (parent instanceof JScrollPane) {
JScrollPane scrollPane = (JScrollPane) parent;
JScrollBar hScrollBar = scrollPane.getHorizontalScrollBar();
if (hScrollBar != null) {
// Add weak listener so that editor pane could be removed
// from scrollpane without being held by scrollbar
hScrollBar.addComponentListener(
(ComponentListener) WeakListeners.create(
ComponentListener.class, listenerImpl, hScrollBar));
}
}
}
} else if ("enabled".equals(propName)) {
Boolean enabled = (Boolean) evt.getNewValue();
if (component.isFocusOwner()) {
if (enabled == Boolean.TRUE) {
if (component.isEditable()) {
setVisible(true);
}
setSelectionVisible(true);
} else {
setVisible(false);
setSelectionVisible(false);
}
}
} else if (RECTANGULAR_SELECTION_PROPERTY.equals(propName)) {
boolean origRectangularSelection = rectangularSelection;
rectangularSelection = Boolean.TRUE.equals(component.getClientProperty(RECTANGULAR_SELECTION_PROPERTY));
if (rectangularSelection != origRectangularSelection) {
if (rectangularSelection) {
setRectangularSelectionToDotAndMark();
// RectangularSelectionTransferHandler.install(component);
} else { // No rectangular selection
// RectangularSelectionTransferHandler.uninstall(component);
}
fireStateChanged(null);
}
}
}
@Override
public Popup getPopup(Component owner, Component contents, int x, int y)
throws IllegalArgumentException
{
Popup popup = super.getPopup(owner, contents, x, y);
// 比较安全的hack方式
Object obj = SwingUtilities.getWindowAncestor(contents);
if (obj instanceof JWindow)
{
JWindow window = (JWindow) obj;
// 承载内容的窗体透明
window.setBackground(UIManager.getColor(LuckGlobalBundle.TRANSLUCENT_COLOR));
((JComponent) window.getContentPane()).setOpaque(false);
JdkVersion version = JdkVersion.getSingleton();
boolean isCompatible = (version.getMajor() <= 1 && version.getMinor() < 8);
if (contents instanceof JPopupMenu && isCompatible)
{
boolean isFound = false;
for (ComponentListener listener : window.getComponentListeners())
{
if(listener instanceof LuckPopupComponentListener)
{
isFound = true;
break;
}
}
if(!isFound)
{
window.addComponentListener(new LuckPopupComponentListener());
}
}
}
return popup;
}
/**
* Create a component listener responsible for initializing the
* contentDisplayer component when the tabbed container is shown
*/
protected ComponentListener createComponentListener() {
return new ContainerComponentListener();
}
/**
* Adds divider listener.
*
* @param listener divider listener to add
*/
public void addDividerListener ( final ComponentListener listener )
{
getUI ().getDivider ().addComponentListener ( listener );
}
/**
* Removes divider listener.
*
* @param listener divider listener to remove
*/
public void removeDividerListener ( final ComponentListener listener )
{
getUI ().getDivider ().removeComponentListener ( listener );
}