单击JLayeredPane

时间:2015-06-20 19:59:27

标签: java swing jlayeredpane

我有一个在不同图层上有两个面板(panel1和panel2)的layeredPane。在panel2中是一个文本字段。当panel1通过单击按钮放在panel2上方时,panel1与panel2下的textfield一起消失。但是,当我用鼠标点击文本字段所在的位置时,它会重新出现。这不应该发生!到目前为止,我发现的唯一解决方案是当panel1放在它上面时,使panel2中的文本字段不可见。但是这种解决方案并不令人满意,因为如果不同面板中有更多组件,这可能会变得复杂。我怎样才能优雅地解决这个问题?

我创建了一个可运行的示例来显示此行为:

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;

public class LayeredPaneTest2 extends javax.swing.JFrame {
    private final JButton button;
    private JLayeredPane layeredPane;
    private JPanel panel1;
    private JPanel panel2;
    private final JTextField textField;

    public LayeredPaneTest2() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new FlowLayout());

        layeredPane = new JLayeredPane();
        panel1 = new JPanel();
        panel2 = new JPanel();
        textField = new JTextField();
        button = new JButton();

        // Config components.
        button.setText("Change Layers");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                layeredPane.setLayer(panel1, 1);
                layeredPane.setLayer(panel2, 0);
            }
        });
        textField.setText("test");
        layeredPane.setPreferredSize(new Dimension(300, 300));
        panel1.setBounds(0, 0, 300, 300);
        panel2.setBounds(0, 0, 300, 300);

        // Add components.
        panel2.add(textField);
        layeredPane.add(panel1);
        layeredPane.add(panel2);
        layeredPane.setLayer(panel1, 0);
        layeredPane.setLayer(panel2, 1);
        add(layeredPane);
        add(button);

        pack();
    }                                                           

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LayeredPaneTest2().setVisible(true);
            }
        });
    }
}

感谢您的帮助!

0 个答案:

没有答案