The Artima Developer Community
Sponsored Link

Java Answers Forum
jswing & a io rw dat file application

3 replies on 1 page. Most recent reply: Jun 17, 2002 8:14 PM by Charles Bell

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 3 replies on 1 page
Fiona

Posts: 4
Nickname: fi
Registered: Jun, 2002

jswing & a io rw dat file application Posted: Jun 13, 2002 9:16 AM
Reply to this message Reply
Advertisement
Hi there :)

I was wondering if anyone would be able to give me a wee bit of guidance in relation to a jswing application I?ve created. I am trying to read / write a .dat file into the textfields of the application and have come to loggerheads with me and coding *sighs*.

There are a couple of questions on the tip of my mind ?.
1. when creating the .dat file is it best to use the ?,? as the separator between textfields and a ?return? at the end of each book to be listed?
2. after much researching the net looking at randomAccessFiles and binaryFiles I am slightly confused on which would be better when reading in an array that the book details .dat file would parse through as a string ?

The code I have so far

import javax.swing.*;
import javax.swing.ImageIcon;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import BookA.*;

public class BookList extends JFrame {
private JRootPane root = new JRootPane();
private JPanel bookLabels = new JPanel( new FlowLayout( FlowLayout.CENTER ) );
private JPanel bookTextFields
= new JPanel( new FlowLayout( FlowLayout.CENTER ) );
private JPanel editPane
= new JPanel( new FlowLayout( FlowLayout.CENTER ) );
private JFileChooser fileChoose
= new JFileChooser();
private JDialog fileDlg;

private static final boolean RESIZABLE = false;
private static final boolean CLOSABLE = true;
private static final boolean MAXIMIZABLE = false;
private static final boolean ICONIFIABLE = true;
private static final boolean MODAL = false;

public BookList( String titleText ) {
super( titleText );
getContentPane().setLayout(
new BoxLayout( getContentPane(), BoxLayout.PAGE_AXIS ) );

JToolBar jtb = new JToolBar();
JMenu file = new JMenu("File");
JMenu sort = new JMenu("Sort");
JMenuBar jmb = new JMenuBar();
jmb.add( file );
jmb.add( sort );

NewAction na = new NewAction();
file.add( na ).setMnemonic( 'N' );
jtb.add( na );

OpenAction op = new OpenAction();
file.add( op ).setMnemonic( 'O' );
jtb.add( op );

SaveAction sa = new SaveAction();
file.add( sa ).setMnemonic( 'S' );
jtb.add( sa );

ExitAction ex = new ExitAction();
file.add( ex ).setMnemonic( 'E' );
jtb.add( ex );

AuthorAction au = new AuthorAction();
sort.add( au ).setMnemonic( 'A' );
jtb.add( au );

TitleAction ta = new TitleAction();
sort.add( ta ).setMnemonic( 'T' );
jtb.add( ta );

setJMenuBar( jmb );

bookLabels.add( new JLabel( "ISDN #:" ) );
bookLabels.add( new JLabel( "Title:" ) );
bookLabels.add( new JLabel( "Author:" ) );
bookLabels.add( new JLabel( "Edition" ) );
bookLabels.add( new JLabel( "Year" ) );
bookLabels.add( new JLabel( "Price" ) );
bookLabels.add( new JLabel( "Comments" ) );

bookTextFields.add( new JTextField( 5 ) );
bookTextFields.add( new JTextField( 10 ) );
bookTextFields.add( new JTextField( 10 ) );
bookTextFields.add( new JTextField( 10 ) );
bookTextFields.add( new JTextField( 2 ) );
bookTextFields.add( new JTextField( 4 ) );
bookTextFields.add( new JTextField( 6 ) );
bookTextFields.add( new JTextArea( 5, 15 ) );

editPane.add( new JButton( "Add Book" ) );
editPane.add( new JButton( "Delete Book" ) );
editPane.add( new JButton( "Previous Book" ) );
editPane.add( new JButton( "Next Book" ) );

bookTextFields.setBorder( BorderFactory.createTitledBorder( "Book Details:" ) );

Container cp = getContentPane();
cp.add( bookLabels );
cp.add( bookTextFields );
cp.add( editPane );
setSize( 300, 150 );
setVisible( false );

root.getContentPane();

JInternalFrame jfrm = new JInternalFrame(
"Internal Frame",
RESIZABLE, CLOSABLE, MAXIMIZABLE, ICONIFIABLE );
jfrm.setPreferredSize( new Dimension( 375, 300 ) );
JDesktopPane jdt = new JDesktopPane();
jdt.setLayout( new FlowLayout() );
jdt.add( jfrm );
getContentPane().add( jdt, BorderLayout.CENTER );

setSize( 500, 200 );
setVisible( true );
JOptionPane.showMessageDialog(
jfrm, "Created by FiFi Applications!" );
}

class NewAction extends AbstractAction {
public NewAction() {
super( "New", new ImageIcon( "new.gif" ));
}
public void actionPerformed( ActionEvent e ) {
}
}
class OpenAction extends AbstractAction {
public OpenAction() {
super( "Open", new ImageIcon( "open.gif" ));
}
public void actionPerformed( ActionEvent e ) {
int result = fileChoose.showOpenDialog(
BookList.this );
File file = fileChoose.getSelectedFile();
if ( file != null && result == JFileChooser.APPROVE_OPTION )
try {
FileReader fr = new FileReader( file );
char[] charBuffer = new char[4096];
int charsRead = fr.read( charBuffer, 0,
charBuffer.length );
while ( charsRead != -1 ) {
charsRead = fr.read( charBuffer, 0,
charBuffer.length );
}
} catch( IOException ioe ) {
ioe.printStackTrace();
}
}
}
class SaveAction extends AbstractAction {
public SaveAction() {
super( "Save", new ImageIcon( "save.gif" ) );
}
public void actionPerformed( ActionEvent e ) {
}
}
class ExitAction extends AbstractAction {
public ExitAction() {
super( "Exit", new ImageIcon( "exit.gif" ) );
}
public void actionPerformed( ActionEvent e ) {
System.exit(0);
}
}
class AuthorAction extends AbstractAction {
public AuthorAction() {
super( "by Author" );
}
public void actionPerformed( ActionEvent e ) {
}
}
class TitleAction extends AbstractAction {
public TitleAction() {
super( "by Title" );
}
public void actionPerformed( ActionEvent e ) {
}
}
public static void main( String[] args ) {
new BookList(
"The Book List!" );
}
}


please excuse the layout ? I?m still playing with layoutmanger ;)
and also some of the code has not been finished for various actionPerformed or the sort by ?title? ?author? has not yet been done <8]

I have created also the class that will do the sorting methods

public class Book {
private String title;
private String author;
public Book(String myAuthor, String myTitle) {
title = myTitle;
author = myAuthor;
}
boolean doesTitleContain(String word) {
String lowerCaseTitle = title.toLowerCase();
String lowerCaseWord = word.toLowerCase();
return lowerCaseTitle.indexOf(lowerCaseWord) >= 0;
}
boolean doesAuthorContain(String word) {
String lowerCaseAuthor = author.toLowerCase();
String lowerCaseWord = word.toLowerCase();
return lowerCaseAuthor.indexOf(lowerCaseWord) >= 0;
}
public String showInfo() {
return "Title: " + title + "\n" +
"Author: " + author + "\n";
}
}


and the class file that declares the strings for the textfields

public class BookA
{
public String title;
public String publisher;
public String dsn;
public String edition;
public String year;
public String comments;
public String price;

//constructor
BookA ()
{
setDSN("0");
setTitle("0");
setPublisher("0");
setEdition("0");
setYear("0") ;
setPrice("0");
setComments("0");
}
public void setDSN(String dsn){this.dsn = dsn; }
public void setTitle(String title){this.title = title; }
public void setPublisher(String p){this.publisher = p; }
public void setEdition(String e){this.edition = e; }
public void setYear(String y){this.year = y; }
public void setPrice(String p){this.price = p; }
public void setComments(String c){this.comments = c; }
public String getDSN() { return dsn; }
public String getTitle() { return title;}
public String getPublisher() { return publisher; }
public String getEdition(){ return edition; }
public String getYear() { return year; }
public String getPrice() { return price; }
public String getComments(){ return comments; }
}

Blending those two class files so that the main java file will be able to use them only need to be "imported"?

Any light shed upon my confused state of mind would be very much appreciated <8]

Thank you thank you thank you!

Fi


Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: jswing & a io rw dat file application Posted: Jun 16, 2002 9:49 PM
Reply to this message Reply
You need to declare your text fields with names so you can reference them in your program and then set the test values. You have them declared anonymously:


bookTextFields.add( new JTextField( 5 ) );
bookTextFields.add( new JTextField( 10 ) );
bookTextFields.add( new JTextField( 10 ) );
bookTextFields.add( new JTextField( 10 ) );
bookTextFields.add( new JTextField( 2 ) );
bookTextFields.add( new JTextField( 4 ) );
bookTextFields.add( new JTextField( 6 ) );
bookTextFields.add( new JTextArea( 5, 15 ) );


You can use proeprties files that might look like:


ISDN=0-596-00143-6
Title=Java and XSLT
Author=Eric M. Burke
Edition=First
Year=2001
Price=$39.95
Comments=This book just happened to be sitting nearby so I used it.


and call a method such as the following:

public void setFields(File propertiesFile){
Properties properties = new Properties();
try{
properties.load(new FileInputStream(propertiesFile));
String isdn = properties.getProperty("ISDN");
String title = properties.getProperty("Title");
String author = properties.getProperty("Author");
String edition = properties.getProperty("Edition");
String year = properties.getProperty("Year");
String price = properties.getProperty("Price");
String comments = properties.getProperty("Comments");

isdnField.setText(isdn);
titleField.setText(title);
authorField.setText(author);
editionField.setText(edition);
yearField.setText(year);
priceField.setText(price);
commentsField.setText(comments);

}catch(FileNotFoundException fnfe){
System.err.println("FileNotFoundException: " + fnfe.getMessage());
}catch(IOException ioe){
System.err.println("IOException: " + ioe.getMessage());
}
}

to set them.

Fiona

Posts: 4
Nickname: fi
Registered: Jun, 2002

Re: jswing & a io rw dat file application Posted: Jun 17, 2002 1:14 PM
Reply to this message Reply
hey charles ...

my code now is slightly different to what i had originally posted here in the forum.
i'm not to set any values into for the text field as this program is to "create" a new randomAccessFile in a binary format. i have two other class files that are to be incorporated into the main java file of the program that allow me 1. to sort and 2. to set to fields to null for "rw". so i cannot put any properties in.

my main code file looks like this:-

package book;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.ImageIcon;
import java.text.DecimalFormat;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.*;


public class BookListA extends JFrame {
RandomAccessFile raf;

/** mainframe
*/

Font textFont;

private JRootPane root = new JRootPane();

/** creating the three panels to make up the content pane
*/

private JPanel blankJP = new JPanel();
private JPanel boxLabels = new JPanel( new GridLayout(9, 1) );
private JPanel boxTextFields = new JPanel( new GridLayout(8, 1) );
private JPanel bookLabels = new JPanel();
private JPanel east = new JPanel();
private JPanel bookTextFields = new JPanel();
private JPanel editPane = new JPanel();
private JFileChooser fileChoose = new JFileChooser();
private JDialog fileDlg;
JLabel blank = new JLabel( "" );
JLabel isdn = new JLabel( "ISDN #:" );
JTextField isdnText = new JTextField("", 15);
JLabel title = new JLabel( "Title:" );
JTextField titledText = new JTextField("", 15);
JLabel author = new JLabel( "Author:" );
JTextField authorText = new JTextField("", 15);
JLabel publisher = new JLabel( "Publisher:" );
JTextField publisherText = new JTextField("", 15);
JLabel edition = new JLabel( "Edition:" );
JTextField editionText = new JTextField("", 15);
JLabel year = new JLabel( "Year:" );
JTextField yearText = new JTextField("", 15);
JLabel price = new JLabel( "Price:" );
JTextField priceText = new JTextField("", 15);
JLabel comments = new JLabel( "Comments:" );
JTextField commentsText = new JTextField( "", 15 );

JButton addB = new JButton( "Add Book" );
JButton deleteB = new JButton( "Delete Book" );
JButton previousB = new JButton( "Previous Book" );
JButton nextB = new JButton( "Next" );

/** declaring the jfrm constraints
*/
private static final boolean RESIZABLE = false;
private static final boolean CLOSABLE = true;
private static final boolean MAXIMIZABLE = false;
private static final boolean ICONIFIABLE = true;
private static final boolean MODAL = false;

/** the constructor
*/
public BookListA( String titleText ) {

super( titleText );
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
int width = 400, height = 200;
setBounds((d.width - width)/2, (d.height - height)/2, width, height);
setResizable(false);

getContentPane().setLayout( new FlowLayout() );


/** level 1 menu objects
*/
JToolBar jtb = new JToolBar();
JMenu file = new JMenu("File");
JMenu sort = new JMenu("Sort");
JMenuBar jmb = new JMenuBar();
jmb.add( file );
jmb.add( sort );

/** level 2 menu items
*/
NewAction na = new NewAction();
file.add( na ).setMnemonic( 'N' );
jtb.add( na );
OpenAction op = new OpenAction();
file.add( op ).setMnemonic( 'O' );
jtb.add( op );
SaveAction sa = new SaveAction();
file.add( sa ).setMnemonic( 'S' );
jtb.add( sa );
ExitAction ex = new ExitAction();
file.add( ex ).setMnemonic( 'E' );
jtb.add( ex );
AuthorAction au = new AuthorAction();
sort.add( au ).setMnemonic( 'A' );
jtb.add( au );
TitleAction ta = new TitleAction();
sort.add( ta ).setMnemonic( 'T' );
jtb.add( ta );

setJMenuBar( jmb );

boxLabels.add( blank );
boxLabels.add( isdn );
boxLabels.add( title );
boxLabels.add( author );
boxLabels.add( publisher );
boxLabels.add( edition );
boxLabels.add( year );
boxLabels.add( price );
boxLabels.add( comments );

boxTextFields.add( isdnText );
boxTextFields.add( titledText );
boxTextFields.add( authorText );
boxTextFields.add( publisherText );
boxTextFields.add( editionText );
boxTextFields.add( yearText );
boxTextFields.add( priceText );
boxTextFields.add( commentsText );

//add the action commands to the third JPanel( editPane )
editPane.add( addB );
editPane.add( deleteB );
editPane.add( previousB );
editPane.add( nextB );
addB.setEnabled( true );
addB.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) { //throws IOException


/** note the code here is trying to access the randomAccessFile or create a new one by using the add button
but I am having difficulty with it?..

JFileChooser fileChooser = new JFileChooser();
try {
book.BookDetails bookDetail = getBookDetails();
String[] values = {
String.valueOf( bookDetail() ),
bookDetail.getIsdn(),
bookDetail.getTitle(),
bookDetail.getAuthor();
bookDet ail.getPublisher();
bookDetail.getEdition();
bookDetail.getYear();
bookDetail.ge tPrice();
bookDetail.getComments();
BookListA.setFieldValues( values );
}
catch ( NumberFormatException nfe ) {
JOptionPane.showMessageDialog( new JFrame(),
"Invalid Entry",
"Invalid Number Format",
JOptionPane.ERROR_MESSAGE );

*/
}
}
);
deleteB.setEnabled( true );
deleteB.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
}
}
);

previousB.setEnabled( true );
previousB.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
}
}
);
nextB.setEnabled( true );
nextB.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
}
}
);

//fill the content pane( cp )
Container cp = getContentPane();
bookLabels.add( boxLabels );
boxTextFields.setBorder( BorderFactory.createTitledBorder( "Book Details" ) );
boxTextFields.setBackground( Color.cyan );
bookTextFields.add( boxTextFields );
cp.setLayout(new BorderLayout());
cp.add( boxLabels, BorderLayout.WEST );
cp.add( boxTextFields, BorderLayout.CENTER );
cp.add( blankJP, BorderLayout.EAST );
cp.add( editPane, BorderLayout.SOUTH );
setSize( 300, 250 );
setVisible( false );

root.getContentPane();


/** creating the constructor of the internal frame
* including its size, layout, calling in constraints set
* and adding a message to the messagebox.
*/
JInternalFrame jfrm = new JInternalFrame(
"Internal Frame",
CLOSABLE, ICONIFIABLE );
jfrm.setPreferredSize( new Dimension( 375, 300 ) );
JDesktopPane jdt = new JDesktopPane();
jdt.setLayout( new FlowLayout() );
jdt.add( jfrm );
getContentPane().add( jdt, BorderLayout.EAST );
setSize( 500, 300 );
setVisible( true );
JOptionPane.showMessageDialog(
jfrm, "Created by FiFi Applications!" );
}
/** creating the menu object classes
*/
class NewAction extends AbstractAction {
public NewAction() {
super( "New", new ImageIcon( "new.gif" ));
}
public void actionPerformed( ActionEvent e ) {
}
}
class OpenAction extends AbstractAction {
public OpenAction() {
super( "Open", new ImageIcon( "open.gif" ));
}
public void actionPerformed( ActionEvent e ) {
int result = fileChoose.showOpenDialog(
BookListA.this );
File file = fileChoose.getSelectedFile();
if ( file != null
&& result == JFileChooser.APPROVE_OPTION ) try {
FileReader fr = new FileReader( file );
char[] charBuffer = new char[4096];
int charsRead = fr.read( charBuffer, 0,
charBuffer.length );
while ( charsRead != -1 ) {
charsRead = fr.read( charBuffer, 0,
charBuffer.length );
}
} catch( IOException ioe ) {
ioe.printStackTrace();
}
}
}

class SaveAction extends AbstractAction {
public SaveAction() {
super( "Save", new ImageIcon( "save.gif" ) );
}
public void actionPerformed( ActionEvent e ) {
}
}

class ExitAction extends AbstractAction {
public ExitAction() {
super( "Exit", new ImageIcon( "exit.gif" ) );
}
public void actionPerformed( ActionEvent e ) {
System.exit(0);
}
}

class AuthorAction extends AbstractAction {
public AuthorAction() {
super( "by Author" );
}
public void actionPerformed( ActionEvent e ) {

// BookSort doesAuthorContain = new BookSort();
// book.BookSort sortAuthor = new BookSort();

/** here I?ve been working upon the sort methods of title and author but gave up since I didn?t have the
randomAccess dat file even connecting yet :\

String choice = "";
while (!(choice.equalsIgnoreCase("x"))){
String isdnText = JOptionPane.showInputDialog(
"Enter a book isdn#:");
Book book = new Book( isdnText );
String message = "You have selected:\n"
+ " Title: " + book.BookListA( title ) + "\n"
+ " Price: " + book.BookListA( price ) + "\n\n"
+ "Press Enter to continue or enter 'x' to exit:";
choice = JOptionPane.showInputDialog(null,
message, "Book", JOptionPane.PLAIN_MESSAGE);
}//end while
System.exit(0); */
}
}

class TitleAction extends AbstractAction {
public TitleAction() {
super( "by Title" );
}
public void actionPerformed( ActionEvent e ) {
}
}

/** naming the main frame
*/
public static void main( String[] args ) {
new BookListA(
"The Book List!" );
}
}


the other two class files that go with this is

1. sort method

public class BookSort{
private String title;
private String author;


public BookSort(String Author, String Title) {
title = Title;
author = Author;
}

boolean doesTitleContain(String word) {
String lowerCaseTitle = title.toLowerCase();
String lowerCaseWord = word.toLowerCase();
return lowerCaseTitle.indexOf(lowerCaseWord) >= 0;
}

boolean doesAuthorContain(String word) {
String lowerCaseAuthor = author.toLowerCase();
String lowerCaseWord = word.toLowerCase();
return lowerCaseAuthor.indexOf(lowerCaseWord) >= 0;
}

public String showInfo() {
return "Title: " + title + "\n" +
"Author: " + author + "\n";
}
}



and

2. the bookDetails class file creating an array for the textfields setting them to null
public class BookDetails
{
public String isdn;
public String title;
public String author;
public String publisher;
public String edition;
public String year;
public String price;
public String comments;

//constructor
BookDetails ()
{
setIsdn( "0" );
setTitle("0");
setAuthor("0");
setPublisher("0");
setEdition("0");
setYear("0");
setPrice("0");
setComments("0");
}

public void setIsdn(String isdn){this.isdn = isdn; }
public void setTitle(String title){this.title = title; }
public void setAuthor(String author){this.author = author; }
public void setPublisher(String p){this.publisher = p; }
public void setEdition(String e){this.edition = e; }
public void setYear(String y){this.year = y; }
public void setPrice(String p){this.price = p; }
public void setComments(String c){this.comments = c; }

public String getIsdn() { return isdn;}
public String getTitle() { return title;}
public String getAuthor() { return author; }
public String getPublisher() { return publisher; }
public String getEdition(){ return edition; }
public String getYear() { return year; }
public String getPrice() { return price; }
public String getComments(){ return comments; }

}


anyways ... i'm still plugging away at trying to workout accessing or creating a randomAccess file in binary format .... and still loggerheading it >8{

but that jswing is cool stuff even if i'd be having problems ... ahahaha ...

let me know what you think ... thanks again charles :)

fi

Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: jswing & a io rw dat file application Posted: Jun 17, 2002 8:14 PM
Reply to this message Reply
It looks to me like the length of your fields are not always going to be the same length. Example:
$14.95 as a string is not the same as $101.98

If you truly want to code your file data so you can read in a random access way, the data must be formatted and padded so that each chunk is the same length so that your program can calculate where to seek to in order to read a data field.
If all you want to do is prevent someone else from reading data, its very easy now in java 1.4.0 to encrypt it and decrypt a file.

I suggest that you decide on the byte length of each data field. Then write a routine to encode each data field and pad it with null bytes '\0' or 0 until it is of the correct size. Writing the data to a file then is very easy.
int dataFieldSize = 100;
byte[] dataField = new byte[dataFieldSize];
String data = dataTextField.getText();
byte dataBytes = data.getBytes();
for (int i = 0;i< dataBytes;i++){
dataField = dataBytes;
}
for (int pad = dataBytes.length; pad < dataFieldSize;pad++){
dataField = 0;
}
File file = new File("yourdatafilename");
FileOutputStream fos = new FileOutputStream(file);
DataOutputStream dos = new DataOutputStream (fos);
dos.write(dataField,0, dataField.length);

//continuing for each data field until
//the whole record is written.

dos.close();
fos.close();


Reading your records is just the reverse.

File file = new File("yourdatafilename");
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream (fis);

byte[] newDataField = new byte[dataFieldSize];
dis.read(newDataField);

//continuing for each data field until
//the whole record is read.
dis.close();
fis.close();

Flat View: This topic has 3 replies on 1 page
Topic: Making radio buttons work Previous Topic   Next Topic Topic: reading MS WORD document through java

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use