Advertisement
thenewboston

Java Programming Tutorial - 66, 67 - JRadioButton

Aug 22nd, 2014
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.99 KB | None | 0 0
  1. import java.awt.FlowLayout;
  2. import java.awt.Font;
  3. import java.awt.event.ItemEvent;
  4. import java.awt.event.ItemListener;
  5. import javax.swing.JFrame;
  6. import javax.swing.JTextField;
  7. import javax.swing.JRadioButton;
  8. import javax.swing.ButtonGroup;
  9.  
  10. class RadioButtons {
  11.    public static void main(String args[ ]) {
  12.       Gui gui = new Gui();
  13.       gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  14.       gui.setSize(320, 100);
  15.       gui.setVisible(true);
  16.    }
  17. }
  18.  
  19. class Gui extends JFrame {
  20.    private JTextField text;
  21.    private JRadioButton plain, bold, italic, boldItalic;
  22.    private Font plainFont, boldFont, italicFont, boldItalicFont;
  23.  
  24.    Gui() {
  25.       super("My radio buttons");
  26.       setLayout(new FlowLayout());
  27.  
  28.       plainFont = new Font("Serif", Font.PLAIN, 14);
  29.       boldFont = new Font("Serif", Font.BOLD, 14);
  30.       italicFont = new Font("Serif", Font.ITALIC, 14);
  31.       boldItalicFont = new Font("Serif", Font.BOLD + Font.ITALIC, 14);
  32.      
  33.       text = new JTextField("This my super awesome sentence.", 23);
  34.       text.setFont(plainFont);
  35.       plain = new JRadioButton("Plain", true);
  36.       bold = new JRadioButton("Bold", false);
  37.       italic = new JRadioButton("Italic", false);
  38.       boldItalic = new JRadioButton("Bold and italic", false);
  39.       add(text);
  40.       add(plain);
  41.       add(bold);
  42.       add(italic);
  43.       add(boldItalic);
  44.      
  45.       ButtonGroup gr = new ButtonGroup();
  46.       gr.add(plain);
  47.       gr.add(bold);
  48.       gr.add(italic);
  49.       gr.add(boldItalic);
  50.      
  51.       plain.addItemListener(new handler(plainFont));
  52.       bold.addItemListener(new handler(boldFont));
  53.       italic.addItemListener(new handler(italicFont));
  54.       boldItalic.addItemListener(new handler(boldItalicFont));
  55.    }
  56.    
  57.    private class handler implements ItemListener {
  58.       Font font;
  59.      
  60.       handler(Font f) {
  61.          font = f;
  62.       }
  63.      
  64.       public void itemStateChanged(ItemEvent event) {
  65.          text.setFont(font);  
  66.       }
  67.    }
  68.    
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement