0

我需要创建一个应用程序,我需要从单选按钮获取用户输入,然后在不同的类中使用选定的文件名。我不确定如何实现这一点,因为每次我尝试放置 getString() 方法在 MyAction 类中,它给了我一个空值。谢谢!!

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;

public class SelectRadioButton{

    public SelectRadioButton(){

      // Directory path here
      String path = "W:\\materials"; 

      JFrame frame = new JFrame("Material Selection");
      JPanel panel = new JPanel(new GridLayout(0, 4));
      ButtonGroup bg = new ButtonGroup();

      String files;
      File folder = new File(path);
      File[] listOfFiles = folder.listFiles(); 
      JRadioButton  first;

      for (int i = 0; i < listOfFiles.length; i++) 
      {

       if (listOfFiles[i].isFile()) 
       {
       files = listOfFiles[i].getName();
           if (files.endsWith(".mtl") || files.endsWith(".MTL"))
           {

              first = new JRadioButton(files);
              panel.add(first,BorderLayout.CENTER);
              panel.revalidate(); 

              bg.add(first);
              first.addActionListener(new MyAction);
            }
         }
      }

       frame.add(panel, BorderLayout.NORTH);
       frame.getContentPane().add(new JScrollPane(panel), BorderLayout.CENTER);
       frame.setSize(1000, 400);
       frame.setVisible(true);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }

  public class MyAction implements ActionListener{
        //String m;
      public void actionPerformed(ActionEvent e){
      String m =e.getActionCommand();
      String[] split = m.split("\\.");
      m=split[0];
      JOptionPane.showMessageDialog(null,"Your Selection is"+m+" radio button.");
   }
        /*
        public String getString(){
               return m;
        }
        */
   }
 }
4

1 回答 1

1

显然,m只有在特定单选按钮收到点击事件时才会设置该变量。
如果您不想更改太多代码,请执行以下操作:

public class MyAction implements ActionListener{
    String m;

    public MyAction(String radioButtonLabel){
        m = radioButtonLabel;
    }
    public void actionPerformed(ActionEvent e){
        JOptionPane.showMessageDialog(null,
                "Your Selection is"+m+" radio button.");
    }
    public String getString(){
        return m;
    }
}

并替换:

first.addActionListener(new MyAction());

经过:

first.addActionListener(new MyAction(files));

并改进变量的名称......这有点令人困惑!
希望能帮助到你。

更新

要获取选定的单选按钮:

public static JRadioButton getSelection(ButtonGroup group) {
    for (Enumeration e = group.getElements(); e.hasMoreElements();) {
        JRadioButton b = (JRadioButton) e.nextElement();
        if (b.getModel() == group.getSelection()) {
            return b;
        }
    }
    return null;
}
于 2012-07-19T18:04:08.827 回答