我有一个设置文件夹目录的重命名工具,但是我创建了一些JCheckBox,我希望它们能够根据选择的目录更改目录。
她是复选框的动作监听器,它编辑txt字段,使其在程序中看起来正确,但实际上并没有更改目录。
cbxBlackBerry = new JCheckBox("BlackBerry");
cbxBlackBerry.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
if(cbxBlackBerry.isSelected())
txtPrefix.setText("x-rimdevice_");
else{
txtPrefix.setText("");
}
if(cbxBlackBerry.isSelected())
txtDirectory.setText("\\RSASoftToken\\blackberry");
else{
txtDirectory.setText("");
}
}
}
); //close addActionListener
这是命令目录设置的代码
private boolean chooseDirectory(){
/* Choose the file Directory
* this will ensure that the class variable directory get the value
* only when a directory is chosen, then the button Ok will be enabled
*/
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setAcceptAllFileFilterUsed(false);
int returnval = fc.showOpenDialog(this);
if(returnval == JFileChooser.APPROVE_OPTION){
directory = fc.getSelectedFile();
btnOk.setEnabled(true);
return true;
}
return false;
}// end chooseDirectory
如何修改此代码以实际更改目录?
if(cbxBlackBerry.isSelected())
txtDirectory.setText("\\RSASoftToken\\blackberry");
else{
txtDirectory.setText("");
答案 0 :(得分:1)
您将使用ChangeListener类
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class JCheckboxApp {
public static void main(String args[]) {
JFrame frame = new JFrame("CheckBox Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JCheckBox cbxBlackBerry = new JCheckBox("BlackBerry");
final JTextField txtPrefix = new JTextField("textPrefix");
final JTextField txtDirectory = new JTextField("txtDirectory");
cbxBlackBerry.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent changeEvent) {
JCheckBox source = (JCheckBox) changeEvent.getSource();
if (source.isSelected()) {
txtPrefix.setText("x-rimdevice_");
txtDirectory.setText("\\RSASoftToken\\blackberry");
} else {
txtPrefix.setText("");
txtDirectory.setText("");
}
}
});
JPanel p = new JPanel();
p.add(txtPrefix);
p.add(txtDirectory);
p.add(cbxBlackBerry);
frame.add(p);
frame.setSize(300, 100);
frame.setVisible(true);
}
}
答案 1 :(得分:1)
你需要一个像这样的方法:
private void setDirectory(File dir) {
directory = dir;
txtDirectory.setText(dir.getAbsolutePath());
}
并且您拥有设置目录JTextField的代码,请调用此方法。例如,而不是
if(cbxBlackBerry.isSelected())
txtDirectory.setText("\\RSASoftToken\\blackberry");
else{
txtDirectory.setText("");
}
做类似的事情:
String dirPath = "";
if (cbxBlackBerry.isSelected())
dirPath = BLACKBERRY_PATH; // a constant
else {
dirPath = "";
}
setDirectory(new File(dirPath));
在课程的顶部,如果需要,可以使用常量:
private static final String BLACKBERRY_PATH = "\\RSASoftToken\\blackberry";