jcheckbox和jcombolist应用

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JPanel // implements ActionListener
{
 private JCheckBox cb1, cb2;
 private JComboBox c1;
 private JTextField t1;
 private ActionHandler h1;

 public void init() {

  setLayout(new FlowLayout());
  h1 = new ActionHandler(this);

  String[] s = { "Serif", "SansSerif", "Monospaced", "Dialog" };
  c1 = new JComboBox(s);
  c1.addActionListener(h1);
  add(c1);

  Font font = new Font(c1.getItemAt(0).toString(), Font.PLAIN, 14);
  t1 = new JTextField("Test string", 30);
  t1.setEditable(false);
  t1.setFont(font);
  add(t1);

  cb1 = new JCheckBox("Bold");
  cb1.addActionListener(h1);
  cb1.setMnemonic('b');
  add(cb1);
  cb2 = new JCheckBox("Italic");
  cb2.addActionListener(h1);
  cb2.setMnemonic('i');
  add(cb2);

 }

 public void updateFont() {
  int valBold, valItatic;
  int fontStyle = t1.getFont().getStyle();
  int fontSize = t1.getFont().getSize();
  String fontName = (String) c1.getSelectedItem();
  valBold = cb1.isSelected() ? Font.BOLD : Font.PLAIN;
  valItatic = cb2.isSelected() ? Font.ITALIC : Font.PLAIN;
  fontStyle = valBold + valItatic;
  t1.setFont(new Font(fontName, fontStyle, fontSize));
  t1.repaint();
 }

 public static void main(String args[]) {
  JFrame fr = new JFrame("Test...");
  fr.setSize(400, 200);
  fr.setLocation(400, 400);
  Test ob = new Test();
  ob.init();
  fr.add(ob, BorderLayout.CENTER);
  fr.setVisible(true);

 }
}

class ActionHandler implements ActionListener {
 private Test ttf;

 public ActionHandler(Test t) {
  ttf = t;
 }

 public void actionPerformed(ActionEvent e) {

  ttf.updateFont();
 }

}

你可能感兴趣的:(jcheckbox和jcombolist应用)