【问题标题】:Getting a variable value from a java action listener?从java动作监听器获取变量值?
【发布时间】:2015-04-11 07:47:22
【问题描述】:

抱歉这个新问题,我正在尝试为使用 JAVA 和 Swing 的简单应用程序创建一个 GUI,但我无法从外部获取在动作侦听器中生成的变量值。

public geRes() 
{
    setTitle("geRes");
    setBounds(100, 100, 272, 308);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));



    JButton btnNewButton = new JButton("igen");
    btnNewButton.addMouseListener(new MouseAdapter() 
    {

        @Override
        public void mouseClicked(MouseEvent e) 
        {
              JFileChooser fc = new JFileChooser();
              fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
              fc.showOpenDialog(fc.getParent());
              fc.getName();
        }
    });             
    btnNewButton.setToolTipText("Selec");
    getContentPane().add(btnNewButton);

    JButton btnCivos = new JButton("smbinar");
    btnCivos.addMouseListener(new MouseAdapter() 
    {
        @Override
        public void mouseClicked(MouseEvent e) 
        {
                File dir = new File(); // I want to use fc.getName() as argument there

我想在另一个按钮内从第二种方法访问 fc.getName()。有什么建议么?提前致谢!

【问题讨论】:

  • 你不应该使用MouseListener,而是在JButton上使用ActionListener
  • 为什么会更好?
  • 因为按钮可以通过其他方式触发,只需单击鼠标即可。根据 L&F,有时也可以通过按 Enter 来触发按钮,或者如果有焦点则按空格键。如果设置了助记符,也可以和ALT+Mnemonic_char组合使用。
  • 好的,谢谢你的建议,我试试看。

标签: java swing variables parameter-passing


【解决方案1】:

将您的 JFileChooser 设为全局变量,以便您可以从其他方法调用它。

在方法外初始化

JFileChooser fc;

你可以把它放在这里:

public geRes() 
{
    JFileChooser fc;
    setTitle("geRes");
    ...

那么当你使用 JFileChooser 时,它会是这样的

fc = new JFileChooser();
          fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
          ...

然后,您现在可以从其他方法调用 JFileChooser。

JButton btnCivos = new JButton("smbinar");
btnCivos.addMouseListener(new MouseAdapter() 
{
    @Override
    public void mouseClicked(MouseEvent e) 
    {
       //you can now get the value of fc.getName()

【讨论】:

  • 感谢您的建议,我试过了,但是当我尝试使用它时,我在这一行得到一个空指针异常 File dir = new File(fc.getName());此外,我只能使用 final final JFileChooser fc = new JFileChooser(); 来定义它。其余的工作,但它似乎没有存储第一个方法的值。
  • 没关系,这个解决方案工作得很好,问题是我使用了错误的方法作为参数, fc.getSelectedFile().getAbsolutePath().toString() 工作而不是 fc.getName( ) 因为需要完整路径。再次感谢!!
猜你喜欢
  • 1970-01-01
  • 2012-04-29
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多