gpt4 book ai didi

java - 在自定义的 JFileChooser 中,从 JComboBox 中选择一个执行该特定操作

转载 作者:行者123 更新时间:2023-12-01 12:32:54 25 4
gpt4 key购买 nike

我通过自定义 JFileChooser 打开文件然后添加 JComboBox。当我从 JComboBox 中选择一个时,该特定操作会针对特定文件执行。例如,我的文本文件包含一些文本,例如“一旦我们完成”。当我选择二进制形式 JComboBox.它显示在文本区域中,如“完成后 63 6F FD 70 6C 65 74”。

这是我的代码,

public class CustomJFileChooser {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
FileChooser frame = new FileChooser();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});

final JFileChooser chooser = new JFileChooser();
JComponent panel = new JPanel((LayoutManager) new FlowLayout( FlowLayout.LEFT));
JComboBox comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(new String[] { "text", "binary" }));
panel.add(new JLabel("FileFormat: "));
panel.add(comboBox);
chooser.setAccessory(panel);
JComponent center = null;
BorderLayout layout = (BorderLayout) chooser.getLayout();
for (Component child : chooser.getComponents()) {
if (BorderLayout.CENTER == layout.getConstraints(child)) {
center = (JComponent) child;
}
}
if (center != null)
center.add(panel, BorderLayout.SOUTH);
final JFrame frame = new JFrame();
JButton button = new JButton("Open File Chooser");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
chooser.showOpenDialog(frame);
}
});
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);

}

}

谢谢。

最佳答案

不要只调用 showOpenDialog 而不获取对结果的引用,而是这样做

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

int result = chooser.showOpenDialog(frame);

然后检查 result == JFileChooser.APPROVE_OPTION 是否意味着已按下 Open 按钮。然后就可以获取选中的文件了

int result = chooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();

然后您要检查组合框中所选的项目。如果它等于“二进制”,则执行二进制操作,否则执行文本操作。类似的东西

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int result = chooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
String type = comboBox.getSelectedItem().toString();
File file = chooser.getSelectedFile();
if ("binary".equals(type)) {
// do binary action
} else {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
textArea.read(reader, null);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
});

查看更多信息 How to use File Choosers .

关于java - 在自定义的 JFileChooser 中,从 JComboBox 中选择一个执行该特定操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25805694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com