Tạo menu trong Java-Swing – Ôn Tập 5

I. Giao diện

II. Viết code


package Menu;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class FrameMenu extends JFrame implements ActionListener{
JMenuBar jmnubar;
JMenu jmnuFile;
JMenuItem jmnuiNew,jmnuiOpen,jmnuiExit;

public FrameMenu() {
setLayout(new BorderLayout());
setSize(300,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);

jmnubar=new JMenuBar();

jmnuFile=new JMenu("File");

jmnuiNew=new JMenuItem("New");
jmnuiNew.setAccelerator(KeyStroke.getKeyStroke("ctrl N"));
jmnuiOpen=new JMenuItem("Open");
jmnuiOpen.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));

jmnuiExit=new JMenuItem("Exit");
jmnuiExit.setAccelerator(KeyStroke.getKeyStroke("ctrl E"));



jmnuFile.add(jmnuiNew);
jmnuFile.add(jmnuiOpen);
jmnuFile.addSeparator();
jmnuFile.add(jmnuiExit);

jmnuFile.setMnemonic('F');


jmnubar.add(jmnuFile);


add(jmnubar,BorderLayout.NORTH);

jmnuiOpen.addActionListener(this);
jmnuiNew.addActionListener(this);
jmnuiExit.addActionListener(this);


setVisible(true);
}
public static void main(String[] args) {
new FrameMenu();
}

@Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==jmnuiOpen)
{
JOptionPane.showMessageDialog(null,"Open");
}
else if(ae.getSource()==jmnuiNew)
{
JOptionPane.showMessageDialog(null,"New");
}
else if(ae.getSource()==jmnuiExit)
{
JOptionPane.showMessageDialog(null,"Exit");
}
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s