JRadio按钮和图像

时间:2018-06-26 17:13:01

标签: java

我目前正在自学Java语言,现在通过使用eclpise,JFrame和window builder讲授GUI。我用两个单选按钮创建了一个GUI,在它们上面有两个标签,每个标签上都带有图片。当我单击左侧的单选按钮时,我希望左侧标签显示图像,而右侧标签则不显示任何内容。然后,当我单击右侧的单选按钮时,我希望右侧的标签显示图像。我被困住了,我尝试了一些不同的事情,并希望获得一些指导。这是到目前为止的一些代码

JLabel lblLeft = new JLabel("");
//This is to retrieve your image and put it in the GUI
Image imgL = new ImageIcon(getClass().getResource    ("schlange.gif")).getImage();  
    lblLeft.setIcon(new ImageIcon(imgL));
    lblLeft.setPreferredSize(new Dimension(290, 26));
    lblLeft.setOpaque(true);
    lblLeft.setBackground(Color.BLACK);
    contentPane.add(lblLeft, BorderLayout.WEST);

    JLabel lblRight = new JLabel("");
    //This is to retrieve your image and put it in the GUI 
    Image imgR = new ImageIcon(getClass().getResource("schlange.gif")).getImage();  
    lblRight.setIcon(new ImageIcon(imgR));
    lblRight.setPreferredSize(new Dimension(290, 26));
    lblRight.setBackground(Color.BLACK);
    lblRight.setOpaque(true);
    contentPane.add(lblRight, BorderLayout.EAST);

    //To get this code to come up you click on your radio button then right click on it go down to add event
    //then go to item and itemStateChanged 
    JRadioButton rdbtnLeft = new JRadioButton("Left");
    rdbtnLeft.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent arg0) 
        {
            lblLeft.setIcon((Icon) imgL);
        }
    });


    buttonGroupLeftRight.add(rdbtnLeft);
    rdbtnLeft.setFont(new Font("Tahoma", Font.PLAIN, 12));
    panel.add(rdbtnLeft);

    JRadioButton rdbtnRight = new JRadioButton("Right");
    buttonGroupLeftRight.add(rdbtnRight);
    rdbtnRight.setToolTipText("                                ");
    rdbtnRight.setFont(new Font("Tahoma", Font.PLAIN, 12));
    panel.add(rdbtnRight);

1 个答案:

答案 0 :(得分:0)

将每个图像包装在自己的JPanel中(leftImagePanel和rightImagePanel)。

然后您可以使用:

leftImagePanel.setVisible(true);
rightImagePanel.setVisible(false);

leftImagePanel.setVisible(false);
rightImagePanel.setVisible(true);

在任何需要的地方。