从Java动作侦听器获取变量值?

Asta86

很抱歉,我想使用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()。有什么建议么?提前致谢!

迪兰兹·法玛多

将您设置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()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章