[英]JFileChooser.showOpenDialog not opening, and no error being thrown?
好的,所以我試圖創建一個十六進制編輯器,並且試圖加載JMenuItem,但是它不起作用。 JFileChooser OpenDialog不會顯示,並且不會顯示任何錯誤。
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與偵聽器一起添加,而是創建一個新的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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.