从java操作侦听器获取变量值?

从java操作侦听器获取变量值?,java,swing,variables,parameter-passing,Java,Swing,Variables,Parameter Passing,很抱歉提出了一个新问题,我正在尝试使用JAVA和Swing为一个简单的应用程序创建GUI,但我一直在尝试从外部获取动作侦听器中生成的变量值 public geRes() { setTitle("geRes"); setBounds(100, 100, 272, 308); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); getContentPane().setLayout(new FlowLayout(FlowLa

很抱歉提出了一个新问题,我正在尝试使用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
设置为全局变量,以便您可以从另一个方法调用它

JButton btnCivos = new JButton("smbinar");
btnCivos.addMouseListener(new MouseAdapter() 
{
    @Override
    public void mouseClicked(MouseEvent e) 
    {
       //you can now get the value of fc.getName()
在方法外部初始化它

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()

您不应该在
JButton
上使用
MouseListener
,而应该在
JButton
上使用
ActionListener
为什么会更好?因为只需单击鼠标,就可以通过其他方式触发该按钮。根据L&F的不同,有时也可以通过按Enter键或空格键(如果有焦点)来触发按钮。如果设置助记符,它也可以与
ALT+mnemonic\u char
组合使用。好的,谢谢你的建议,我会试试。谢谢你的建议,我试过了,但当我尝试使用它时,我在这一行文件dir=new File(fc.getName())处出现空指针异常;另外,我只允许使用final-final JFileChooser fc=new-JFileChooser()定义它;其余部分可以工作,但它似乎没有存储第一个方法的值。没关系,这个解决方案工作得很好,问题是我使用了错误的方法作为参数,fc.getSelectedFile().getAbsolutePath().toString()可以工作,而不是fc.getName(),因为需要完整的路径。再次感谢!!