我有一个Java作业,我需要构建一个程序,用于在学生之间交换信息。我正在使用IntelliJ IDEA和一个名为JFormDesigner的插件来设计GUI。我想在单击按钮时显示文件选择器。我尝试了不同的实现,但没有一个有效。单击按钮时屏幕上不显示任何内容,我想知道是否有人可以帮助我找到解决方案。
这是按钮代码:
ChooseButton1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
ChooseButton1MouseClicked(e);
}
});
这是实现操作的方法:
private void ChooseButton1MouseClicked(MouseEvent e) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION)
{
File selectedFile = fileChooser.getSelectedFile();
System.out.println(selectedFile.getName());
}
}
以下是测试代码:
import java.awt.event.*;
import javax.swing.*;
import javax.swing.GroupLayout;
import java.io.*;
public class Test extends JPanel {
private JButton ChooseButton;
public Test() {
initComponents();
}
private void ChooseButtonActionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION)
{
File selectedFile = fileChooser.getSelectedFile();
System.out.println(selectedFile.getName());
}
}
private void initComponents() {
ChooseButton = new JButton();
setBorder(new javax.swing.border.CompoundBorder(
new javax.swing.border.TitledBorder(new javax.swing.border.EmptyBorder(0, 0, 0, 0),
"JFormDesigner Evaluation", javax.swing.border.TitledBorder.CENTER,
javax.swing.border.TitledBorder.BOTTOM, new java.awt.Font("Dialog", java.awt.Font.BOLD, 12),
java.awt.Color.red), getBorder())); addPropertyChangeListener(new java.beans.PropertyChangeListener(){public void propertyChange(java.beans.PropertyChangeEvent e) {
if("border".equals(e.getPropertyName())) throw new RuntimeException();
}
});
//---- ChooseButton ----
ChooseButton.setText("Choose");
ChooseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ChooseButtonActionPerformed(e);
}
});
GroupLayout layout = new GroupLayout(this);
setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup()
.addGroup(layout.createSequentialGroup()
.addGap(155, 155, 155)
.addComponent(ChooseButton)
.addContainerGap(175, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup()
.addGroup(layout.createSequentialGroup()
.addGap(125, 125, 125)
.addComponent(ChooseButton)
.addContainerGap(143, Short.MAX_VALUE))
);
}
public void main(String[] args) {
Runnable runnable = new Runnable() {
@Override public void run() {
new Test();
}
};
EventQueue.invokeLater(runnable);
}
}
选择其他侦听器
ChooseButton1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ChooseButton1MouseClicked(e);
}
});