JFileChooser.showOpenDialog没有打开,并且没有错误被抛出?
好吧,所以我试图做一个十六进制编辑器,我试图做一个负载JMenuItem,但它不工作。 JFileChooser OpenDialog不显示,并且没有显示错误。JFileChooser.showOpenDialog没有打开,并且没有错误被抛出?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.util.Vector;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class HexEditor extends JFrame{
JTextArea textArea;
JFileChooser chooser;// = new JFileChooser();
FileInputStream fin;
JMenuBar menuBar;
JMenu file;
JMenuItem load;
public HexEditor(){
super("Cypri's java hex editor");
chooser = new JFileChooser();
load = new JMenuItem("Load");
load.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event) {
try{
openFile();
fin = new FileInputStream(chooser.getSelectedFile());
int ch;
StringBuffer strContent = new StringBuffer("");
for(int i = 0; (ch = fin.read()) != -1; i++){
String s = Integer.toHexString(ch);
if(s.length() < 2)
s = "0" + Integer.toHexString(ch);
if(i < 10)
strContent.append(" " + s.toUpperCase());
else{
strContent.append(" " + s.toUpperCase() + "\n");
i = 0;
}
}
textArea.setText(strContent.toString());
//textArea.setWrapStyleWord(true);
//textArea.setColumns(50);
//textArea.setRows(50);
}
catch(Exception e){
e.printStackTrace();
}
}
});
file = new JMenu("File");
file.add(new JMenuItem("Load"));
menuBar = new JMenuBar();
menuBar.add(file);
textArea = new JTextArea();
textArea.setSize(300,300);
textArea.setText("Hello\n");
textArea.append(" world!");
setSize(640, 480);
//getContentPane().setBackground(Color.);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(BorderLayout.NORTH, menuBar);
getContentPane().add(BorderLayout.WEST, textArea);
pack();
setVisible(true);
}
public void openFile(){
chooser.showOpenDialog(this);
}
public static void main(String[] args){
HexEditor app = new HexEditor();
}
}
你永远不与添加的JMenuItem听众,而是创建一个新的。
替换:
file.add(new JMenuItem("Load"));
与
file.add(load);
一切都在事件调度线程中完成吗?如果不是,你会得到这样的小错误。
http://download.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html
http://www.javaworld.com/javaworld/jw-08-2007/jw-08-swingthreading.html
http://www.jguru.com/faq/view.jsp?EID=8963
而且,看http://www.fifesoft.com/hexeditor/一个整洁的十六进制编辑器组件在BSD许可下:)
import javax.swing.SwingUtilities;
public static void main(String[] args){
Runnable r = new Runnable() {
public void run() {
HexEditor app = new HexEditor();
}
};
SwingUtilities.invokeLater(r);
}
无关,与他的问题:) – willcodejavaforfood 2010-10-10 20:58:41
我不会说。他直接在主线上做东西,这是绝对的灾难。 – 2010-10-10 20:59:58
我会这么说,但你是对的。你真的应该从美国东部时间开始。 – willcodejavaforfood 2010-10-10 21:08:01
这工作,我会尽快除了这个答案,只要我可以。谢谢。 :) – William 2010-10-10 21:03:18
@William - 没问题:) – willcodejavaforfood 2010-10-10 21:04:36