潇潇雨雨
使用JDesktopPane(或它的超类JLayeredPane)作为其内容,添加到窗格中。在这里,您可以看到一种让组件重叠的好方法,并在光标停留在其上时弹出:import javax.swing.*;import java.awt.*;import java.awt.event.*;public class ShiftedStackPanel extends JPanel implements MouseListener, ActionListener { private static final long serialVersionUID = 1988454751139668485L; private int layer; private JDesktopPane desktopPane; private Timer timer; private Component currentComponent; private int layerOfCurrent; private int shiftDivision; public ShiftedStackPanel() { this(4); } public ShiftedStackPanel(int shift) { shiftDivision = shift; setLayout(new BorderLayout(0, 0)); desktopPane = new JDesktopPane(); desktopPane.setBackground(SystemColor.window); super.add(desktopPane); timer = new Timer(1000, this); timer.setRepeats(false); } public Component add(Component c) { Dimension dim = c.getPreferredSize(); c.setBounds( (desktopPane.getComponentCount() * (dim.width / shiftDivision)), 0, dim.width, dim.height); desktopPane.add(c, new Integer(++layer)); c.addMouseListener(this); return c; } public void remove(Component c) { throw new IllegalArgumentException( "Removal of component, not yet supported."); // FIXME: allow removal, and shift all latter comps, to left } public void removeAll() { desktopPane.removeAll(); } public static void main(String[] args) { JFrame f = new JFrame("JFrame Wrapper"); ShiftedStackPanel p; f.setContentPane(p = new ShiftedStackPanel(4)); p.add(new JTextField("ABCDEFGHI")); p.add(new JTextField("DEFGHIJKL")); p.add(new JTextField("GHIJKLMNO")); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); f.setMinimumSize(new Dimension(400, 200)); f.setLocationRelativeTo(null); } @Override public void mouseClicked(MouseEvent evt) { if (currentComponent != null) { Component c = (Component) evt.getSource(); currentComponent = c; layerOfCurrent = desktopPane.getLayer(c); desktopPane.remove(c); desktopPane.add(c, new Integer(100)); } } @Override public void mouseEntered(MouseEvent evt) { timer.start(); Component c = (Component) evt.getSource(); currentComponent = c; layerOfCurrent = desktopPane.getLayer(c); } @Override public void mouseExited(MouseEvent evt) { if ((currentComponent != null) && currentComponent == evt.getSource()) { desktopPane.remove(currentComponent); desktopPane.add(currentComponent, new Integer(layerOfCurrent)); currentComponent = null; timer.stop(); } } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void actionPerformed(ActionEvent arg0) { desktopPane.remove(currentComponent); desktopPane.add(currentComponent, new Integer(100)); }}在使用需要重点关注但应与JLabel和配合使用的组件时,仍然存在一些问题JPanel。