AbstractButton: addActionListener(ActionListener l)
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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 Main extends JFrame {
public static final String FontName[] = { "Serif", "SansSerif", "Courier" };
private Font[] fonts = new Font[FontName.length];
protected JMenuItem[] fontMenus;
public Main() {
super();
setSize(450, 350);
for (int k = 0; k < FontName.length; k++)
fonts[k] = new Font(FontName[k], Font.PLAIN, 12);
JMenuBar menuBar = createMenuBar();
setJMenuBar(menuBar);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
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 Main();
}
}
Related examples in the same category