import javax.swing.*;
import javax.swing.filechooser.*;
import java.awt.event.*;
import java.awt.*;
public class JFrameEx extends JFrame {
private JLabel imageLabel = new JLabel();
public JFrameEx(){
setTitle("Menu 만들기 예제");
Container c = getContentPane();
c.add(imageLabel);
createMenu();
setSize(500, 500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void createMenu() {
JMenuBar mb = new JMenuBar();
JMenu screenMenu = new JMenu("Screen");
screenMenu.add(new JMenuItem("Load"));
screenMenu.add(new JMenuItem("Hide"));
screenMenu.add(new JMenuItem("ReShow"));
screenMenu.addSeparator();
screenMenu.add(new JMenuItem("Exit"));
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open");
fileMenu.add(openItem);
mb.add(fileMenu);
openItem.addActionListener(new OpenActionListener());
mb.add(screenMenu);
mb.add(new JMenu("Edit"));
mb.add(new JMenu("Source"));
mb.add(new JMenu("Project"));
mb.add(new JMenu("Run"));
setJMenuBar(mb);
}
class OpenActionListener implements ActionListener{
private JFileChooser chooser;
public OpenActionListener(){
chooser = new JFileChooser();
}
@Override
public void actionPerformed(ActionEvent e) {
FileNameExtensionFilter filter
= new FileNameExtensionFilter("JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int ret = chooser.showOpenDialog(null);
if(ret !=JFileChooser.APPROVE_OPTION){
JOptionPane.showMessageDialog(null, "파일을 선택하지 않았습니다.",
"경고", JOptionPane.WARNING_MESSAGE);
return;
}
String filePath = chooser.getSelectedFile().getPath();
imageLabel.setIcon(new ImageIcon(filePath));
pack();
}
}
public static void main(String[] args) {
new JFrameEx();
}
}