我需要创建一个应用程序,我需要从单选按钮获取用户输入,然后在不同的类中使用选定的文件名。我不知道如何实现这个,因为每次我尝试放置 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;
}
*/
}
}
最佳答案
显然,只有当特定单选按钮收到单击事件时才会设置 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;
}
关于java - 需要从 JFrame 中的单选按钮获取输入,并在另一个类中使用选定的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11565490/