Tóm Tắt
Đặc điểm cơ bản của JRadioButton :
– Chỉ cho phép chọn 1 từ 1 nhóm các lựa chọn
Code minh họa sử dụng JRadioButton:
Ví dụ sau minh họa việc hiển thị hình ảnh tương ứng với lựa chọn từ RadioButton ( Lưu ý : Bạn cần có các ảnh hanoi.jpg,hue.jpg,saigon.jpg đặt trong thư mục code )
package quyetdv.javaswing.demo; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JRadioButtonDemo extends JPanel { static JFrame frame; JLabel jlbPicture; RadioListener myListener = null; public JRadioButtonDemo() { // Create the radio buttons and assign Keyboard shortcuts using // Mnemonics JRadioButton jrbNumbers = new JRadioButton("HaNoi"); jrbNumbers.setMnemonic(KeyEvent.VK_N); jrbNumbers.setActionCommand("HaNoi"); jrbNumbers.setSelected(true); JRadioButton jrbAlphabets = new JRadioButton("Hue"); jrbAlphabets.setMnemonic(KeyEvent.VK_H); jrbAlphabets.setActionCommand("Hue"); JRadioButton jrbSymbols = new JRadioButton("SaiGon"); jrbSymbols.setMnemonic(KeyEvent.VK_S); jrbSymbols.setActionCommand("SaiGon"); // Group the radio buttons. ButtonGroup group = new ButtonGroup(); group.add(jrbNumbers); group.add(jrbAlphabets); group.add(jrbSymbols); // Register an action listener for the radio buttons. myListener = new RadioListener(); jrbNumbers.addActionListener(myListener); jrbAlphabets.addActionListener(myListener); jrbSymbols.addActionListener(myListener); // Set up the picture label jlbPicture = new JLabel(new ImageIcon("" + "hanoi" + ".jpg")); // Set the Default Image jlbPicture.setPreferredSize(new Dimension(177, 122)); // Put the radio buttons in a column in a panel JPanel jplRadio = new JPanel(); jplRadio.setLayout(new GridLayout(0, 1)); jplRadio.add(jrbNumbers); jplRadio.add(jrbAlphabets); jplRadio.add(jrbSymbols); setLayout(new BorderLayout()); add(jplRadio, BorderLayout.WEST); add(jlbPicture, BorderLayout.CENTER); setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); } /** Listens to the radio buttons. */ class RadioListener implements ActionListener { public void actionPerformed(ActionEvent e) { jlbPicture .setIcon(new ImageIcon("" + e.getActionCommand() + ".jpg")); } } public static void main(String s[]) { frame = new JFrame("JRadioButton Usage Demo"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.getContentPane().add(new JRadioButtonDemo(), BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } }
Kết quả :
Link download source : https://www.dropbox.com/s/uvlack8alvsxhht/DemoJavaSwing_JRadioButton.7z
Share this:
Like this:
Like
Loading…
Related