当我点击激活文件选择器的按钮时,添加生成的文件,面板颜色消失。有谁知道为什么会这样?
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileSystemView;
import javax.swing.JFileChooser;
import javax.swing.plaf.FileChooserUI;
@SuppressWarnings("serial")
public class pan extends JPanel implements DropTargetListener {
private DefaultListModel listModel = new DefaultListModel();
private JButton addbutton;
private JButton removebutton;
private JButton selectbutton;
private JButton lockbutton;
private JButton unlockbutton;
/**
* Create the panel.
*/
public pan() {
setLayout(null);
addbutton = new JButton("New button");
addbutton.setBounds(10, 10, 90, 100);
addbutton.addActionListener(new Action());
add(addbutton);
removebutton = new JButton("New button");
removebutton.setBounds(110, 10, 90, 100);
add(removebutton);
selectbutton = new JButton("New button");
selectbutton.setBounds(210, 10, 90, 100);
add(selectbutton);
lockbutton = new JButton("New button");
lockbutton.setBounds(310, 10, 90, 100);
add(lockbutton);
unlockbutton = new JButton("New button");
unlockbutton.setBounds(410, 10, 90, 100);
add(unlockbutton);
JLabel headerLabel = new JLabel("New label");
headerLabel.setBorder(new BevelBorder(BevelBorder.RAISED,
Color.LIGHT_GRAY, Color.GRAY, null, null));
headerLabel.setUI(new ModifLabelUI());
headerLabel.setBounds(10, 120, 635, 30);
add(headerLabel);
}
class Action implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==addbutton){
JFileChooser filechooser=new JFileChooser();
filechooser.setMultiSelectionEnabled(true);
filechooser.updateUI();
filechooser.showOpenDialog(new pan());
File files=filechooser.getSelectedFile();
listModel.addElement(files);
}
}
}
答案 0 :(得分:1)
这不适合updateUI()
,“将UI属性重置为当前外观的值。”目前尚不清楚为什么要调用该方法,但它可能会导致您观察到的颜色变化。首先删除该行。如果不这样做,请修改您的问题以包含展示您所描述问题的sscce。
另请考虑使用非null
layout manager。
答案 1 :(得分:0)
更改actionPerformed
方法的最后几行,如下所示:
int returnVal = filechooser.showOpenDialog(new pan());
if(returnVal == JFileChooser.APPROVE_OPTION) {
//since its multiselection enabled,
//get the selected files not selected file
File[] files=filechooser.getSelectedFiles();
if(files != null){
for(File file: files){
listModel.addElement(file);
}
}
}
编辑:请确保正确处理HeadlessException
等预期异常的异常处理。
<强>说明强>:
当浏览面板打开时,用户可以取消操作。在这种情况下,您不应该读取未选中的文件。这就是为什么需要添加一个用户选择检查,即是否选择了文件。
由于filechooser
以setMultiSelectionEnabled
作为true
打开,因此您需要将选定的文件作为File[]
来代替获取单个文件。
由于您要获取多个文件,因此需要在listModel
中添加每个文件。一种方法是迭代File数组并一次添加一个文件。其他选项可能是使用Arrays.asList()
,获取列表并一次添加所有文件。
希望这有帮助。