如何将只读模式设置为JPanel

时间:2014-01-07 13:18:28

标签: java swing

我有2个JPanels(LeftPanel和RightPanel)。

RightPanel有4个JRadioButtons,其中一个是通过设置setSelected(true)来选择的。

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

你能帮我解决一下这个问题吗?

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

示例代码会有所帮助。

2 个答案:

答案 0 :(得分:3)

我建议你看看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();
        }



    }
}

答案 1 :(得分:2)

最简单的选择是对setEnabled(false);内的所有组件执行JPanel。您还可以将setEditable(false);用于JTextFieldJTextAreaJEditorPanel等文字组件。