package com.deitel.jhtp4.ch16;
import java.io.Serializable;
public class AccountRecord implements Serializable{
private int account;
private String firstName;
private String lastName;
private double balance;
public AccountRecord()
{
this(0,"","",0.0);
}
public AccountRecord(int acct,String first,
String last,double bal)
{
setAccount(acct);
setFirstName(first);
setLastName(last);
setBalance(bal);
}
public void setAccount(int acct)
{
account=acct;
}
public int getAccount()
{
return account;
}
public void setFirstName(String first)
{
firstName=first;
}
public String getFirstName()
{
return firstName;
}
public void setLastName(String last)
{
lastName=last;
}
public String getLastName()
{
return lastName;
}
public void setBalance(double bal)
{
balance=bal;
}
public double getBalance()
{
return balance;
}}package com.deitel.jhtp4.ch16;
import java.awt.*;
import javax.swing.*;
public class BankUI extends JPanel{
protected final static String names[]={"Account number",
"First name","Last name","Balance",
"Transaction Amount"};
protected JLabel labels[];
protected JTextField fields[];
protected JButton doTask1,doTask2;
protected JPanel innerPanelCenter,innerPanelSouth;
protected int size;
public static final int ACCOUNT=0,FIRSTNAME=1,
LASTNAME=2,BALANCE=3,TRANSACTION=4;
public BankUI(int mySize)
{
size=mySize;
labels=new JLabel[size];
fields=new JTextField[size];
for(int count=0;count<labels.length;count++)
labels[count]=new JLabel(names[count]);
for(int count=0;count<fields.length;count++)
fields[count]=new JTextField();
innerPanelCenter=new JPanel();
innerPanelCenter.setLayout(new GridLayout(size,2));
for(int count=0;count<size;count++){
innerPanelCenter.add(labels[count]);
innerPanelCenter.add(fields[count]);
}
doTask1=new JButton();
doTask2=new JButton();
innerPanelSouth=new JPanel();
innerPanelSouth.add(doTask1);
innerPanelSouth.add(doTask2);
setLayout(new BorderLayout());
add(innerPanelCenter);
add(innerPanelSouth,BorderLayout.SOUTH);
validate();
}
public JButton getDoTask1Button()
{
return doTask1;
}
public JButton getDoTask2Button()
{
return doTask2;
}
public JTextField[] getFields()
{
return fields;
}
public void clearFields()
{
for(int count=0;count<size;count++)
fields[count].setText("");
}
public void setFieldValues(String strings[])
throws IllegalArgumentException
{
if(strings.length!=size)
throw new IllegalArgumentException("There must be"+
size+"Strings in the array");
for(int count=0;count<size;count++)
fields[count].setText(strings[count]);
}
public String[] getFieldValues()
{
String values[]=new String[size];
for(int count=0;count<size;count++)
values[count]=fields[count].getText();
return values;
}
}
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import com.deitel.jhtp4.ch16.*;
public class CreateSequentialFile extends JFrame{
private ObjectOutputStream output;
private BankUI userInterface;
private JButton enterButton,openButton;
public CreateSequentialFile(){
super("Creating a Sequential File of Objects");
userInterface=new BankUI(4);
getContentPane().add(userInterface);
openButton=userInterface.getDoTask1Button();
openButton.setText("Save into File...");
openButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event)
{
openFile();
}
}
);
enterButton=userInterface.getDoTask2Button();
enterButton.setText("Enter");
enterButton.setEnabled(false);
enterButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event)
{
addRecord();
}
}
);
addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent event)
{
if(output!=null)
addRecord();
closeFile();
}
}
);
setSize(300,200);
show();
}
private void openFile()
{
JFileChooser fileChooser=new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int result=fileChooser.showSaveDialog(this);
if(result==JFileChooser.CANCEL_OPTION)
return;
File fileName=fileChooser.getSelectedFile();
if(fileName==null||
fileName.getName().equals(""))
JOptionPane.showMessageDialog(this,
"Invalid File Name","Invalid File Name",
JOptionPane.ERROR_MESSAGE);
else{
try{
output=new ObjectOutputStream(
new FileOutputStream(fileName));
openButton.setEnabled(false);
enterButton.setEnabled(true);
}
catch(IOException ioException){
JOptionPane.showMessageDialog(this,
"Error Opening File","Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
private void closeFile()
{
try{
output.close();
System.exit(0);
}
catch(IOException ioException){
JOptionPane.showMessageDialog(this,
"Error closing file","Error",
JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
public void addRecord()
{
int accountNumber=0;
AccountRecord record;
String fieldValues[]=userInterface.getFieldValues();
if(!fieldValues[BankUI.ACCOUNT].equals("")){
try{
accountNumber=Integer.parseInt(fieldValues[BankUI.ACCOUNT]);
if(accountNumber>0){
record=new AccountRecord(accountNumber,
fieldValues[BankUI.FIRSTNAME],
fieldValues[BankUI.LASTNAME],
Double.parseDouble(fieldValues[BankUI.BALANCE]));
output.writeObject(record);
output.flush();
}
userInterface.clearFields();
}
catch(NumberFormatException formatException){
JOptionPane.showMessageDialog(this,
"Bad account number or balance",
"Invalid Number Format",
JOptionPane.ERROR_MESSAGE);
}
catch(IOException ioException){
closeFile();
}
}
} /**
* @param args
*/
public static void main(String[] args) {
CreateSequentialFile application=new CreateSequentialFile();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// TODO Auto-generated method stub }}
import java.io.Serializable;
public class AccountRecord implements Serializable{
private int account;
private String firstName;
private String lastName;
private double balance;
public AccountRecord()
{
this(0,"","",0.0);
}
public AccountRecord(int acct,String first,
String last,double bal)
{
setAccount(acct);
setFirstName(first);
setLastName(last);
setBalance(bal);
}
public void setAccount(int acct)
{
account=acct;
}
public int getAccount()
{
return account;
}
public void setFirstName(String first)
{
firstName=first;
}
public String getFirstName()
{
return firstName;
}
public void setLastName(String last)
{
lastName=last;
}
public String getLastName()
{
return lastName;
}
public void setBalance(double bal)
{
balance=bal;
}
public double getBalance()
{
return balance;
}}package com.deitel.jhtp4.ch16;
import java.awt.*;
import javax.swing.*;
public class BankUI extends JPanel{
protected final static String names[]={"Account number",
"First name","Last name","Balance",
"Transaction Amount"};
protected JLabel labels[];
protected JTextField fields[];
protected JButton doTask1,doTask2;
protected JPanel innerPanelCenter,innerPanelSouth;
protected int size;
public static final int ACCOUNT=0,FIRSTNAME=1,
LASTNAME=2,BALANCE=3,TRANSACTION=4;
public BankUI(int mySize)
{
size=mySize;
labels=new JLabel[size];
fields=new JTextField[size];
for(int count=0;count<labels.length;count++)
labels[count]=new JLabel(names[count]);
for(int count=0;count<fields.length;count++)
fields[count]=new JTextField();
innerPanelCenter=new JPanel();
innerPanelCenter.setLayout(new GridLayout(size,2));
for(int count=0;count<size;count++){
innerPanelCenter.add(labels[count]);
innerPanelCenter.add(fields[count]);
}
doTask1=new JButton();
doTask2=new JButton();
innerPanelSouth=new JPanel();
innerPanelSouth.add(doTask1);
innerPanelSouth.add(doTask2);
setLayout(new BorderLayout());
add(innerPanelCenter);
add(innerPanelSouth,BorderLayout.SOUTH);
validate();
}
public JButton getDoTask1Button()
{
return doTask1;
}
public JButton getDoTask2Button()
{
return doTask2;
}
public JTextField[] getFields()
{
return fields;
}
public void clearFields()
{
for(int count=0;count<size;count++)
fields[count].setText("");
}
public void setFieldValues(String strings[])
throws IllegalArgumentException
{
if(strings.length!=size)
throw new IllegalArgumentException("There must be"+
size+"Strings in the array");
for(int count=0;count<size;count++)
fields[count].setText(strings[count]);
}
public String[] getFieldValues()
{
String values[]=new String[size];
for(int count=0;count<size;count++)
values[count]=fields[count].getText();
return values;
}
}
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import com.deitel.jhtp4.ch16.*;
public class CreateSequentialFile extends JFrame{
private ObjectOutputStream output;
private BankUI userInterface;
private JButton enterButton,openButton;
public CreateSequentialFile(){
super("Creating a Sequential File of Objects");
userInterface=new BankUI(4);
getContentPane().add(userInterface);
openButton=userInterface.getDoTask1Button();
openButton.setText("Save into File...");
openButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event)
{
openFile();
}
}
);
enterButton=userInterface.getDoTask2Button();
enterButton.setText("Enter");
enterButton.setEnabled(false);
enterButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event)
{
addRecord();
}
}
);
addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent event)
{
if(output!=null)
addRecord();
closeFile();
}
}
);
setSize(300,200);
show();
}
private void openFile()
{
JFileChooser fileChooser=new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int result=fileChooser.showSaveDialog(this);
if(result==JFileChooser.CANCEL_OPTION)
return;
File fileName=fileChooser.getSelectedFile();
if(fileName==null||
fileName.getName().equals(""))
JOptionPane.showMessageDialog(this,
"Invalid File Name","Invalid File Name",
JOptionPane.ERROR_MESSAGE);
else{
try{
output=new ObjectOutputStream(
new FileOutputStream(fileName));
openButton.setEnabled(false);
enterButton.setEnabled(true);
}
catch(IOException ioException){
JOptionPane.showMessageDialog(this,
"Error Opening File","Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
private void closeFile()
{
try{
output.close();
System.exit(0);
}
catch(IOException ioException){
JOptionPane.showMessageDialog(this,
"Error closing file","Error",
JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
public void addRecord()
{
int accountNumber=0;
AccountRecord record;
String fieldValues[]=userInterface.getFieldValues();
if(!fieldValues[BankUI.ACCOUNT].equals("")){
try{
accountNumber=Integer.parseInt(fieldValues[BankUI.ACCOUNT]);
if(accountNumber>0){
record=new AccountRecord(accountNumber,
fieldValues[BankUI.FIRSTNAME],
fieldValues[BankUI.LASTNAME],
Double.parseDouble(fieldValues[BankUI.BALANCE]));
output.writeObject(record);
output.flush();
}
userInterface.clearFields();
}
catch(NumberFormatException formatException){
JOptionPane.showMessageDialog(this,
"Bad account number or balance",
"Invalid Number Format",
JOptionPane.ERROR_MESSAGE);
}
catch(IOException ioException){
closeFile();
}
}
} /**
* @param args
*/
public static void main(String[] args) {
CreateSequentialFile application=new CreateSequentialFile();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// TODO Auto-generated method stub }}
解决方案 »
- 关于console类的readline()方法的用法问题
- List<Integer>转int[]
- myeclipse里新建jTree时可以可视化建立节点么
- 如何得到按钮名字?
- 关于串口的小问题!
- 执行java界面出不来
- 安装 JBuilder9后在web中web Application, Servlet,Java Server Page等为什么都不能使用?在线等!
- 如何去掉Application中该死的applet窗口标签
- 大家看看这句话什么意思?(关于内部类)
- 关于自定义类中泛型方法的一个错误的问题,请教!!加精!!
- 请问大家 学习Java最重要的是什么
- 请教:设计通用的ActionForm
楼主【gplxbxc】截止到2008-07-18 23:20:10的历史汇总数据(不包括此帖):
发帖的总数量:3 发帖的总分数:0 每贴平均分数:0
回帖的总数量:19 得分贴总数量:9 回帖的得分率:47%
结贴的总数量:3 结贴的总分数:0
无满意结贴数:0 无满意结贴分:0
未结的帖子数:0 未结的总分数:0
结贴的百分比:100.00% 结分的百分比:---------------------
无满意结贴率:0.00 % 无满意结分率:---------------------
敬礼!
请楼主把代码copy TO eclips 格式化后。代码注释加上
package com.deitel.jhtp4.ch16;// Java core packages
import java.awt.*;// Java extension packages
import javax.swing.*;public class BankUI extends JPanel { // label text for GUI
protected final static String names[] = { "Account number",
"First name", "Last name", "Balance",
"Transaction Amount" }; // GUI components; protected for future subclass access
protected JLabel labels[];
protected JTextField fields[];
protected JButton doTask1, doTask2;
protected JPanel innerPanelCenter, innerPanelSouth; // number of text fields in GUI
protected int size; // constants representing text fields in GUI
public static final int ACCOUNT = 0, FIRSTNAME = 1,
LASTNAME = 2, BALANCE = 3, TRANSACTION = 4; // Set up GUI. Constructor argument of 4 creates four rows
// of GUI components. Constructor argument of 5 (used in a
// later program) creates five rows of GUI components.
public BankUI( int mySize )
{
size = mySize;
labels = new JLabel[ size ];
fields = new JTextField[ size ]; // create labels
for ( int count = 0; count < labels.length; count++ )
labels[ count ] = new JLabel( names[ count ] );
// create text fields
for ( int count = 0; count < fields.length; count++ )
fields[ count ] = new JTextField(); // create panel to lay out labels and fields
innerPanelCenter = new JPanel();
innerPanelCenter.setLayout( new GridLayout( size, 2 ) ); // attach labels and fields to innerPanelCenter
for ( int count = 0; count < size; count++ ) {
innerPanelCenter.add( labels[ count ] );
innerPanelCenter.add( fields[ count ] );
}
// create generic buttons; no labels or event handlers
doTask1 = new JButton();
doTask2 = new JButton(); // create panel to lay out buttons and attach buttons
innerPanelSouth = new JPanel();
innerPanelSouth.add( doTask1 );
innerPanelSouth.add( doTask2 ); // set layout of this container and attach panels to it
setLayout( new BorderLayout() );
add( innerPanelCenter, BorderLayout.CENTER );
add( innerPanelSouth, BorderLayout.SOUTH ); // validate layout
validate(); } // end constructor // return reference to generic task button doTask1
public JButton getDoTask1Button()
{
return doTask1;
} // return reference to generic task button doTask2
public JButton getDoTask2Button()
{
return doTask2;
} // return reference to fields array of JTextFields
public JTextField[] getFields()
{
return fields;
} // clear content of text fields
public void clearFields()
{
for ( int count = 0; count < size; count++ )
fields[ count ].setText( "" );
} // set text field values; throw IllegalArgumentException if
// incorrect number of Strings in argument
public void setFieldValues( String strings[] )
throws IllegalArgumentException
{
if ( strings.length != size )
throw new IllegalArgumentException( "There must be " +
size + " Strings in the array" ); for ( int count = 0; count < size; count++ )
fields[ count ].setText( strings[ count ] );
} // get array of Strings with current text field contents
public String[] getFieldValues()
{
String values[] = new String[ size ]; for ( int count = 0; count < size; count++ )
values[ count ] = fields[ count ].getText(); return values;
}} // end class BankUI
package com.deitel.jhtp4.ch16;// Java core packages
import java.io.Serializable;public class AccountRecord implements Serializable {
private int account;
private String firstName;
private String lastName;
private double balance;
// no-argument constructor calls other constructor with
// default values
public AccountRecord()
{
this( 0, "", "", 0.0 );
}
// initialize a record
public AccountRecord( int acct, String first,
String last, double bal )
{
setAccount( acct );
setFirstName( first );
setLastName( last );
setBalance( bal );
} // set account number
public void setAccount( int acct )
{
account = acct;
} // get account number
public int getAccount()
{
return account;
}
// set first name
public void setFirstName( String first )
{
firstName = first;
} // get first name
public String getFirstName()
{
return firstName;
}
// set last name
public void setLastName( String last )
{
lastName = last;
} // get last name
public String getLastName()
{
return lastName;
}
// set balance
public void setBalance( double bal )
{
balance = bal;
} // get balance
public double getBalance()
{
return balance;
}} // end class AccountRecord
// The objects are written sequentially to a file.// Java core packages
import java.io.*;
import java.awt.*;
import java.awt.event.*;// Java extension packages
import javax.swing.*;// Deitel packages
import com.deitel.jhtp4.ch16.BankUI;
import com.deitel.jhtp4.ch16.AccountRecord;public class CreateSequentialFile extends JFrame {
private ObjectOutputStream output;
private BankUI userInterface;
private JButton enterButton, openButton; // set up GUI
public CreateSequentialFile()
{
super( "Creating a Sequential File of Objects" ); // create instance of reusable user interface
userInterface = new BankUI( 4 ); // four textfields
getContentPane().add(
userInterface, BorderLayout.CENTER );
// get reference to generic task button doTask1 in BankUI
// and configure button for use in this program
openButton = userInterface.getDoTask1Button();
openButton.setText( "Save into File ..." ); // register listener to call openFile when button pressed
openButton.addActionListener( // anonymous inner class to handle openButton event
new ActionListener() { // call openFile when button pressed
public void actionPerformed( ActionEvent event )
{
openFile();
} } // end anonymous inner class ); // end call to addActionListener // get reference to generic task button doTask2 in BankUI
// and configure button for use in this program
enterButton = userInterface.getDoTask2Button();
enterButton.setText( "Enter" );
enterButton.setEnabled( false ); // disable button // register listener to call addRecord when button pressed
enterButton.addActionListener( // anonymous inner class to handle enterButton event
new ActionListener() { // call addRecord when button pressed
public void actionPerformed( ActionEvent event )
{
addRecord();
} } // end anonymous inner class ); // end call to addActionListener // register window listener to handle window closing event
addWindowListener( // anonymous inner class to handle windowClosing event
new WindowAdapter() { // add current record in GUI to file, then close file
public void windowClosing( WindowEvent event )
{
if ( output != null )
addRecord(); closeFile();
} } // end anonymous inner class ); // end call to addWindowListener setSize( 300, 200 );
show(); } // end CreateSequentialFile constructor // allow user to specify file name
private void openFile()
{
// display file dialog, so user can choose file to open
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(
JFileChooser.FILES_ONLY );
int result = fileChooser.showSaveDialog( this ); // if user clicked Cancel button on dialog, return
if ( result == JFileChooser.CANCEL_OPTION )
return; // get selected file
File fileName = fileChooser.getSelectedFile();
// display error if invalid
if ( fileName == null ||
fileName.getName().equals( "" ) )
JOptionPane.showMessageDialog( this,
"Invalid File Name", "Invalid File Name",
JOptionPane.ERROR_MESSAGE ); else { // open file
try {
output = new ObjectOutputStream(
new FileOutputStream( fileName ) ); openButton.setEnabled( false );
enterButton.setEnabled( true );
} // process exceptions from opening file
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this,
"Error Opening File", "Error",
JOptionPane.ERROR_MESSAGE );
}
}
} // end method openFile // close file and terminate application
private void closeFile()
{
// close file
try {
output.close(); System.exit( 0 );
} // process exceptions from closing file
catch( IOException ioException ) {
JOptionPane.showMessageDialog( this,
"Error closing file", "Error",
JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
}
} // add record to file
public void addRecord()
{
int accountNumber = 0;
AccountRecord record;
String fieldValues[] = userInterface.getFieldValues();
// if account field value is not empty
if ( ! fieldValues[ BankUI.ACCOUNT ].equals( "" ) ) { // output values to file
try {
accountNumber = Integer.parseInt(
fieldValues[ BankUI.ACCOUNT ] ); if ( accountNumber > 0 ) { // create new record
record = new AccountRecord( accountNumber,
fieldValues[ BankUI.FIRSTNAME ],
fieldValues[ BankUI.LASTNAME ],
Double.parseDouble(
fieldValues[ BankUI.BALANCE ] ) ); // output record and flush buffer
output.writeObject( record );
output.flush();
} // clear textfields
userInterface.clearFields();
} // process invalid account number or balance format
catch ( NumberFormatException formatException ) {
JOptionPane.showMessageDialog( this,
"Bad account number or balance",
"Invalid Number Format",
JOptionPane.ERROR_MESSAGE );
} // process exceptions from file output
catch ( IOException ioException ) {
closeFile();
} } // end if } // end method addRecord // execute application; CreateSequentialFile constructor
// displays window
public static void main( String args[] )
{
new CreateSequentialFile();
}} // end class CreateSequentialFile
try {
if(output!=null)
output.close();
System.exit(0);
} catch (IOException ioException) {
JOptionPane.showMessageDialog(this, "Error closing file", "Error",
JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}就是
output.close();
改为
if(output!=null)output.close();output为null的时候用close()方法当然会出现异常拉。