radiodemo.java

来自「金旭亮的java教案」· Java 代码 · 共 75 行

JAVA
75
字号
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class RadioDemo {

    static JFrame jframe = new JFrame("Example");

    public static void setupFrame() {
        jframe.setSize(400,130);
        jframe.getContentPane().setLayout( new FlowLayout() );

        WindowListener l = new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);}
        };
        jframe.addWindowListener(l);
    }

    static String pieString = "pie";
    static String cakeString = "cake";
    static String iceString = "ice";

    public static void main(String[] args) {
        setupFrame();
    final JLabel piclabel = new JLabel(new ImageIcon( pieString + ".gif"));

    /** Listens to the radio buttons. */
    class RadioListener implements ActionListener { 
        public void actionPerformed(ActionEvent e) {
            piclabel.setIcon(new ImageIcon( e.getActionCommand() 
                                          + ".gif"));
        }
    }


        JRadioButton pieButton = new JRadioButton(pieString);
        pieButton.setMnemonic('b');
        pieButton.setActionCommand(pieString);
        pieButton.setSelected(true);

        JRadioButton cakeButton = new JRadioButton(cakeString);
        JRadioButton iceButton = new JRadioButton(iceString);

        // Group the radio buttons.
        ButtonGroup group = new ButtonGroup();
        group.add(pieButton);
        group.add(cakeButton);
        group.add(iceButton);

        // Register a listener for the radio buttons.
        RadioListener myListener = new RadioListener();
        pieButton.addActionListener(myListener);
        cakeButton.addActionListener(myListener);
        iceButton.addActionListener(myListener);


        // Put the radio buttons in a column in a panel
        JPanel radioPanel = new JPanel();
        radioPanel.setLayout(new GridLayout(0, 1));
        radioPanel.add(pieButton);
        radioPanel.add(cakeButton);
        radioPanel.add(iceButton);

        // setLayout(new BorderLayout());

        jframe.getContentPane().add(radioPanel);
        jframe.getContentPane().add(piclabel);
        jframe.setLocation(300,300);
        jframe.setVisible(true);

    }
}


⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?