JMenu menu = new JMenu("File"); JCheckBoxMenuItem chkMenu = new JCheckBoxMenuItem("CheckBox Item"); menu.add(chkMenu);
package com.java.myapp; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.KeyStroke; public class MyForm extends JFrame { /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { MyForm frame = new MyForm(); frame.setVisible(true); } }); } /** * Create the frame. */ public MyForm() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 362, 249); setTitle("ThaiCreate.Com Java GUI Tutorial"); getContentPane().setLayout(null); // Menu Bar JMenuBar menuBar=new JMenuBar(); JMenu menu = new JMenu("File"); menu.setMnemonic(KeyEvent.VK_F); // Open ImageIcon openExit = new ImageIcon(getClass().getResource("open.gif")); JMenuItem menuOpen = new JMenuItem("Open",openExit); menuOpen.setMnemonic(KeyEvent.VK_O); menuOpen.setToolTipText("Open Application"); menuOpen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { JOptionPane.showMessageDialog(null, "Open Command"); } }); // CheckBox final JCheckBoxMenuItem chkMenu = new JCheckBoxMenuItem("CheckBox Item"); chkMenu.setState(false); chkMenu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (chkMenu.isVisible()) { JOptionPane.showMessageDialog(null, "Checkbox is Checked"); } else { JOptionPane.showMessageDialog(null, "Checkbox is UnChecked"); } } }); // Exit ImageIcon iconExit = new ImageIcon(getClass().getResource("exit.gif")); JMenuItem menuExit = new JMenuItem("Exit",iconExit); menuExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK)); menuExit.setToolTipText("Exit Application"); menuExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.exit(0); } }); // Create menu menu.add(menuOpen); // Open menu.addSeparator(); menu.add(chkMenu); // Checkbox menu.addSeparator(); menu.add(menuExit); // Exit menuBar.add(menu); setJMenuBar(menuBar); } }
ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท