I
want to share how to CODING FOR CHECKRADIO in J2SE. You can use this code
but if you copy this code and paste in your blog/website, please insert this
link of article.
import java.awt.event.*;
import javax.swing.*;
public class CheckRadio extends JFrame {
JLabel lblTeks;
JCheckBox chkBold, chkItalic;
public CheckRadio() {
super("Check dan Radio");
JPanel radioPane = new JPanel();
ButtonGroup btnGrp = new ButtonGroup();
JRadioButton radRed = new JRadioButton("CheckBox 1");
radioPane.add(radRed);
JRadioButton radGreen = new JRadioButton("CheckBox 2");
radioPane.add(radGreen);
btnGrp.add(radRed);
btnGrp.add(radGreen);
RadioListener radListener = new RadioListener();
radRed.addActionListener(radListener);
radGreen.addActionListener(radListener);
JPanel checkPane = new JPanel();
chkBold = new JCheckBox("Bold");
checkPane.add(chkBold);
chkItalic = new JCheckBox("Italic");
checkPane.add(chkItalic);
CheckListener chkListener = new CheckListener();
chkBold.addItemListener(chkListener);
chkItalic.addItemListener(chkListener);
lblTeks = new JLabel("Pilihan", SwingConstants.CENTER);
setLayout(new GridLayout(3, 1));
add(radioPane);
add(lblTeks);
add(checkPane);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 150);
setVisible(true);
}
// Misal radio button ditangani menggunakan ActionListener
class RadioListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
lblTeks.setText(e.getActionCommand() + " dipilih");
}
}
// Misal check box ditangani menggunakan ItemListener
class CheckListener implements ItemListener {
private int valBold = Font.PLAIN;
private int valItalic = Font.PLAIN;
// Merespon event check box
public void itemStateChanged(ItemEvent e) {
if (e.getSource() == chkBold)
valBold = chkBold.isSelected() ? Font.BOLD : Font.PLAIN;
if (e.getSource() == chkItalic)
valItalic = chkItalic.isSelected() ? Font.ITALIC : Font.PLAIN;
// Menetapkan font teks
lblTeks.setFont(new Font( "Serif", valBold + valItalic, 14 ) );
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CheckRadio();
}
});
}
}
0 komentar:
Posting Komentar