Recently, when doing a project, you need to deal with clicking on a JLabel implementation to remove this JLabel feature. Recently tortured a little time to check the API. 2 methods were found to implement this function.
Remove
Remove (Component comp)
-
removes the specified component from the container. If
comp
not
rootPane
, the call is forwarded to the
contentPane
. If
comp
it is not
JFrame
or
contentPane
a child, no action is taken.
Repaint
Repaint (long time, int x, int y, int width, int height)
-
-
time
redraws The specified rectangular area of this component within milliseconds.
-
-
the code to implement this function is as follows:
-
1 PackageQq.client.tools;2 ImportJava.awt.Frame;3 Importjava.awt.event.MouseEvent;4 ImportJava.awt.event.MouseListener;5 ImportJavax.swing.JLabel;6 /**7 * Realize click on a jlabel to delete a jlabel small function8 * @authorAdministrator9 *Ten */ One Public classTest { A - Public Static voidMain (string[] args) { - the FinalFrame frame =NewFrame ();//Create Window -Frame.setsize (800, 600); -Frame.setlayout (NULL); - +JLabel BTN =NULL;//Monitor -JLabel b=NULL; +BTN =NewJLabel ("btn");//Create BTN, add monitoring ABtn.addmouselistener (NewMouseListener () { at @Override - Public voidmousereleased (MouseEvent e) { - //TODO auto-generated Method Stub - - } - in @Override - Public voidmousepressed (MouseEvent e) { to //TODO auto-generated Method Stub + - } the * @Override $ Public voidmouseexited (MouseEvent e) {Panax Notoginseng //TODO auto-generated Method Stub - the } + A @Override the Public voidmouseentered (MouseEvent e) { + //TODO auto-generated Method Stub - $ } $ - @Override - Public voidmouseclicked (MouseEvent e) { the //TODO auto-generated Method Stub - if(E.getclickcount () ==1) {//Click ThingsWuyiJLabel sourcebtn = (JLabel) e.getsource ();//get the Event source object (click Btn) the Frame.remove (SOURCEBTN); - frame.repaint (); Wu } - } About }); $ Frame.add (BTN); -Btn.setbounds (50, 50, 50, 50); -Frame.setvisible (true); - } A}
The entire function is realized. Be careful not to add frame.repaint (); This code will not be refreshed in time. You need to minimize the window or maximize (I think the refresh requires a user action to refresh) window to automatically refresh. Add Frame.repaint (); it will be refreshed in time.
-
-
-
-
Java implementation Click a control to implement a method to delete a control