Thursday, 22 November 2012

Java - tutorial

Open a file in java using JFileChooser

CODE

import java.io.*;
import javax.swing.*;
class OpenFileUsingJFileChooser{
    public static void main(String[] args)throws Exception{
        JFileChooser chooser=new  JFileChooser();
        int returnVal = chooser.showOpenDialog(null);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
        File f = chooser.getSelectedFile();
        BufferedReader br=new BufferedReader(new FileReader(f));
        String st="";
        while((st=br.readLine())!=null){
            System.out.println(st);
        }
      }
    }
}
 
 

Using a JFileChooser in Your JFrame

CODE 

import java.awt.BorderLayout;
import java.awt.Font;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class FileSamplePanel {

  public static void main(String args[]) {
    JFrame frame = new JFrame("JFileChooser Popup");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    final JLabel directoryLabel = new JLabel(" ");
    directoryLabel.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 36));
    frame.add(directoryLabel, BorderLayout.NORTH);

    final JLabel filenameLabel = new JLabel(" ");
    filenameLabel.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 36));
    frame.add(filenameLabel, BorderLayout.SOUTH);

    JFileChooser fileChooser = new JFileChooser(".");
    fileChooser.setControlButtonsAreShown(false);
    frame.add(fileChooser, BorderLayout.CENTER);

    frame.pack();
    frame.setVisible(true);
  }
}

 Creating an About Menu Item

 CODE

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class FramewithAboutMenu extends JFrame {
  public FramewithAboutMenu(String title) {
    JMenuBar menuBar = new JMenuBar();
    setTitle(title);
    setJMenuBar(menuBar);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    JMenu fileMenu = new JMenu("File");
    JMenu elementMenu = new JMenu("Elements");
    JMenu helpMenu = new JMenu("Help");
    fileMenu.setMnemonic('F');
    elementMenu.setMnemonic('E');
    helpMenu.setMnemonic('H');
    JMenuItem aboutItem = new JMenuItem("About");
    helpMenu.add(aboutItem);
    menuBar.add(helpMenu);
  }
  public static void main(String[] a) {
    FramewithAboutMenu window = new FramewithAboutMenu("Sketcher");
    window.setBounds(3030300300);
    window.setVisible(true);
  }
}

 

No comments:

Post a Comment