【New】Java学习小记(七)地址薄(三)

接下去继续给大家介绍这个地址薄程序我们要做的如下:

 

 

1.创建一个用户界面

2.向文件中添加一条记录

3.从文件中读取一条记录

4.编程实现按钮的功能

代码如下:

package chapter18;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class AddressBook extends JFrame {
  // Specify the size of five string fields in the record
  final static int NAME_SIZE = 32;
  final static int STREET_SIZE = 32;
  final static int CITY_SIZE = 20;
  final static int STATE_SIZE = 2;
  final static int ZIP_SIZE = 5;
  final static int RECORD_SIZE =
    (NAME_SIZE + STREET_SIZE + CITY_SIZE + STATE_SIZE + ZIP_SIZE);

  // Access address.dat using RandomAccessFile
  private RandomAccessFile raf;

  // Text fields
  private JTextField jtfName = new JTextField(NAME_SIZE);
  private JTextField jtfStreet = new JTextField(STREET_SIZE);
  private JTextField jtfCity = new JTextField(CITY_SIZE);
  private JTextField jtfState = new JTextField(ZIP_SIZE);
  private JTextField jtfZip = new JTextField(ZIP_SIZE);

  // Buttons
  private JButton jbtAdd = new JButton("Add");
  private JButton jbtFirst = new JButton("First");
  private JButton jbtNext = new JButton("Next");
  private JButton jbtPrevious = new JButton("Previous");
  private JButton jbtLast = new JButton("Last");

  public AddressBook() {
    // Open or create a random access file
    try {
      raf = new RandomAccessFile("address.dat", "rw");
    }
    catch(IOException ex) {
      System.out.print("Error: " + ex);
      System.exit(0);
    }

    // Panel p1 for holding labels Name, Street, and City
    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(3, 1));
    p1.add(new JLabel("Name"));
    p1.add(new JLabel("Street"));
    p1.add(new JLabel("City"));

    // Panel jpState for holding state
    JPanel jpState = new JPanel();
    jpState.setLayout(new BorderLayout());
    jpState.add(new JLabel("State"), BorderLayout.WEST);
    jpState.add(jtfState, BorderLayout.CENTER);

    // Panel jpZip for holding zip
    JPanel jpZip = new JPanel();
    jpZip.setLayout(new BorderLayout());
    jpZip.add(new JLabel("Zip"), BorderLayout.WEST);
    jpZip.add(jtfZip, BorderLayout.CENTER);

    // Panel p2 for holding jpState and jpZip
    JPanel p2 = new JPanel();
    p2.setLayout(new BorderLayout());
    p2.add(jpState, BorderLayout.WEST);
    p2.add(jpZip, BorderLayout.CENTER);

    // Panel p3 for holding jtfCity and p2
    JPanel p3 = new JPanel();
    p3.setLayout(new BorderLayout());
    p3.add(jtfCity, BorderLayout.CENTER);
    p3.add(p2, BorderLayout.EAST);

    // Panel p4 for holding jtfName, jtfStreet, and p3
    JPanel p4 = new JPanel();
    p4.setLayout(new GridLayout(3, 1));
    p4.add(jtfName);
    p4.add(jtfStreet);
    p4.add(p3);

    // Place p1 and p4 into jpAddress
    JPanel jpAddress = new JPanel(new BorderLayout());
    jpAddress.add(p1, BorderLayout.WEST);
    jpAddress.add(p4, BorderLayout.CENTER);

    // Set the panel with line border
    jpAddress.setBorder(new BevelBorder(BevelBorder.RAISED));

    // Add buttons to a panel
    JPanel jpButton = new JPanel();
    jpButton.add(jbtAdd);
    jpButton.add(jbtFirst);
    jpButton.add(jbtNext);
    jpButton.add(jbtPrevious);
    jpButton.add(jbtLast);

    // Add jpAddress and jpButton to the frame
    add(jpAddress, BorderLayout.CENTER);
    add(jpButton, BorderLayout.SOUTH);

    jbtAdd.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        writeAddress();
      }
    });
    jbtFirst.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
          if (raf.length() > 0) readAddress(0);
        }
        catch (IOException ex) {
          ex.printStackTrace();
        }
      }
    });
    jbtNext.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
          long currentPosition = raf.getFilePointer();
          if (currentPosition < raf.length())
            readAddress(currentPosition);
        }
        catch (IOException ex) {
          ex.printStackTrace();
        }
      }
    });
    jbtPrevious.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
          long currentPosition = raf.getFilePointer();
          if (currentPosition - 2 * RECORD_SIZE > 0)
            // Why 2 * 2 * RECORD_SIZE? See the follow-up remarks
            readAddress(currentPosition - 2 * 2 * RECORD_SIZE);
          else
            readAddress(0);
        }
        catch (IOException ex) {
          ex.printStackTrace();
        }
      }
    });
    jbtLast.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
          long lastPosition = raf.length();
          if (lastPosition > 0)
            // Why 2 * RECORD_SIZE? See the follow-up remarks
            readAddress(lastPosition - 2 * RECORD_SIZE);
        }
        catch (IOException ex) {
          ex.printStackTrace();
        }
      }
    });

    // Display the first record if exists
    try {
      if (raf.length() > 0) readAddress(0);
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
  }

  /** Write a record at the end of the file */
  public void writeAddress() {
    try {
      raf.seek(raf.length());
      FixedLengthStringIO.writeFixedLengthString(
        jtfName.getText(), NAME_SIZE, raf);
      FixedLengthStringIO.writeFixedLengthString(
        jtfStreet.getText(), STREET_SIZE, raf);
      FixedLengthStringIO.writeFixedLengthString(
        jtfCity.getText(), CITY_SIZE, raf);
      FixedLengthStringIO.writeFixedLengthString(
        jtfState.getText(), STATE_SIZE, raf);
      FixedLengthStringIO.writeFixedLengthString(
        jtfZip.getText(), ZIP_SIZE, raf);
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
  }

  /** Read a record at the specified position */
  public void readAddress(long position) throws IOException {
    raf.seek(position);
    String name = FixedLengthStringIO.readFixedLengthString(
      NAME_SIZE, raf);
    String street = FixedLengthStringIO.readFixedLengthString(
      STREET_SIZE, raf);
    String city = FixedLengthStringIO.readFixedLengthString(
      CITY_SIZE, raf);
    String state = FixedLengthStringIO.readFixedLengthString(
      STATE_SIZE, raf);
    String zip = FixedLengthStringIO.readFixedLengthString(
      ZIP_SIZE, raf);

    jtfName.setText(name);
    jtfStreet.setText(street);
    jtfCity.setText(city);
    jtfState.setText(state);
    jtfZip.setText(zip);
  }

  public static void main(String[] args) {
    AddressBook frame = new AddressBook();
    frame.pack();
    frame.setTitle("AddressBook");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
}

          如果这个文件address.dat不存在,则创建名为address.dat的随机读写文件来存储地址信息。如果它已经存在,则打开它。随机文件对象raf用于实现文件的读写操作。记录中每个域的长度都是固定的
         44——100行创建用户界面,第102——156行注册监听器,在第159——164行程序开始运行后,如果存在记录,则显示第一条记录。
         writeAddress()方法将文件指针设置到文件的尾(170行),并向文件中写入新纪录(第171——180行)
         readAddress()方法将指针设置到指定位置(189行)并从文件中读取一条记录(190——199行)
         要向文件中添加记录,需要从用户界面中收集地址信息,在写到文件之中去
         处理按事件的代码第102——156行实现。Firs按钮读取文件中0的位置的记录(110行)Next按钮读取当前文件指针所指的记录(122行)读取一条记录后,文件指针从上一个位置向前移动2*RECORD_SIZE个字节。对previous按钮,需要显示当前正在显示的记录的前一条,所以,必须将当前文件指针向后移动两条记录(135行)Last按钮读取raf.length()-2*RECORD_SIZE位置的记录
 

再给大家截图看看效果



 




 
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值