import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.ButtonGroup;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
public class SingleChoiceMenu extends JFrame {
public static final String FontName[] = { "Serif", "SansSerif", "Courier" };
private Font[] fonts;
protected JMenuItem[] fontMenus;
public SingleChoiceMenu() {
super("BasicTextEditor with JColorChooser");
setSize(450, 350);
fonts = new Font[FontName.length];
for (int k = 0; k < FontName.length; k++)
fonts[k] = new Font(FontName[k], Font.PLAIN, 12);
JMenuBar menuBar = createMenuBar();
setJMenuBar(menuBar);
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(wndCloser);
setVisible(true);
}
protected JMenuBar createMenuBar() {
final JMenuBar menuBar = new JMenuBar();
JMenu mFont = new JMenu("Font");
mFont.setMnemonic('o');
ButtonGroup group = new ButtonGroup();
fontMenus = new JMenuItem[FontName.length];
for (int k = 0; k < FontName.length; k++) {
int m = k + 1;
fontMenus[k] = new JRadioButtonMenuItem(m + " " + FontName[k]);
boolean selected = (k == 0);
fontMenus[k].setSelected(selected);
fontMenus[k].setMnemonic('1' + k);
fontMenus[k].setFont(fonts[k]);
fontMenus[k].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println(((JComponent) arg0.getSource())
.getFont());
}
});
group.add(fontMenus[k]);
mFont.add(fontMenus[k]);
}
menuBar.add(mFont);
return menuBar;
}
public static void main(String argv[]) {
new SingleChoiceMenu();
}
}
|