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