来自MenuItem / MenuBar和Sound Player的Java Exit按钮

时间:2012-01-03 02:43:54

标签: java swing jframe jbutton actionlistener

好的,我在视频/学校的java学习中作为初学者编写了这段代码,我得到了一些问题。

1 => 为什么文件>退出按钮不起作用并且有一个小箭头,好像有一些孩子一样?大退出按钮使用相同的功能。 我从这里受到启发:http://www.youtube.com/watch?src_vid=FB_wJpIdA8k&feature=iv&annotation_id=annotation_40248&v=dwLkDGm5EBc

2 => 如何让该按钮变小?当我调整它时,它会更大。

3 => 有谁知道一个简单的声音播放器库?那么当我按下那个按钮播放声音时?我已尝试过一些网络示例,例如http://www.developer.com/java/other/article.php/2173111/Java-Sound-Playing-Back-Audio-Files-using-Java.htm,并且不知道如何使其变得简单,并且像SoundPlay(sound.au)一样在任何地方使用它;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class form4 
{
    public static void main(String[] args)
    {
        // Frame
        JFrame frame = new JFrame("Menu");
        frame.setSize(300,300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Just create menubar
        JMenuBar menubar = new JMenuBar();
        frame.setJMenuBar(menubar);

        // Add an JMenu
        JMenu file = new JMenu("File");
        menubar.add(file);
        // Add an JMenuItem
        JMenuItem exit = new JMenu("Exit");
        file.add(exit);
        exit.addActionListener(new exitApp());

        // Add an JMenu
        JMenu help = new JMenu("Help");
        menubar.add(help);
        // Add an JMenuItem
        JMenuItem about = new JMenuItem("About");
        help.add(about);

        // Add an JButton
        JButton exitButton= new JButton("Exit!");
        frame.add(exitButton);
        exitButton.addActionListener(new exitApp());
        exitButton.setSize(40,40);

        frame.setVisible(true);
    }

    // Exit app
    static class exitApp implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            System.exit(0);
        }
    }
}

谢谢!

2 个答案:

答案 0 :(得分:11)

要使退出菜单有效,请使用JMenuItem:

  JMenuItem exit = new JMenuItem("Exit");
  exit.addActionListener(new exitApp());
  file.add(exit);

关于你的另一个问题,如何使按钮“更小”,你需要了解你将这个JButton添加到JFrame的contentPane,并且默认情况下contentPane使用BorderLayout。因此,以这种方式添加按钮将使其完全填满容器。为防止这种情况发生,您需要使用其他布局。请详细了解如何使用Swing Layouts:A Visual Guide to the Layout Managers

答案 1 :(得分:3)

以下是我在我的应用程序中实现它的方式,希望它有所帮助:

    menuBar = new JMenuBar();
    mainWindow.setJMenuBar(menuBar);

    mnFile = new JMenu("File");
    menuBar.add(mnFile);

    mntmClose = new JMenuItem("Close");
    mntmClose.setMnemonic(KeyEvent.VK_Q);
    mntmClose.setAccelerator(KeyStroke.getKeyStroke(
             KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
    mntmClose.setToolTipText("Exit application");
    mntmClose.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            System.exit(0);
        }

    });
    mnFile.add(mntmClose);