【问题标题】:Java Swing Menu Beginners AdviceJava Swing 菜单初学者建议
【发布时间】:2014-04-17 20:07:36
【问题描述】:

我刚开始学习一些 java GUI 技术,我创建了一个小程序,它有一个菜单栏、一个菜单以及该菜单中的一个项目。现在我想做的是实现一个文件选择器,这样当菜单中的项目被选中时,文件选择器就会被执行。问题是我创建的文件选择器在另一个类中。单击菜单中的项目时,是否有任何可能的方法来启动我的文件选择器的类? 这是我的代码

  public class menu {


  public static void main(String[] args){


//to menu
JFrame frame = new JFrame("Menu");
frame.setVisible(true);
frame.setSize(600,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


JMenuBar bar = new JMenuBar();
frame.setJMenuBar(bar);
JMenu search = new JMenu("Browse");
bar.add(search);
final JMenuItem songstoplay = new JMenuItem("Browse Songs To Play");
search.add(songstoplay);



//to outline
  final Container content = frame.getContentPane();
   content.setLayout(new GridLayout(3, 1));
   JLabel text = new JLabel("My first iteration", JLabel.CENTER);
   text.setVerticalAlignment(JLabel.TOP);
   text.setFont(new Font("Serif", Font.PLAIN, 30));
   content.add(text);


 JLabel text2 = new JLabel();


 text2.setText("List of drives connected: C:/");
 text2.setFont(new Font("Serif", Font.PLAIN, 20));
  text2.setVerticalAlignment(JLabel.TOP);
 content.add(text2);


}
}

【问题讨论】:

  • 你试过调用文件选择器构造函数吗?
  • 你为什么不试试JFileChooser
  • 您好,感谢您的回复。但这就是我要问的如何在选择菜单项时使用文件选择器?

标签: java swing menu actionlistener


【解决方案1】:

如果你想使用 JFileChooser,你必须在你的菜单项上添加一个事件监听器。最好你看看这个:http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

或上例中代码的直接链接: http://docs.oracle.com/javase/tutorial/uiswing/examples/components/FileChooserDemoProject/src/components/FileChooserDemo.java

【讨论】:

  • 嘿,感谢您的建议,我通过添加 actionlistener 解决了我遇到的问题:D
猜你喜欢
  • 1970-01-01
  • 2016-09-23
  • 2014-08-17
  • 2018-10-07
  • 2011-04-19
  • 2014-11-12
  • 2022-11-27
  • 2011-11-27
  • 1970-01-01
相关资源
最近更新 更多