我需要创建一个应用程序,我需要从单选按钮获取用户输入,然后在不同的类中使用选定的文件名。我不确定如何实现这一点,因为每次我尝试放置 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;
}
*/
}
}