我的代码有点麻烦。我已经放入文件选择器/阅读器,但我不知道如何在GUI中的左窗格中显示它。我尝试了一些事情没有成功,无法弄明白。如果有人能够提供解决方案和解释,以便我能够理解我做错了/没做过什么,那么我将非常感激。
此外,我的代码有点凌乱,而且我已经完成了我的方法,如果有人在组织方法和代码方面有未来的部队,那么做某些令人烦恼和不方便的事情会受到高度赞赏。
这是我的代码。
public class JavaAssignment {
public static JMenuBar setupMenu() { // method modifiers where mising here
JMenuBar menuBar = new JMenuBar(); // menubar
JMenu menu1 = new JMenu("File"); //menu
menuBar.add(menu1); // add menu to gui
JMenu menu2 = new JMenu("Help");
menuBar.add(menu2);
JMenuItem menuItem1 = new JMenuItem("Load File", KeyEvent.VK_1); // create drop down menu
JMenuItem menuItem2 = new JMenuItem("Save File", KeyEvent.VK_1);
JMenuItem menuItem3 = new JMenuItem("Exit", KeyEvent.VK_1);
JMenuItem menuItem4 = new JMenuItem("About", KeyEvent.VK_1);
menu1.add(menuItem1); // adds drop down menus to gui
menu1.add(menuItem2);
menu1.add(menuItem3);
menu2.add(menuItem4);
// execute code when selected
menuItem1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final JFileChooser fc = new JFileChooser();
// you can set the directory with the setCurrentDirectory method.
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
// User has selected to open the file.
File file = fc.getSelectedFile();
try {
// Open the selected file
BufferedReader reader = new BufferedReader(new FileReader(file));
// Output the contents to the console.
String nextLine = reader.readLine();
while ( nextLine != null ) {
final JTextArea input = new JTextArea(nextLine);
nextLine = reader.readLine();
}
reader.close();
} catch (IOException e1) {
System.err.println("Error while reading the file");
}
}
}});
return menuBar;
}
public static void main(String[] args) throws FileNotFoundException {
window window = new window();
}
public static class window extends JFrame {
public window() throws FileNotFoundException {
JScrollPane leftScrollPane = new JScrollPane();
JPanel rightPane = new JPanel();
JSplitPane splitPane;
this.setVisible(true);
this.setSize(400, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
splitPane = new JSplitPane();
splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
splitPane.setDividerSize(10);
splitPane.setDividerLocation(100);
splitPane.setLeftComponent(leftScrollPane);
splitPane.setRightComponent(rightPane);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(600);
Dimension minimumSize = new Dimension(100, 50);
leftScrollPane.setSize(400, 400);
this.setJMenuBar(setupMenu());
splitPane.setPreferredSize(new Dimension(400, 200));
splitPane.setLeftComponent(leftScrollPane);
splitPane.setRightComponent(rightPane);
this.add(splitPane);
this.setSize(1280, 720);
}
}
}