سؤال

JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");  
add(menubar,BorderLayout.NORTH); 
menubar.add(file);              
JMenuItem Open = new JMenuItem("OPEN...     Ctrl+O");
file.add(Open);
Open.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) { 
        Frame f = new Frame();
        FileDialog openf = new FileDialog(f, "Open");
        openf.setVisible(true);
    }
});

Well, I tried to use a lot many examples on the internet which makes the open button work as you can see i have already made the design but i need help in how to open a .txt file on clicking the open button in the filedialog. how am i supposed to do that?? i would really appreciate if anyone can help me out with few lines of code that actually works as i am sick of searching error generating codes from the internet.

enter image description here

هل كانت مفيدة؟

المحلول

The documentation states:

The FileDialog class displays a dialog window from which the user can select a file.

Since it is a modal dialog, when the application calls its show method to display the dialog, it blocks the rest of the application until the user has chosen a file.

Therefore, instead of calling .setVisible(true) you can call .show() on the dialog, and then you can use getFile() to get the file that was chosen, or getFiles() if you are using multipleMode.

To read the file you can use:

public static String readFile(String path, Charset encoding) throws IOException {
  byte[] encoded = Files.readAllBytes(Paths.get(path));
  return encoding.decode(ByteBuffer.wrap(encoded)).toString();
}

yourComponent.setText(readFile(openf.getFile(), Charset.defaultCharset()));

(Taken from this question)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top