我有2个JPanels(LeftPanel和RightPanel)。

RightPanel具有4个JRadioButton,通过设置setSelected(true)选择其中一个。

我的要求是在只读模式下显示RightPanel。

你能帮我实现这个目标吗?

 JPanel RightPanel=new JPanel();
 RightPanel.removeMouseListener(null);


示例代码将很有帮助。

最佳答案

我建议您看一下JLayer,您可以自己使用所有事件。看一下教程How to Decorate Components with the JLayer Class。您需要Java 7+才能使用此类。

简单的例子:

import java.awt.AWTEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayer;
import javax.swing.JPanel;
import javax.swing.plaf.LayerUI;

public class Test {


    public static void main(String args []){
        JFrame frame = new JFrame();
        frame.setTitle("Test checkbox");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.add(new JLabel("Test checkbox"));
        JCheckBox checkbox = new JCheckBox();
        LayerUI<JComponent> layerUI = new MyLayerUISubclass();
        JLayer<JComponent> jlayer = new JLayer<>(checkbox, layerUI);

        panel.add (jlayer);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);

    }



    static class MyLayerUISubclass extends LayerUI<JComponent>{


        @Override
        public void installUI(JComponent c) {
            super.installUI(c);
            JLayer jlayer = (JLayer)c;
            jlayer.setLayerEventMask(
                    AWTEvent.MOUSE_EVENT_MASK |
                    AWTEvent.KEY_EVENT_MASK
                    );

        }

        @Override
        public void uninstallUI(JComponent c) {
            JLayer jlayer = (JLayer)c;
            jlayer.setLayerEventMask(0);
            super.uninstallUI(c);
        }


        @Override
        protected void processMouseEvent(MouseEvent e, JLayer l) {
            e.consume();
        }





        @Override
        protected void processKeyEvent(KeyEvent e,
                JLayer<? extends JComponent> l) {
            e.consume();
        }



    }
}

07-26 09:28