Registering Listener
===Oracle 10gR2 RAC - Nodes-4 - Redhat Linux AS4===
Hi All,
$ crs_stat -t | grep LISTENER
NAME=ora.rcorprod01.LISTENER_RCORPROD01.lsnr
NAME=ora.rcorprod01.LISTENER_RCORPROD01_DB2.lsnr
NAME=ora.rcorprod01.LISTENER_RCORPROD01_DB3.lsnr
NAME=ora.rcorprod02.LISTENER_RCORPROD02.lsnr
NAME=ora.rcorprod02.LISTENER_RCORPROD02_DB2.lsnr
NAME=ora.rcorprod02.LISTENER_RCORPROD02_DB3.lsnr
NAME=ora.rcorprod03.LISTENER_RCORPROD03.lsnr
NAME=ora.rcorprod03.LISTENER_RCORPROD03_DB2.lsnr
NAME=ora.rcorprod03.LISTENER_RCORPROD03_DB3.lsnr
NAME=ora.rcorprod04.LISTENER_RCORPROD04.lsnr
NAME=ora.rcorprod04.LISTENER_RCORPROD04_DB2.lsnr
NAME=ora.rcorprod04.LISTENER_RCORPROD04_DB3.lsnr
I have another ORACLE_HOME with another listener LISTENER_RCORPROD01_DB1. How do I add/register this listener to crs? I tried srvctl add listener -h but didn't help. I have to manually start this particular listener on all the nodes everytime the server reboots.
Also, Is there a document to explain all the usage options of srvctl?
Thanks
Hi
You can use the netca gui tool in order for your listener to be registered in the OCR.
Thanks,
Anil
Similar Messages
-
Hi, I need to send and XML file to a different system everytime a user is created in the portal, there's any way to create a listener for every user is created in the UME?
I have seen some classes like PrincipalListener in the UME API but there's no documentation about how to use these classes.
Regards.Hi Pablo,
ZAR files are from the old EP5 days - are you on EP5?!?!
From http://help.sap.com/ep/EP50sp5Glossary.htm :
<i>Service Archive file
Portal Architecture (EP-PIN-ARC)
The distribution format of a portal service. It is a zip archive (having a *.zar extension) with a defined directory structure and it contains a descriptor file, called service.xml, as well as Java classes and other files.</i>
It's more than two years ago that I've deployed my last ZAR, so sorry, in that case I cannot help you further.
If you are on EP6, you obviously are using the wrong wizards. Anyhow, in this case see http://help.sap.com/saphelp_nw04/helpdata/en/df/e6b74253ffda11e10000000a155106/frameset.htm
Hope it helps
Detlev -
J2Se receiver File adapter-HTTP 503 no listener registered for service
Hi,
We are using J2Se file adapter for one the interfaces and the logs of the J2se adapter engine has shown the following error-
Error: com.sap.aii.messaging.net.TransportException: HTTP 503 no listener registered for service /file/example_outbound
at com.sap.aii.messaging.net.HTTPRequest.run(ServerHttpImpl.java:416)
I checked with the J2SE File/FTP receiver adapter configuration given at help.sap and found the following the following info related to the error-
Specifications for addressing by the Integration Engine
○ XI.httpPort=<port_no>
<port_no>specifies the HTTP server port that receives the messages from the Integration Engine.
○ XI.httpService=<service>
<service> describes the service part of the address where the Integration Engine must send its messages.
These specifications are mandatory.
If, for example, you have specified XI.httpPort=1234 and XI.httpService=/file/Receiver, the end point address of the file/FTP adapter in the Integration Engine must be specified as follows:
http://<fileadapterhost>:1234/file/Receiver
The end point address must be extended as follows for the Integration Engine in Release 1.0:
http://<fileadapterhost>:1234/file/Receiver?action=execute&pipelineid=Receiver
If the Integration Engine message is sent to a non-specified adapter service, the system displays the following error message:
*No registered listener for <Service> found*
The system displays the same message if the adapter is initialized, but has not been started (status STOPPED or INITIALIZED).
Where I need to check this Integration engine address specifications. I have't found any of the above code in the adapter configuration which we are using presently.The interface is running successfully before but thrown this error now.
Please reply me if some one has faced similar issue and get it resolved.Hi
How was this issue resolved? I have the same problem.
I only have two receivers - the deafult j2se file receiver and my newly created one which used the default as a template. The ports and service's are different.
I've even tried deleting my custom receive adapter and using only the default one but i still get that error. -
Help needed with passing data between classes, graph building application?
Good afternoon please could you help me with a problem with my application, my head is starting to hurt?
I have run into some difficulties when trying to build an application that generates a linegraph?
Firstly i have a gui that the client will enter the data into a text area call jta; this data is tokenised and placed into a format the application can use, and past to a seperate class that draws the graph?
I think the problem lies with the way i am trying to put the data into co-ordinate form (x,y) as no line is being generated.
The following code is from the GUI:
+public void actionPerformed(ActionEvent e) {+
+// Takes data and provides program with CoOrdinates+
int[][]data = createData();
+// Set the data data to graph for display+
grph.showGrph(data);
+// Show the frame+
grphFrame.setVisible(true);
+}+
+/** set the data given to the application */+
+private int[][] createData() {+
+ //return data;+
+ String rawData = jta.getText();+
+ StringTokenizer tokens = new StringTokenizer(rawData);+
+ List list = new LinkedList();+
+ while (tokens.hasMoreElements()){+
+ String number = "";+
+ String token = tokens.nextToken();+
+ for (int i=0; i<token.length(); i++){+
+ if (Character.isDigit(token.charAt(i))){+
+ number += token.substring(i, i+1);+
+ }+
+ } +
+ }+
+ int [][]data = new int[list.size()/2][2];+
+ int index = -2;+
+ for (int i=0; i<data.length;i++){+
+ index += 2;+
+ data[0] = Integer.parseInt(+
+ (list.get(index).toString()));+
+ data[i][1] = Integer.parseInt(+
+ (list.get(index +1).toString()));+
+ }+
+ return data;+
The follwing is the coding for drawing the graph?
+public void showGrph(int[][] data) {+
this.data = data;
repaint();
+} +
+/** Paint the graph */+
+protected void paintComponent(Graphics g) {+
+//if (data == null)+
+ //return; // No display if data is null+
super.paintComponent(g);
+// x is the start position for the first point+
int x = 30;
int y = 30;
for (int i = 0; i < data.length; i+) {+
+g.drawLine(data[i][0],data[i][1],data[i+1][0],data[i+1][1]);+
+}+
+}+Thanks for that tip!
package LineGraph;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.util.List;
public class GUI extends JFrame
implements ActionListener {
private JTextArea Filejta;
private JTextArea jta;
private JButton jbtShowGrph = new JButton("Show Chromatogram");
public JButton jbtExit = new JButton("Exit");
public JButton jbtGetFile = new JButton("Search File");
private Grph grph = new Grph();
private JFrame grphFrame = new JFrame(); // Create a new frame to hold the Graph panel
public GUI() {
JScrollPane pane = new JScrollPane(Filejta = new JTextArea("Default file location: - "));
pane.setPreferredSize(new Dimension(350, 20));
Filejta.setWrapStyleWord(true);
Filejta.setLineWrap(true);
// Store text area in a scroll pane
JScrollPane scrollPane = new JScrollPane(jta = new JTextArea("\n\n Type in file location and name and press 'Search File' button: - "
+ "\n\n\n Data contained in the file will be diplayed in this Scrollpane "));
scrollPane.setPreferredSize(new Dimension(425, 300));
jta.setWrapStyleWord(true);
jta.setLineWrap(true);
// Place scroll pane and button in the frame
JPanel jpButtons = new JPanel();
jpButtons.setLayout(new FlowLayout());
jpButtons.add(jbtShowGrph);
jpButtons.add(jbtExit);
JPanel searchFile = new JPanel();
searchFile.setLayout(new FlowLayout());
searchFile.add(pane);
searchFile.add(jbtGetFile);
add (searchFile, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
add(jpButtons, BorderLayout.SOUTH);
// Exit Program
jbtExit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
// Read Files data contents
jbtGetFile.addActionListener(new ActionListener(){
public void actionPerformed( ActionEvent e) {
String FileLoc = Filejta.getText();
LocateFile clientsFile;
clientsFile = new LocateFile(FileLoc);
if (FileLoc != null){
String filePath = clientsFile.getFilePath();
String filename = clientsFile.getFilename();
String DocumentType = clientsFile.getDocumentType();
public String getFilecontents(){
String fileString = "\t\tThe file contains the following data:";
return fileString;
// Register listener // Create a new frame to hold the Graph panel
jbtShowGrph.addActionListener(this);
grphFrame.add(grph);
grphFrame.pack();
grphFrame.setTitle("Chromatogram showing data contained in file \\filename");
/** Handle the button action */
public void actionPerformed(ActionEvent e) {
// Takes data and provides program with CoOrdinates
int[][]data = createData();
// Set the data data to graph for display
grph.showGrph(data);
// Show the frame
grphFrame.setVisible(true);
/** set the data given to the application */
private int[][] createData() {
String rawData = jta.getText();
StringTokenizer tokens = new StringTokenizer(rawData);
List list = new LinkedList();
while (tokens.hasMoreElements()){
String number = "";
String token = tokens.nextToken();
for (int i=0; i<token.length(); i++){
if (Character.isDigit(token.charAt(i))){
number += token.substring(i, i+1);
int [][]data = new int[list.size()/2][2];
int index = -2;
for (int i=0; i<data.length;i++){
index += 2;
data[0] = Integer.parseInt(
(list.get(index).toString()));
data[i][1] = Integer.parseInt(
(list.get(index +1).toString()));
return data;
public static void main(String[] args) {
GUI frame = new GUI();
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Clients Data Retrival GUI");
frame.pack();
frame.setVisible(true);
package LineGraph;
import javax.swing.*;
import java.awt.*;
public class Grph extends JPanel {
private int[][] data;
/** Set the data and display Graph */
public void showGrph(int[][] data) {
this.data = data;
repaint();
/** Paint the graph */
protected void paintComponent(Graphics g) {
//if (data == null)
//return; // No display if data is null
super.paintComponent(g);
//Find the panel size and bar width and interval dynamically
int width = getWidth();
int height = getHeight();
//int intervalw = (width - 40) / data.length;
//int intervalh = (height - 20) / data.length;
//int individualWidth = (int)(((width - 40) / 24) * 0.60);
////int individualHeight = (int)(((height - 40) / 24) * 0.60);
// Find the maximum data. The maximum data
//int maxdata = 0;
//for (int i = 0; i < data.length; i++) {
//if (maxdata < data[i][0])
//maxdata = data[i][1];
// x is the start position for the first point
int x = 30;
int y = 30;
//draw a vertical axis
g.drawLine(20, height - 45, 20, (height)* -1);
// Draw a horizontal base line4
g.drawLine(20, height - 45, width - 20, height - 45);
for (int i = 0; i < data.length; i++) {
//int Value = i;
// Display a line
//g.drawLine(x, height - 45 - Value, individualWidth, height - 45);
g.drawLine(data[i][0],data[i][1],data[i+1][0],data[i+1][1]);
// Display a number under the x axis
g.drawString((int)(0 + i) + "", (x), height - 30);
// Display a number beside the y axis
g.drawString((int)(0 + i) + "", width - 1277, (y) + 900);
// Move x for displaying the next character
//x += (intervalw);
//y -= (intervalh);
/** Override getPreferredSize */
public Dimension getPreferredSize() {
return new Dimension(1200, 900); -
Hi,
Ok, I'll preface this by saying there's a lotta code pasted in here but it really quite an easy question, I just need to post all the code so you understand where what came from.
Now.............the question I'm trying to do is to create an applet that has 2 buttons -- each button when clicked opens an application (one is a simple calculator, the other a Mortgage calculation app). When you click one of the buttons (calc or mortgage), that app opens infront of the 2 button menu so its in "focus". The button on the 2 button menu then switches to a "hide app X" button (ie: "Mortgage", changes to "Hide Mortgage"). Thus if you click the hide button, the app that was opened is hidden, and then that "hide" button switches back to the original "app X" button. Pretty simple.
Now, I have from my text book an example that does exactly this, with the simple calculator already in it, and with another app (a traffic light thing) where the Mortgage should be in my final product. I also already have the Mortgage applet I need to insert from another book example in place of that Traffic Light portion.
Now, common sense would dictate that I should be able to just copy my code for the Mortgage applet into the example that has the 2 button menu structure, and overwrite the code I want to get rid of (the traffic light) with the mortgage code & rename the menu buttons. Right?? A simple switch of one thing for another... but therein lies my problem.
I copied all the Mortgage code in correctly over the traffic lights, switched the button names, tried to compile it but I get one error....
Exercise12_17.java:52: cannot resolve symbol
symbol : method pack ()
location: class MortgageApplet
mortgageAppletFrame.pack();I don't understand why..... mortgageAppletFrame.pack(); was a simple rewrite from lightsFrame.pack(); like every other line...... it should work. I've gone over it for 2 days......... Anyone know why it comes up as an error???
Below, in order going down is (1)my code with the 1 error I can't solve, (2)the original menu example I tried to edit, and (3)the Mortgage app code...........
Does anyone know what my error is?? Help or a hint would be greatly appreciated........ Thanks.
My erroring app.......
// Exercise12_17.java: Create multiple windows
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class Exercise12_17 extends JFrame implements ActionListener {
// Declare and create a frame: an instance of MenuDemo
MenuDemo calcFrame = new MenuDemo();
// Declare and create a frame: an instance of RadioButtonDemo
MortgageApplet mortgageAppletFrame = new MortgageApplet();
// Declare two buttons for displaying frames
private JButton jbtCalc;
private JButton jbtMortgage;
public static void main(String[] args) {
Exercise12_17 frame = new Exercise12_17();
frame.setSize( 400, 70 );
frame.setTitle("Exercise 11.8: Multiple Windows Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
public Exercise12_17() {
// Add buttons to the main frame
getContentPane().setLayout(new FlowLayout());
getContentPane().add(jbtCalc = new JButton("Simple Calculator"));
getContentPane().add(jbtMortgage = new JButton("Mortgage"));
// Register the main frame as listener for the buttons
jbtCalc.addActionListener(this);
jbtMortgage.addActionListener(this);
public void actionPerformed(ActionEvent e) {
String arg = e.getActionCommand();
if (e.getSource() instanceof JButton)
if ("Simple Calculator".equals(arg)) {
//show the MenuDemo frame
jbtCalc.setText("Hide Simple Calculator");
calcFrame.pack();
calcFrame.setVisible(true);
else if ("Hide Simple Calculator".equals(arg)) {
calcFrame.setVisible(false);
jbtCalc.setText("Simple Calculator");
else if ("Mortgage".equals(arg)) {
//show the CheckboxGroup frame
mortgageAppletFrame.pack();
jbtMortgage.setText("Hide Mortgage");
mortgageAppletFrame.setVisible(true);
else if ("Hide Mortgage".equals(arg)) {
mortgageAppletFrame.setVisible(false);
jbtMortgage.setText("Mortgage");
class MortgageApplet extends JApplet
implements ActionListener {
// Declare and create text fields for interest rate
// year, loan amount, monthly payment, and total payment
private JTextField jtfAnnualInterestRate = new JTextField();
private JTextField jtfNumOfYears = new JTextField();
private JTextField jtfLoanAmount = new JTextField();
private JTextField jtfMonthlyPayment = new JTextField();
private JTextField jtfTotalPayment = new JTextField();
// Declare and create a Compute Mortgage button
private JButton jbtComputeMortgage = new JButton("Compute Mortgage");
/** Initialize user interface */
public void init() {
// Set properties on the text fields
jtfMonthlyPayment.setEditable(false);
jtfTotalPayment.setEditable(false);
// Right align text fields
jtfAnnualInterestRate.setHorizontalAlignment(JTextField.RIGHT);
jtfNumOfYears.setHorizontalAlignment(JTextField.RIGHT);
jtfLoanAmount.setHorizontalAlignment(JTextField.RIGHT);
jtfMonthlyPayment.setHorizontalAlignment(JTextField.RIGHT);
jtfTotalPayment.setHorizontalAlignment(JTextField.RIGHT);
// Panel p1 to hold labels and text fields
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(5, 2));
p1.add(new Label("Annual Interest Rate"));
p1.add(jtfAnnualInterestRate);
p1.add(new Label("Number of Years"));
p1.add(jtfNumOfYears);
p1.add(new Label("Loan Amount"));
p1.add(jtfLoanAmount);
p1.add(new Label("Monthly Payment"));
p1.add(jtfMonthlyPayment);
p1.add(new Label("Total Payment"));
p1.add(jtfTotalPayment);
p1.setBorder(new
TitledBorder("Enter interest rate, year and loan amount"));
// Panel p2 to hold the button
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout(FlowLayout.RIGHT));
p2.add(jbtComputeMortgage);
// Add the components to the applet
getContentPane().add(p1, BorderLayout.CENTER);
getContentPane().add(p2, BorderLayout.SOUTH);
// Register listener
jbtComputeMortgage.addActionListener(this);
/** Handle the "Compute Mortgage" button */
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jbtComputeMortgage) {
// Get values from text fields
double interest = (Double.valueOf(
jtfAnnualInterestRate.getText())).doubleValue();
int year =
(Integer.valueOf(jtfNumOfYears.getText())).intValue();
double loan =
(Double.valueOf(jtfLoanAmount.getText())).doubleValue();
// Create a mortgage object
Mortgage m = new Mortgage(interest, year, loan);
// Display monthly payment and total payment
jtfMonthlyPayment.setText(String.valueOf(m.monthlyPayment()));
jtfTotalPayment.setText(String.valueOf(m.totalPayment()));
class MenuDemo extends JFrame implements ActionListener {
// Text fields for Number 1, Number 2, and Result
private JTextField jtfNum1, jtfNum2, jtfResult;
// Buttons "Add", "Subtract", "Multiply" and "Divide"
private JButton jbtAdd, jbtSub, jbtMul, jbtDiv;
// Menu items "Add", "Subtract", "Multiply","Divide" and "Close"
private JMenuItem jmiAdd, jmiSub, jmiMul, jmiDiv, jmiClose;
/** Main method */
public static void main(String[] args) {
MenuDemo frame = new MenuDemo();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
/** Default constructor */
public MenuDemo() {
setTitle("Menu Demo");
// Create menu bar
JMenuBar jmb = new JMenuBar();
// Set menu bar to the frame
setJMenuBar(jmb);
// Add menu "Operation" to menu bar
JMenu operationMenu = new JMenu("Operation");
operationMenu.setMnemonic('O');
jmb.add(operationMenu);
// Add menu "Exit" in menu bar
JMenu exitMenu = new JMenu("Exit");
exitMenu.setMnemonic('E');
jmb.add(exitMenu);
// Add menu items with mnemonics to menu "Operation"
operationMenu.add(jmiAdd= new JMenuItem("Add", 'A'));
operationMenu.add(jmiSub = new JMenuItem("Subtract", 'S'));
operationMenu.add(jmiMul = new JMenuItem("Multiply", 'M'));
operationMenu.add(jmiDiv = new JMenuItem("Divide", 'D'));
exitMenu.add(jmiClose = new JMenuItem("Close", 'C'));
// Set keyboard accelerators
jmiAdd.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));
jmiSub.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
jmiMul.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_M, ActionEvent.CTRL_MASK));
jmiDiv.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.CTRL_MASK));
// Panel p1 to hold text fields and labels
JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout());
p1.add(new JLabel("Number 1"));
p1.add(jtfNum1 = new JTextField(3));
p1.add(new JLabel("Number 2"));
p1.add(jtfNum2 = new JTextField(3));
p1.add(new JLabel("Result"));
p1.add(jtfResult = new JTextField(4));
jtfResult.setEditable(false);
// Panel p2 to hold buttons
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout());
p2.add(jbtAdd = new JButton("Add"));
p2.add(jbtSub = new JButton("Subtract"));
p2.add(jbtMul = new JButton("Multiply"));
p2.add(jbtDiv = new JButton("Divide"));
// Add panels to the frame
getContentPane().setLayout(new BorderLayout());
getContentPane().add(p1, BorderLayout.CENTER);
getContentPane().add(p2, BorderLayout.SOUTH);
// Register listeners
jbtAdd.addActionListener(this);
jbtSub.addActionListener(this);
jbtMul.addActionListener(this);
jbtDiv.addActionListener(this);
jmiAdd.addActionListener(this);
jmiSub.addActionListener(this);
jmiMul.addActionListener(this);
jmiDiv.addActionListener(this);
jmiClose.addActionListener(this);
/** Handle ActionEvent from buttons and menu items */
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
// Handle button events
if (e.getSource() instanceof JButton) {
if ("Add".equals(actionCommand))
calculate('+');
else if ("Subtract".equals(actionCommand))
calculate('-');
else if ("Multiply".equals(actionCommand))
calculate('*');
else if ("Divide".equals(actionCommand))
calculate('/');
else if (e.getSource() instanceof JMenuItem) {
// Handle menu item events
if ("Add".equals(actionCommand))
calculate('+');
else if ("Subtract".equals(actionCommand))
calculate('-');
else if ("Multiply".equals(actionCommand))
calculate('*');
else if ("Divide".equals(actionCommand))
calculate('/');
else if ("Close".equals(actionCommand))
System.exit(0);
/** Calculate and show the result in jtfResult */
private void calculate(char operator) {
// Obtain Number 1 and Number 2
int num1 = (Integer.parseInt(jtfNum1.getText().trim()));
int num2 = (Integer.parseInt(jtfNum2.getText().trim()));
int result = 0;
// Perform selected operation
switch (operator) {
case '+': result = num1 + num2;
break;
case '-': result = num1 - num2;
break;
case '*': result = num1 * num2;
break;
case '/': result = num1 / num2;
// Set result in jtfResult
jtfResult.setText(String.valueOf(result));
Original 2 button menu example....
// Exercise11_8.java: Create multiple windows
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Exercise11_8 extends JFrame implements ActionListener {
// Declare and create a frame: an instance of MenuDemo
MenuDemo calcFrame = new MenuDemo();
// Declare and create a frame: an instance of RadioButtonDemo
RadioButtonDemo lightsFrame = new RadioButtonDemo();
// Declare two buttons for displaying frames
private JButton jbtCalc;
private JButton jbtLights;
public static void main(String[] args) {
Exercise11_8 frame = new Exercise11_8();
frame.setSize( 400, 70 );
frame.setTitle("Exercise 11.8: Multiple Windows Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
public Exercise11_8() {
// Add buttons to the main frame
getContentPane().setLayout(new FlowLayout());
getContentPane().add(jbtCalc = new JButton("Simple Calculator"));
getContentPane().add(jbtLights = new JButton("Traffic Lights"));
// Register the main frame as listener for the buttons
jbtCalc.addActionListener(this);
jbtLights.addActionListener(this);
public void actionPerformed(ActionEvent e) {
String arg = e.getActionCommand();
if (e.getSource() instanceof JButton)
if ("Simple Calculator".equals(arg)) {
//show the MenuDemo frame
jbtCalc.setText("Hide Simple Calculator");
calcFrame.pack();
calcFrame.setVisible(true);
else if ("Hide Simple Calculator".equals(arg)) {
calcFrame.setVisible(false);
jbtCalc.setText("Simple Calculator");
else if ("Traffic Lights".equals(arg)) {
//show the CheckboxGroup frame
lightsFrame.pack();
jbtLights.setText("Hide Traffic Lights");
lightsFrame.setVisible(true);
else if ("Hide Traffic Lights".equals(arg)) {
lightsFrame.setVisible(false);
jbtLights.setText("Traffic Lights");
class RadioButtonDemo extends JFrame
implements ItemListener {
// Declare radio buttons
private JRadioButton jrbRed, jrbYellow, jrbGreen;
// Declare a radio button group
private ButtonGroup btg = new ButtonGroup();
// Declare a traffic light display panel
private Light light;
/** Main method */
public static void main(String[] args) {
RadioButtonDemo frame = new RadioButtonDemo();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 170);
frame.setVisible(true);
/** Default constructor */
public RadioButtonDemo() {
setTitle("RadioButton Demo");
// Add traffic light panel to panel p1
JPanel p1 = new JPanel();
p1.setSize(200, 200);
p1.setLayout(new FlowLayout(FlowLayout.CENTER));
light = new Light();
light.setSize(40, 90);
p1.add(light);
// Put the radio button in Panel p2
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout());
p2.add(jrbRed = new JRadioButton("Red", true));
p2.add(jrbYellow = new JRadioButton("Yellow", false));
p2.add(jrbGreen = new JRadioButton("Green", false));
// Set keyboard mnemonics
jrbRed.setMnemonic('R');
jrbYellow.setMnemonic('Y');
jrbGreen.setMnemonic('G');
// Group radio buttons
btg.add(jrbRed);
btg.add(jrbYellow);
btg.add(jrbGreen);
// Place p1 and p2 in the frame
getContentPane().setLayout(new BorderLayout());
getContentPane().add(p1, BorderLayout.CENTER);
getContentPane().add(p2, BorderLayout.SOUTH);
// Register listeners for check boxes
jrbRed.addItemListener(this);
jrbYellow.addItemListener(this);
jrbGreen.addItemListener(this);
/** Handle checkbox events */
public void itemStateChanged(ItemEvent e) {
if (jrbRed.isSelected())
light.turnOnRed(); // Set red light
if (jrbYellow.isSelected())
light.turnOnYellow(); // Set yellow light
if (jrbGreen.isSelected())
light.turnOnGreen(); // Set green light
// Three traffic lights shown in a panel
class Light extends JPanel {
private boolean red;
private boolean yellow;
private boolean green;
/** Default constructor */
public Light() {
turnOnGreen();
/** Set red light on */
public void turnOnRed() {
red = true;
yellow = false;
green = false;
repaint();
/** Set yellow light on */
public void turnOnYellow() {
red = false;
yellow = true;
green = false;
repaint();
/** Set green light on */
public void turnOnGreen() {
red = false;
yellow = false;
green = true;
repaint();
/** Display lights */
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (red) {
g.setColor(Color.red);
g.fillOval(10, 10, 20, 20);
g.setColor(Color.black);
g.drawOval(10, 35, 20, 20);
g.drawOval(10, 60, 20, 20);
g.drawRect(5, 5, 30, 80);
else if (yellow) {
g.setColor(Color.yellow);
g.fillOval(10, 35, 20, 20);
g.setColor(Color.black);
g.drawRect(5, 5, 30, 80);
g.drawOval(10, 10, 20, 20);
g.drawOval(10, 60, 20, 20);
else if (green) {
g.setColor(Color.green);
g.fillOval(10, 60, 20, 20);
g.setColor(Color.black);
g.drawRect(5, 5, 30, 80);
g.drawOval(10, 10, 20, 20);
g.drawOval(10, 35, 20, 20);
else {
g.setColor(Color.black);
g.drawRect(5, 5, 30, 80);
g.drawOval(10, 10, 20, 20);
g.drawOval(10, 35, 20, 20);
g.drawOval(10, 60, 20, 20);
/** Set preferred size */
public Dimension getPreferredSize() {
return new Dimension(40, 90);
class MenuDemo extends JFrame implements ActionListener {
// Text fields for Number 1, Number 2, and Result
private JTextField jtfNum1, jtfNum2, jtfResult;
// Buttons "Add", "Subtract", "Multiply" and "Divide"
private JButton jbtAdd, jbtSub, jbtMul, jbtDiv;
// Menu items "Add", "Subtract", "Multiply","Divide" and "Close"
private JMenuItem jmiAdd, jmiSub, jmiMul, jmiDiv, jmiClose;
/** Main method */
public static void main(String[] args) {
MenuDemo frame = new MenuDemo();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
/** Default constructor */
public MenuDemo() {
setTitle("Menu Demo");
// Create menu bar
JMenuBar jmb = new JMenuBar();
// Set menu bar to the frame
setJMenuBar(jmb);
// Add menu "Operation" to menu bar
JMenu operationMenu = new JMenu("Operation");
operationMenu.setMnemonic('O');
jmb.add(operationMenu);
// Add menu "Exit" in menu bar
JMenu exitMenu = new JMenu("Exit");
exitMenu.setMnemonic('E');
jmb.add(exitMenu);
// Add menu items with mnemonics to menu "Operation"
operationMenu.add(jmiAdd= new JMenuItem("Add", 'A'));
operationMenu.add(jmiSub = new JMenuItem("Subtract", 'S'));
operationMenu.add(jmiMul = new JMenuItem("Multiply", 'M'));
operationMenu.add(jmiDiv = new JMenuItem("Divide", 'D'));
exitMenu.add(jmiClose = new JMenuItem("Close", 'C'));
// Set keyboard accelerators
jmiAdd.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));
jmiSub.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
jmiMul.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_M, ActionEvent.CTRL_MASK));
jmiDiv.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.CTRL_MASK));
// Panel p1 to hold text fields and labels
JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout());
p1.add(new JLabel("Number 1"));
p1.add(jtfNum1 = new JTextField(3));
p1.add(new JLabel("Number 2"));
p1.add(jtfNum2 = new JTextField(3));
p1.add(new JLabel("Result"));
p1.add(jtfResult = new JTextField(4));
jtfResult.setEditable(false);
// Panel p2 to hold buttons
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout());
p2.add(jbtAdd = new JButton("Add"));
p2.add(jbtSub = new JButton("Subtract"));
p2.add(jbtMul = new JButton("Multiply"));
p2.add(jbtDiv = new JButton("Divide"));
// Add panels to the frame
getContentPane().setLayout(new BorderLayout());
getContentPane().add(p1, BorderLayout.CENTER);
getContentPane().add(p2, BorderLayout.SOUTH);
// Register listeners
jbtAdd.addActionListener(this);
jbtSub.addActionListener(this);
jbtMul.addActionListener(this);
jbtDiv.addActionListener(this);
jmiAdd.addActionListener(this);
jmiSub.addActionListener(this);
jmiMul.addActionListener(this);
jmiDiv.addActionListener(this);
jmiClose.addActionListener(this);
/** Handle ActionEvent from buttons and menu items */
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
// Handle button events
if (e.getSource() instanceof JButton) {
if ("Add".equals(actionCommand))
calculate('+');
else if ("Subtract".equals(actionCommand))
calculate('-');
else if ("Multiply".equals(actionCommand))
calculate('*');
else if ("Divide".equals(actionCommand))
calculate('/');
else if (e.getSource() instanceof JMenuItem) {
// Handle menu item events
if ("Add".equals(actionCommand))
calculate('+');
else if ("Subtract".equals(actionCommand))
calculate('-');
else if ("Multiply".equals(actionCommand))
calculate('*');
else if ("Divide".equals(actionCommand))
calculate('/');
else if ("Close".equals(actionCommand))
System.exit(0);
/** Calculate and show the result in jtfResult */
private void calculate(char operator) {
// Obtain Number 1 and Number 2
int num1 = (Integer.parseInt(jtfNum1.getText().trim()));
int num2 = (Integer.parseInt(jtfNum2.getText().trim()));
int result = 0;
// Perform selected operation
switch (operator) {
case '+': result = num1 + num2;
break;
case '-': result = num1 - num2;
break;
case '*': result = num1 * num2;
break;
case '/': result = num1 / num2;
// Set result in jtfResult
jtfResult.setText(String.valueOf(result));
Mortgage applet code....
// MortgageApplet.java: Applet for computing mortgage payments
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class MortgageApplet extends JApplet
implements ActionListener {
// Declare and create text fields for interest rate
// year, loan amount, monthly payment, and total payment
private JTextField jtfAnnualInterestRate = new JTextField();
private JTextField jtfNumOfYears = new JTextField();
private JTextField jtfLoanAmount = new JTextField();
private JTextField jtfMonthlyPayment = new JTextField();
private JTextField jtfTotalPayment = new JTextField();
// Declare and create a Compute Mortgage button
private JButton jbtComputeMortgage = new JButton("Compute Mortgage");
/** Initialize user interface */
public void init() {
// Set properties on the text fields
jtfMonthlyPayment.setEditable(false);
jtfTotalPayment.setEditable(false);
// Right align text fields
jtfAnnualInterestRate.setHorizontalAlignment(JTextField.RIGHT);
jtfNumOfYears.setHorizontalAlignment(JTextField.RIGHT);
jtfLoanAmount.setHorizontalAlignment(JTextField.RIGHT);
jtfMonthlyPayment.setHorizontalAlignment(JTextField.RIGHT);
jtfTotalPayment.setHorizontalAlignment(JTextField.RIGHT);
// Panel p1 to hold labels and text fields
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(5, 2));
p1.add(new Label("Annual Interest Rate"));
p1.add(jtfAnnualInterestRate);
p1.add(new Label("Number of Years"));
p1.add(jtfNumOfYears);
p1.add(new Label("Loan Amount"));
p1.add(jtfLoanAmount);
p1.add(new Label("Monthly Payment"));
p1.add(jtfMonthlyPayment);
p1.add(new Label("Total Payment"));
p1.add(jtfTotalPayment);
p1.setBorder(new
TitledBorder("Enter interest rate, year and loan amount"));
// Panel p2 to hold the button
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout(FlowLayout.RIGHT));
p2.add(jbtComputeMortgage);
// Add the components to the applet
getContentPane().add(p1, BorderLayout.CENTER);
getContentPane().add(p2, BorderLayout.SOUTH);
// Register listener
jbtComputeMortgage.addActionListener(this);
/** Handle the "Compute Mortgage" button */
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jbtComputeMortgage) {
// Get values from text fields
double interest = (Double.valueOf(
jtfAnnualInterestRate.getText())).doubleValue();
int year =
(Integer.valueOf(jtfNumOfYears.getText())).intValue();
double loan =
(Double.valueOf(jtfLoanAmount.getText())).doubleValue();
// Create a mortgage object
Mortgage m = new Mortgage(interest, year, loan);
// Display monthly payment and total payment
jtfMonthlyPayment.setText(String.valueOf(m.monthlyPayment()));
jtfTotalPayment.setText(String.valueOf(m.totalPayment()));
}Does it have to be an applet?
If you want the same behaviour as in the code with traffic lights, change
class MortgageApplet extends JApplet implements ActionListener {
to
class MortgageApplet extends JFrame implements ActionListener {
and change
public void init() {
to
public MortgageApplet() { -
Why does this class not read and write at same time???
I had another thread where i was trying to combine two class files together
http://forum.java.sun.com/thread.jspa?threadID=5146796
I managed to do it myself but when i run the file it does not work right. If i write a file then try and open the file it says there are no records in the file, but if i close the gui down and open the file everything get read in as normal can anybody tell me why?
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import bank.BankUI;
import bank.*;
public class testing extends JFrame {
private ObjectOutputStream output;
private BankUI userInterface;
private JButton SaveToFile, SaveAs, Exit; //////////savetofile also saves to store need to split up and have 2 buttons
//private Store store; MIGHT BE SOMETHING TO DO WITH THIS AS I HAD TO COMMENT THIS STORE OUT TO GET IT WORKING AS STORE IS USED BELOW
private Employee record;
//////////////////////////////////////from read
private ObjectInputStream input;
private JButton nextButton, openButton, nextRecordButton ;
private Store store = new Store(100);
private Employee employeeList[] = new Employee[100];
private int count = 0, next = 0;
/////////////////////////////////////////////from read end
// set up GUI
public testing()
super( "Employee Data" ); // appears in top of gui
// create instance of reusable user interface
userInterface = new BankUI( 9 ); // nine textfields
getContentPane().add( userInterface, BorderLayout.CENTER );
// configure button doTask1 for use in this program
SaveAs = userInterface.getSaveAsButton();
SaveAs.setText( "Save as.." );
//////////////////from read
openButton = userInterface.getOpenFileButton();
openButton.setText( "Open File" );
openButton.addActionListener(
// anonymous inner class to handle openButton event
new ActionListener() {
// close file and terminate application
public void actionPerformed( ActionEvent event )
openFile();
} // end anonymous inner class
); // end call to addActionListener
// register window listener for window closing event
addWindowListener(
// anonymous inner class to handle windowClosing event
new WindowAdapter() {
// close file and terminate application
public void windowClosing( WindowEvent event )
if ( input != null )
closeFile();
System.exit( 0 );
} // end anonymous inner class
); // end call to addWindowListener
// get reference to generic task button doTask2 from BankUI
nextButton = userInterface.getDoTask2Button();
nextButton.setText( "Next Record" );
nextButton.setEnabled( false );
// register listener to call readRecord when button pressed
nextButton.addActionListener(
// anonymous inner class to handle nextRecord event
new ActionListener() {
// call readRecord when user clicks nextRecord
public void actionPerformed( ActionEvent event )
readRecord();
} // end anonymous inner class
); // end call to addActionListener
//get reference to generic task button do Task3 from BankUI
// get reference to generic task button doTask3 from BankUI
nextRecordButton = userInterface.getDoTask3Button();
nextRecordButton.setText( "Get Next Record" );
nextRecordButton.setEnabled( false );
// register listener to call readRecord when button pressed
nextRecordButton.addActionListener(
// anonymous inner class to handle nextRecord event
new ActionListener() {
// call readRecord when user clicks nextRecord
public void actionPerformed( ActionEvent event )
getNextRecord();
} // end anonymous inner class
); // end call to addActionListener
///////////from read end
// register listener to call openFile when button pressed
SaveAs.addActionListener(
// anonymous inner class to handle openButton event
new ActionListener() {
// call openFile when button pressed
public void actionPerformed( ActionEvent event )
SaveLocation();
} // end anonymous inner class
); // end call to addActionListener
// configure button doTask2 for use in this program
SaveToFile = userInterface.getSaveStoreToFileButton();
SaveToFile.setText( "Save to store and to file need to split this task up" );
SaveToFile.setEnabled( false ); // disable button
// register listener to call addRecord when button pressed
SaveToFile.addActionListener(
// anonymous inner class to handle enterButton event
new ActionListener() {
// call addRecord when button pressed
public void actionPerformed( ActionEvent event )
addRecord(); // NEED TO SPLIT UP SO DONT DO BOTH
} // end anonymous inner class
); // end call to addActionListener
Exit = userInterface.getExitAndSaveButton();
Exit.setText( "Exit " );
Exit.setEnabled( false ); // disable button
// register listener to call addRecord when button pressed
Exit.addActionListener(
// anonymous inner class to handle enterButton event
new ActionListener() {
// call addRecord when button pressed
public void actionPerformed( ActionEvent event )
addRecord(); // adds record to to file
closeFile(); // closes everything
} // 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( 600, 500 );
setVisible( true );
store = new Store(100);
} // end CreateSequentialFile constructor
// allow user to specify file name
////////////////from read
// enable user to select file to open
private void openFile()
// display file dialog so user can select file to open
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
int result = fileChooser.showOpenDialog( this );
// if user clicked Cancel button on dialog, return
if ( result == JFileChooser.CANCEL_OPTION )
return;
// obtain selected file
File fileName = fileChooser.getSelectedFile();
// display error if file name invalid
if ( fileName == null || fileName.getName().equals( "" ) )
JOptionPane.showMessageDialog( this, "Invalid File Name",
"Invalid File Name", JOptionPane.ERROR_MESSAGE );
else {
// open file
try {
input = new ObjectInputStream(
new FileInputStream( fileName ) );
openButton.setEnabled( false );
nextButton.setEnabled( true );
// process exceptions opening file
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this, "Error Opening File",
"Error", JOptionPane.ERROR_MESSAGE );
} // end else
} // end method openFile
public void readRecord() // need to merger with next record
Employee record;
// input the values from the file
try {
record = ( Employee ) input.readObject();
employeeList[count++]= record;
store.add(record);/////////ADDS record to Store
store.displayAll();
System.out.println("Count is " + store.getCount());
// create array of Strings to display in GUI
String values[] = {
String.valueOf(record.getName()),
String.valueOf(record.getGender()),
String.valueOf( record.getDateOfBirth()),
String.valueOf( record.getID()),
String.valueOf( record.getStartDate()),
String.valueOf( record.getSalary()),
String.valueOf( record.getAddress()),
String.valueOf( record.getNatInsNo()),
String.valueOf( record.getPhone())
// i added all those bits above split onto one line to look neater
// display record contents
userInterface.setFieldValues( values );
// display message when end-of-file reached
catch ( EOFException endOfFileException ) {
nextButton.setEnabled( false );
nextRecordButton.setEnabled( true );
JOptionPane.showMessageDialog( this, "No more records in file",
"End of File", JOptionPane.ERROR_MESSAGE );
// display error message if class is not found
catch ( ClassNotFoundException classNotFoundException ) {
JOptionPane.showMessageDialog( this, "Unable to create object",
"Class Not Found", JOptionPane.ERROR_MESSAGE );
// display error message if cannot read due to problem with file
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this,
"Error during read from file",
"Read Error", JOptionPane.ERROR_MESSAGE );
} // end method readRecord
private void getNextRecord()
Employee record = employeeList[next++%count];//cycles throught accounts
//create aray of string to display in GUI
String values[] = {String.valueOf(record.getName()),
String.valueOf(record.getGender()),
String.valueOf( record.getStartDate() ), String.valueOf( record.getAddress()),
String.valueOf( record.getNatInsNo()),
String.valueOf( record.getPhone()),
String.valueOf( record.getID() ),
String.valueOf( record.getDateOfBirth() ),
String.valueOf( record.getSalary() ) };
//display record contents
userInterface.setFieldValues(values);
//display record content
///////////////////////////////////from read end
private void SaveLocation()
// 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;
File fileName = fileChooser.getSelectedFile(); // get selected file
// 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 ) );
SaveAs.setEnabled( false );
SaveToFile.setEnabled( true );
Exit.setEnabled( true );
// process exceptions from opening file
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this, "Error Opening File",
"Error", JOptionPane.ERROR_MESSAGE );
} // end else
} // end method openFile
// close file and terminate application
private void closeFile()
// close file
try {
//you want to cycle through each recordand add them to store here.
int storeSize = store.getCount();
for (int i = 0; i<storeSize;i++)
output.writeObject(store.elementAt(i));
output.close();
input.close();// from read!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
System.exit( 0 );
// process exceptions from closing file
catch( IOException ioException ) {
JOptionPane.showMessageDialog( this, "Error closing file",
"Error", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
} // end method closeFile
// add record to file
public void addRecord()
int employeeNumber = 0;
String fieldValues[] = userInterface.getFieldValues();
// if account field value is not empty
if ( ! fieldValues[ BankUI.IDNUMBER ].equals( "" ) ) {
// output values to file
try {
employeeNumber = Integer.parseInt(
fieldValues[ BankUI.IDNUMBER ] );
String dob = fieldValues[ BankUI.DOB ];
String[] dateofBirth = dob.split ("-"); // what used to put between number chnage to /
String sDate = fieldValues[ BankUI.START ];
String[] startDate = sDate.split ("-");
String sex = fieldValues[ BankUI.GENDER ];
char gender = (sex.charAt(0)); // check if m or f prob check in employee
if ( employeeNumber >= 0 ) {
/* create new record =String name, char gender, Date dob, String add, String nin, String phone, String id, Date start, float salary*/
record = new Employee(
fieldValues[ BankUI.NAME ],
gender,
new Date( Integer.parseInt(dateofBirth[0]),
Integer.parseInt(dateofBirth[1]),
Integer.parseInt(dateofBirth[2])),
fieldValues[ BankUI.ADDRESS ],
fieldValues[ BankUI.NATINTNO ],
fieldValues[ BankUI.PHONE ],
fieldValues[ BankUI.IDNUMBER ],
new Date( Integer.parseInt(startDate[0]),
Integer.parseInt(startDate[1]),
Integer.parseInt(startDate[2])),
Float.parseFloat( fieldValues[ BankUI.SALARY ] ));
if (!store.isFull())
store.add(record);
else
JOptionPane.showMessageDialog( this, "The Store is full you cannot add\n"+
"anymore employees. \nPlease Save Current File and Create a New File." );
System.out.println("Store full");
store.displayAll();
System.out.println("Count is " + store.getCount());
// output record and flush buffer
//output.writeObject( record );
output.flush();
else
JOptionPane.showMessageDialog( this,
"Account number must be greater than 0",
"Bad account number", JOptionPane.ERROR_MESSAGE );
// clear textfields
userInterface.clearFields();
} // end try
// process invalid account number or balance format
catch ( NumberFormatException formatException ) {
JOptionPane.showMessageDialog( this,
"Bad ID number, Date or Salary", "Invalid Number Format",
JOptionPane.ERROR_MESSAGE );
// process exceptions from file output
catch ( ArrayIndexOutOfBoundsException ArrayException ) {
JOptionPane.showMessageDialog( this, "Error with Start Date or Date of Birth\nPlease enter like: 01-01-2001",
"IO Exception", JOptionPane.ERROR_MESSAGE );
// process exceptions from file output
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this, "Error writing to file",
"IO Exception", JOptionPane.ERROR_MESSAGE );
closeFile();
} // end if
} // end method addRecord
public static void main( String args[] )
new testing();
} // end class CreateSequentialFileSure you can read and write at the same time. But normally you would be reading from one place and writing to another place.
I rather regret avoiding the OP's earlier post asking how to combine two classes. I looked at the two classes posted and realized the best thing to do was actually to break them into more classes. But I also realized it was going to be a big job explaining why and how, and I just don't have the patience for that sort of thing.
So now we have a Big Ball Of Tar™ and I feel partly responsible. -
Randomaccessfile, writing an update to the file?
Hi,
I'm working on an app that uses a randomaccessfile (student.dat) and I have it so it will write info to the dat file & I can search thru what I entered..... now I need to add the ability to update a record in the dat. The student info is just basic name & address. So I need to be able to update an address change for a given record.
I looked at the documentation online but I'm not understanding how you capture the reference point in the file and modify it.... does anyone have a good example or does anyone out there know how to explain how to do it to me??
My file is here below that I need to add the update functionality to (and the 2 accompaning files)...... I already inserted my Update button on the second panel where it needs to reside. Now I need to add the update functionality to the button.
Anyone have any suggestions/explanations on how to add this fnctionality or know a working example I can reference?? Any help would be great appreciated.... thanks.
// StudentRecords.java: Store and read data
// using RandomAccessFile
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class StudentRecords extends JFrame {
// Create a tabbed pane to hold two panels
private JTabbedPane jtpStudent = new JTabbedPane();
// Random access file for access the student.dat file
private RandomAccessFile raf;
/** Main method */
public static void main(String[] args) {
StudentRecords frame = new StudentRecords();
frame.pack();
frame.setTitle("Test RandomAccessFile");
frame.setVisible(true);
/** Default constructor */
public StudentRecords() {
// Open or create a random access file
try {
raf = new RandomAccessFile("student.dat", "rw");
catch(IOException ex) {
System.out.print("Error: " + ex);
System.exit(0);
// Place buttons in the tabbed pane
jtpStudent.add(new RegisterStudent(raf), "Register Student");
jtpStudent.add(new ViewStudent(raf), "View Student");
// Add the tabbed pane to the frame
getContentPane().add(jtpStudent);
// Register student panel
class RegisterStudent extends JPanel implements ActionListener {
// Button for registering a student
private JButton jbtRegister;
// Student information panel
private StudentPanel studentPanel;
// Random access file
private RandomAccessFile raf;
public RegisterStudent(RandomAccessFile raf) {
// Pass raf to RegisterStudent Panel
this.raf = raf;
// Add studentPanel and jbtRegister in the panel
setLayout(new BorderLayout());
add(studentPanel = new StudentPanel(),
BorderLayout.CENTER);
add(jbtRegister = new JButton("Register"),
BorderLayout.SOUTH);
// Register listener
jbtRegister.addActionListener(this);
/** Handle button actions */
// JFileChooser fc;
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jbtRegister) {
Student student = studentPanel.getStudent();
try {
raf.seek(raf.length());
student.writeStudent(raf);
catch(IOException ex) {
System.out.print("Error: " + ex);
// View student panel
class ViewStudent extends JPanel implements ActionListener {
// Buttons for viewing student information
private JButton jbtFirst, jbtNext, jbtPrevious, jbtLast, jbtUpdate;
// Random access file
private RandomAccessFile raf = null;
// Current student record
private Student student = new Student();
// Create a student panel
private StudentPanel studentPanel = new StudentPanel();
// File pointer in the random access file
private long lastPos;
private long currentPos;
public ViewStudent(RandomAccessFile raf) {
// Pass raf to ViewStudent
this.raf = raf;
// Panel p to hold four navigator buttons
JPanel p = new JPanel();
p.setLayout(new FlowLayout(FlowLayout.LEFT));
p.add(jbtFirst = new JButton("First"));
p.add(jbtNext = new JButton("Next"));
p.add(jbtPrevious = new JButton("Previous"));
p.add(jbtLast = new JButton("Last"));
p.add(jbtUpdate = new JButton("Update"));
// Add panel p and studentPanel to ViewPanel
setLayout(new BorderLayout());
add(studentPanel, BorderLayout.CENTER);
add(p, BorderLayout.SOUTH);
// Register listeners
jbtFirst.addActionListener(this);
jbtNext.addActionListener(this);
jbtPrevious.addActionListener(this);
jbtLast.addActionListener(this);
jbtUpdate.addActionListener(this);
/** Handle navigation button actions */
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if (e.getSource() instanceof JButton) {
try {
if ("First".equals(actionCommand)) {
if (raf.length() > 0)
retrieve(0);
else if ("Next".equals(actionCommand)) {
currentPos = raf.getFilePointer();
if (currentPos < raf.length())
retrieve(currentPos);
else if ("Previous".equals(actionCommand)) {
currentPos = raf.getFilePointer();
if (currentPos > 0)
retrieve(currentPos - 2*2*Student.RECORD_SIZE);
else if ("Last".equals(actionCommand)) {
lastPos = raf.length();
if (lastPos > 0)
retrieve(lastPos - 2*Student.RECORD_SIZE);
else if ("Update".equals(actionCommand)) {
// raf.writeChars(student.dat); //HOW DO I UPDATE THE FILE????????????????
catch(IOException ex) {
System.out.print("Error: " + ex);
/** Retrieve a record at specified position */
public void retrieve(long pos) {
try {
raf.seek(pos);
student.readStudent(raf);
studentPanel.setStudent(student);
catch(IOException ex) {
System.out.print("Error: " + ex);
// This class contains static methods for reading and writing
// fixed length records
class FixedLengthStringIO {
// Read fixed number of characters from a DataInput stream
public static String readFixedLengthString(int size,
DataInput in) throws IOException {
char c[] = new char[size];
for (int i=0; i<size; i++)
c[i] = in.readChar();
return new String(c);
// Write fixed number of characters (string s with padded spaces)
// to a DataOutput stream
public static void writeFixedLengthString(String s, int size,
DataOutput out) throws IOException {
char cBuffer[] = new char[size];
s.getChars(0, s.length(), cBuffer, 0);
for (int i = s.length(); i < cBuffer.length; i++)
cBuffer[i] = ' ';
String newS = new String(cBuffer);
out.writeChars(newS);
}Student Panel....................
// StudentPanel.java: Panel for displaying student information
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
public class StudentPanel extends JPanel {
JTextField jtfName = new JTextField(32);
JTextField jtfStreet = new JTextField(32);
JTextField jtfCity = new JTextField(20);
JTextField jtfState = new JTextField(2);
JTextField jtfZip = new JTextField(5);
/** Construct a student panel */
public StudentPanel() {
// Set the panel with line border
setBorder(new BevelBorder(BevelBorder.RAISED));
// 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 StudentPanel
setLayout(new BorderLayout());
add(p1, BorderLayout.WEST);
add(p4, BorderLayout.CENTER);
/** Get student information from the text fields */
public Student getStudent() {
return new Student(jtfName.getText().trim(),
jtfStreet.getText().trim(),
jtfCity.getText().trim(),
jtfState.getText().trim(),
jtfZip.getText().trim());
/** Set student information on the text fields */
public void setStudent(Student s) {
jtfName.setText(s.getName());
jtfStreet.setText(s.getStreet());
jtfCity.setText(s.getCity());
jtfState.setText(s.getState());
jtfZip.setText(s.getZip());
}Student file............
// Student.java: Student class encapsulates student information
import java.io.*;
public class Student implements Serializable {
private String name;
private String street;
private String city;
private String state;
private String zip;
// 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;
// the total size of the record in bytes, a Unicode
// character is 2 bytes size
final static int RECORD_SIZE =
(NAME_SIZE + STREET_SIZE + CITY_SIZE + STATE_SIZE + ZIP_SIZE);
/** Default constructor */
public Student() {
/** Construct a Student with specified name, street, city, state,
and zip
public Student(String name, String street, String city,
String state, String zip) {
this.name = name;
this.street = street;
this.city = city;
this.state = state;
this.zip = zip;
/** Return name */
public String getName() {
return name;
/** Return street */
public String getStreet() {
return street;
/** Return city */
public String getCity() {
return city;
/** Return state */
public String getState() {
return state;
/** Return zip */
public String getZip() {
return zip;
/** Write a student to a data output stream */
public void writeStudent(DataOutput out) throws IOException {
FixedLengthStringIO.writeFixedLengthString(
name, NAME_SIZE, out);
FixedLengthStringIO.writeFixedLengthString(
street, STREET_SIZE, out);
FixedLengthStringIO.writeFixedLengthString(
city, CITY_SIZE, out);
FixedLengthStringIO.writeFixedLengthString(
state, STATE_SIZE, out);
FixedLengthStringIO.writeFixedLengthString(
zip, ZIP_SIZE, out);
/** Read a student from data input stream */
public void readStudent(DataInput in) throws IOException {
name = FixedLengthStringIO.readFixedLengthString(
NAME_SIZE, in);
street = FixedLengthStringIO.readFixedLengthString(
STREET_SIZE, in);
city = FixedLengthStringIO.readFixedLengthString(
CITY_SIZE, in);
state = FixedLengthStringIO.readFixedLengthString(
STATE_SIZE, in);
zip = FixedLengthStringIO.readFixedLengthString(
ZIP_SIZE, in);Advise sounds strikingly similar to what I mentioned
page b4. Look, can you post the entire class in code
tags ... and the entire file as well?@Bill,
Yes, I read yours but (sorry, its hard to answer multiple replies in these forums) but I could not understand some of what you suggested. If you look at the //???? lines I commented on your code below you'll see where I'm lost on what you are doing there. You also mentioned a "marker"... is that the currentPos thing in the code of mine, to get the current position?
Both you and Andrew suggested classes to some extent but I'm not sure how to it or what goes in it. If you look at my code paste above the buttons seem to have everything in the action, not a class, other than the register button on the other pane (which has a write method in studentpanel.java).
I'm trying to follow/implement what u guys have been suggesting... but my brain just is not wrapping around the what I should type & where..... :-( Got any further explanation/demonstration of what I should be doing?? Sorry, I'm not that skilled of a programmer yet...
int curr_ptr = 0,
prev_ptr = 0;
String marker = "ADDRS=",
address="My new address",
record = null;
while ( ( record = raf.readLine() ) != null ) { //????
curr_ptr = raf.getFilePointer();
if ( ( idx = record.indexOf("marker") ) != -1 ) { //????
record = record.substring( 0, 6 ) + address; //????
raf.seek( prev_ptr );
raf.writeBytes( record );
curr_ptr = raf.getFilePointer();
raf.seek(curr_ptr);
} -
How to find out MTS or Dedicated
I am running Oracle 8.1.7 on Sun Solaris. I have set the following in init.ora file.
mts_dispatchers="(protocol=tcp)(dispatchers=4)(connections=1000)"
mts_servers = 3
When I query the server column of v$session table I find DEDECATED for each user. Does this means the server is running in dedicated mode.
MohanHow to register listener with the database. I have configured the listener.ora file with (SERVICE = SHARED). I have set the same thing for tnsnames.ora on the client. Still I am not finding shared servers for new connections. Any idea what is going wrong.
Mohan -
Applet only runs 50% of the time in Netbeans
I run this application and 50% of the time it works and the other half it doesn't. I'm not changing any code and I noticed this happens w/ my SSCCE and the actual program. I'm using Netbeans, I right click the file and choose run.
Here's the SSCCE:
package carbuyer;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class SampleApplet extends JApplet implements ActionListener {
private JTextField jtfSellingPrice = new JTextField();
private JButton jbtComputeCost = new JButton("Compute Cost");
@Override
public void init() {
//Right align text fields
jtfSellingPrice.setHorizontalAlignment(JTextField.RIGHT);
//Panel p1 to hold labels and text fields
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(5,2));
p1.add(new Label("Selling Price: "));
p1.add(jtfSellingPrice);
p1.setBorder(new TitledBorder("Enter Selling price, trade in value, down payment, APR, and loan term"));
//Panel p2 to hold the button
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout(FlowLayout.RIGHT));
p2.add(jbtComputeCost);
//Add the components to the applet
getContentPane().add(p1,BorderLayout.CENTER);
getContentPane().add(p2,BorderLayout.SOUTH);
//Register listener
jbtComputeCost.addActionListener(this);
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
} catch (Exception ex) {
ex.printStackTrace();
/**Handle the ComputeCost button */
public void actionPerformed(ActionEvent e)
/** This method is called from within the init() method to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setLayout(new java.awt.BorderLayout());
}// </editor-fold>
// Variables declaration - do not modify
// End of variables declaration
}Here's my SSCCE to demonstrate the problem that occurs when you set the contentPane's layout to BorderLayout after adding components:
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SampleSwing {
private static void createAndShowGUI() {
JPanel mainPanel = new JPanel();
mainPanel.add(new JButton("Fubar"));
JFrame frame = new JFrame("SampleSwing Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
// Comment and uncomment the following line to see its effect:
//frame.getContentPane().setLayout(new BorderLayout());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
} -
Messages are not dequeing from the Queue
I am using Oracle Advanced Queueing.
PL/SQL API for enqueue
JMS API for Dequeue Messages asynchronously (register listener and using onMessage())
It is multi consumer queue.
The program used to work fine. Now, it has stopped. Now, we can enqueue as
many messages as we want. The subscriber does not recieve any messages. BUT,
once we disconnect subscriber and connect again, the subscriber gets all the
messages in the queue. You can repeat this N times.
I sent this java program and sql scripts to Oracle support and they ran it successfully in their environment. So it appears to be some weird environment problem.
Question:
Did anybody have problem like this?
Does anybody have any ideas about what to check in Oracle/Java client environment?
We use Java SDK 1.2.2, thin JDBC drive and Oracle 8.1.7
Thanks for reading this message.
Vlad.
nullEMON is running:
oracle 1105 1 0 Apr 28 ? 0:03 ora_emn0_wmdev
And there are two trace files, but nothing interesting inside (they don't change when I run java client):
-rw-r--r-- 1 oracle dba 107 May 2 18:01 PLSExtProc_agt_5404.trc
-rw-r--r-- 1 oracle dba 107 May 2 18:06 PLSExtProc_agt_7021.trc
PLSExtProc_agt_5404.trc
Remote HO Agent received unexpected RPC disconnect
status 1003: ncrorpi_recv_procid, called from horg.c
PLSExtProc_agt_7021.trc
Remote HO Agent received unexpected RPC disconnect
status 1003: ncrorpi_recv_procid, called from horg.c
null -
500 Internal Server Error on inbound
Hi all,
Current Version: Oracle Application Server Integration B2B, Release 10.1.2, Build B2B_10.1.2.4.0_GENERIC_091027
We have several connection with several trading partners, all are working flawlessly EXCEPT,
One particular AS2 document from one trading partner results in an error back to them as follows:
Error sending document over http to host [https://xx.xx.com/b2b/transportServlet], status code [500], reason [Internal Server Error], response from server [<HTML><HEAD><TITLE>500 Internal Server Error</TITLE></HEAD><BODY><H1>500 Internal Server Error</H1><PRE>java.lang.NullPointerException<br> at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:247)<br> at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:223)<br> at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:133)<br> at oracle.tip.transport.basic.HTTPReceiver_Stub.sendRequest(HTTPReceiver_Stub.java:87)<br> at oracle.tip.transport.basic.TransportServlet.doPost(TransportServlet.java:626)<br> at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)<br> at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)<br> at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.3.0)].server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:835)<br> at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.3.0)].server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:341)<br> at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.3.0)].server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:816)<br> at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.3.0)].server.http.AJPRequestHandler.run(AJPRequestHandler.java:231)<br> at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.3.0)].server.http.AJPRequestHandler.run(AJPRequestHandler.java:136)<br> at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.3.0)].util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:192)<br> at java.lang.Thread.run(Thread.java:534)<br></PRE></BODY></HTML>]
Nothing shows up in the console.
Looking at the logs...
- Transport Log:
RMI TCP Connection(775)-127.0.0.1: (STATUS) [IPT_HttpRecSendMessageViaCallback] A request is routed by HTTP Receiver to registered listener.
B2B Log:
RMI TCP Connection(775)-127.0.0.1: B2B - (ERROR) Error -: AIP-50083: Document protocol identification error
at oracle.tip.adapter.b2b.engine.Engine.identifyDocument(Engine.java:3283)
at oracle.tip.adapter.b2b.engine.Engine.processIncomingMessage(Engine.java:1685)
at oracle.tip.adapter.b2b.transport.InterfaceListener.onMessage(InterfaceListener.java:437)
at oracle.tip.transport.basic.HTTPReceiver.sendRequest(HTTPReceiver.java:447)
at sun.reflect.GeneratedMethodAccessor6.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:324)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:261)
at sun.rmi.transport.Transport$1.run(Transport.java:148)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:144)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:460)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:701)
at java.lang.Thread.run(Thread.java:534)
We will be switching our b2b logs to debug later this afternoon to see if it will uncover something.
Any ideas in the meantime?
Thanks for any advice.AIP-50083: Document protocol identification error
at oracle.tip.adapter.b2b.engine.Engine.identifyDocument(Engine.java:3283)
at oracle.tip.adapter.b2b.engine.Engine.processIncomingMessage(Engine.java:1685)
Above Error says : B2B is not able to identify the incoming document. Check your Inbound document. Let us know your document protocol for more details .
Rgds,
Nitesh Jain -
Tax Calulator applet again pls help urgent
why isn't it possible to pass a string and a double into GetResult below, i get a compilation error and right now i dunno how to proceed. GetRelief is supposed to calculate "relief" from textfields i/p and GetResult is suppose to calculate the "result" (minus "relief" from GetRelief). And is it the correct way to create an object as in calc = new Calculate(); below................any help would be greatly appreciated...
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class TaxCal extends Applet implements ActionListener {
private TextField income, age, child, parent, course, maid, pay;
private Button b2, b3;
private Calculate calc;
public void init() {
setBackground(Color.lightGray);
/* Create the input boxes, and make sure that the background
color is white. (On some platforms, it is automatically.) */
income = new TextField(10);
Panel incomePanel = new Panel();
incomePanel.setLayout(new BorderLayout(2,2));
incomePanel.add( new Label("Input your annual income"), BorderLayout.WEST );
incomePanel.add(income, BorderLayout.CENTER);
age = new TextField(2);
Panel agePanel = new Panel();
agePanel.setLayout(new BorderLayout(2,2));
agePanel.add( new Label("Input your age"), BorderLayout.WEST );
agePanel.add(age, BorderLayout.CENTER);
child = new TextField(2);
Panel childPanel = new Panel();
childPanel.setLayout(new BorderLayout(2,2));
childPanel.add( new Label("Number of children"), BorderLayout.WEST );
childPanel.add(child, BorderLayout.CENTER);
parent = new TextField(1);
Panel parentPanel = new Panel();
parentPanel.setLayout(new BorderLayout(2,2));
parentPanel.add( new Label("Number of parent that live with you"), BorderLayout.WEST );
parentPanel.add(parent, BorderLayout.CENTER);
course = new TextField(5);
Panel coursePanel = new Panel();
coursePanel.setLayout(new BorderLayout(2,2));
coursePanel.add( new Label("Course fee"), BorderLayout.WEST );
coursePanel.add(course, BorderLayout.CENTER);
maid = new TextField(5);
Panel maidPanel = new Panel();
maidPanel.setLayout(new BorderLayout(2,2));
maidPanel.add( new Label("Maid levy paid"), BorderLayout.WEST );
maidPanel.add(maid, BorderLayout.CENTER);
pay = new TextField(10);
pay.setEditable(false);
Panel payPanel = new Panel();
payPanel.setLayout(new BorderLayout(2,2));
payPanel.add( new Label("Please pay"), BorderLayout.WEST );
payPanel.add(pay, BorderLayout.CENTER);
Panel buttonPanel = new Panel();
buttonPanel.setLayout(new GridLayout(1,3));
Button b2 = new Button("Reset");
b2.addActionListener(this); // register listener
buttonPanel.add(b2);
Button b3 = new Button("Calculate");
b3.addActionListener(this); // register listener
buttonPanel.add(b3);
/* Set up the layout for the applet, using a GridLayout,
and add all the components that have been created. */
setLayout(new GridLayout(8,2));
add(incomePanel);
add(agePanel);
add(childPanel);
add(parentPanel);
add(coursePanel);
add(maidPanel);
add(payPanel);
add(buttonPanel);
/* Try to give the input focus to xInput, which is
the natural place for the user to start. */
income.requestFocus();
} // end init()
public TaxCal() {
calc = new Calculate();
public Insets getInsets() {
// Leave some space around the borders of the applet.
return new Insets(2,2,2,2);
// event handler for ActionEvent
public void actionPerformed (ActionEvent e) {
String s = e.getActionCommand();
if (s.equals("Calculate"))
double relief = calc.GetRelief(age.getText(), child.getText(), parent.getText(), course.getText(), maid.getText());
double result = calc.GetResult(income.getText(), relief);
pay.setText(Double.toString(relief));
else
income.setText("");
age.setText("");
child.setText("");
parent.setText("");
course.setText("");
maid.setText("");
pay.setText("");
} // end actionPerformed()
public class Calculate
private double result;
private double incomeTotal;
private double ageTotal;
private double childTotal;
private double parentTotal;
private double courseTotal;
private double maidTotal;
private double relief;
public Calculate()
relief = 0.0;
result = 0.0;
incomeTotal = 0;
ageTotal = 0;
childTotal = 0;
parentTotal = 0;
courseTotal = 0;
maidTotal = 0;
public double GetResult(String theincome, Double therelief)
incomeTotal = Double.parseDouble(theincome);
relief = therelief;
incomeTotal =- relief;
if (incomeTotal <= 7500)
result = incomeTotal * .02;
else if (incomeTotal > 7500 && incomeTotal <= 20000)
result = 150 + ((incomeTotal - 7500) * .05);
else if (incomeTotal > 20000 && incomeTotal <= 35000)
result = ((incomeTotal - 20000) * .08) + 775;
else if (incomeTotal> 35000 && incomeTotal <= 50000)
result = ((incomeTotal - 35000) * .12) + 1975;
else if (incomeTotal > 50000 && incomeTotal <= 75000)
result = ((incomeTotal - 50000) * .16) + 3775;
else if (incomeTotal > 75000 && incomeTotal <= 100000)
result = ((incomeTotal - 75000) * .2) + 7775;
else if (incomeTotal > 100000 && incomeTotal <= 150000)
result = ((incomeTotal - 100000) * .22) + 12775;
else if (incomeTotal > 150000 && incomeTotal <= 200000)
result = ((incomeTotal - 150000) * .23) + 23775;
else if (incomeTotal > 200000 && incomeTotal <= 400000)
result = ((incomeTotal - 200000) * .26) + 35275;
else if (incomeTotal > 400000)
result = ((incomeTotal - 400000) * .28) + 87275;
return result;
public double GetRelief(String theage, String thechild, String theparent, String thecourse, String themaid)
ageTotal = Double.parseDouble(theage);
parentTotal = Double.parseDouble(theparent);
maidTotal = Double.parseDouble(themaid);
childTotal = Double.parseDouble(thechild);
courseTotal = Double.parseDouble(thecourse);
//determine age relief
if(ageTotal<55)
relief += 3000;
else if(ageTotal>=55 && ageTotal<= 59)
relief += 8000;
else
relief += 10000;
//determine children relief
if(childTotal<=3)
relief += (childTotal*2000);
else if(childTotal>3 && childTotal<6)
relief += ((childTotal-3)*500 + 6000);
else
relief += 0;
//determine parent relief
if(parentTotal == 1)
relief += 3000;
else if(parentTotal ==2)
relief += 6000;
else
relief += 0;
//determine course subsidy
if(courseTotal != 0 ) {
if(courseTotal <= 2500)
relief += courseTotal;
else
relief += 2500;
//determine maid levy
if(maidTotal != 0) {
if(maidTotal <= 4000)
relief += 2 * maidTotal;
else
relief += 0;
return relief;
} // end of class Calculate
} // end class TaxCalYou're probably not getting anything to show up because in your actionPerformed() method, b3 has not been initialized.
You declare static variables:
Button b2, b3;
but then in your init() method, you delare new local variables when you specify:
Button b2 = new Button(...);
Button b3 = new Button(...);
Since you're declaring and initializing the new local variables, you have never set the static variables to any values. Try removing the type declaration for b2 and b3 in your init() method as follows:
b2 = new Button(...)
b3 = new Button(...)
Hope this helps! -
Can you take a look pls.....urgent
i'm writing a tax calculator applet i've no compilation errors but my applet doesn't seems to run. can u guys pls help....
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class TaxCal extends Applet implements ActionListener {
private TextField txtIncome, txtAge, txtChild, txtParent, txtCourse, txtMaid, txtPay;
private Button b2, b3;
private Calculate calc;
public void init() {
setBackground(Color.lightGray);
/* Create the input boxes, and make sure that the background
color is white. (On some platforms, it is automatically.) */
txtIncome = new TextField(10);
Panel incomePanel = new Panel();
incomePanel.setLayout(new BorderLayout(2,2));
incomePanel.add( new Label("Input your annual income"), BorderLayout.WEST );
incomePanel.add(txtIncome, BorderLayout.CENTER);
txtAge = new TextField(2);
Panel agePanel = new Panel();
agePanel.setLayout(new BorderLayout(2,2));
agePanel.add( new Label("Input your age"), BorderLayout.WEST );
agePanel.add(txtAge, BorderLayout.CENTER);
txtChild = new TextField(2);
Panel childPanel = new Panel();
childPanel.setLayout(new BorderLayout(2,2));
childPanel.add( new Label("Number of children"), BorderLayout.WEST );
childPanel.add(txtChild, BorderLayout.CENTER);
txtParent = new TextField(1);
Panel parentPanel = new Panel();
parentPanel.setLayout(new BorderLayout(2,2));
parentPanel.add( new Label("Number of parent that live with you"), BorderLayout.WEST );
parentPanel.add(txtParent, BorderLayout.CENTER);
txtCourse = new TextField(5);
Panel coursePanel = new Panel();
coursePanel.setLayout(new BorderLayout(2,2));
coursePanel.add( new Label("Course fee"), BorderLayout.WEST );
coursePanel.add(txtCourse, BorderLayout.CENTER);
txtMaid = new TextField(5);
Panel maidPanel = new Panel();
maidPanel.setLayout(new BorderLayout(2,2));
maidPanel.add( new Label("Maid levy paid"), BorderLayout.WEST );
maidPanel.add(txtMaid, BorderLayout.CENTER);
txtPay = new TextField(10);
txtPay.setEditable(false);
Panel payPanel = new Panel();
payPanel.setLayout(new BorderLayout(2,2));
payPanel.add( new Label("Please pay"), BorderLayout.WEST );
payPanel.add(txtPay, BorderLayout.CENTER);
Panel buttonPanel = new Panel();
buttonPanel.setLayout(new GridLayout(1,3));
Button b2 = new Button("Reset");
b2.addActionListener(this); // register listener
buttonPanel.add(b2);
Button b3 = new Button("Calculate");
b3.addActionListener(this); // register listener
buttonPanel.add(b3);
/* Set up the layout for the applet, using a GridLayout,
and add all the components that have been created. */
setLayout(new GridLayout(8,2));
add(incomePanel);
add(agePanel);
add(childPanel);
add(parentPanel);
add(coursePanel);
add(maidPanel);
add(payPanel);
add(buttonPanel);
/* Try to give the input focus to txtIncome, which is
the natural place for the user to start. */
txtIncome.requestFocus();
} // end init()
public TaxCal() {
calc = new Calculate();
public Insets getInsets() {
// Leave some space around the borders of the applet.
return new Insets(2,2,2,2);
// event handler for ActionEvent
public void actionPerformed (ActionEvent e) {
String s = e.getActionCommand();
if (s.equals("Calculate"))
//double income = calc.GetIncome(txtIncome.getText());
double age = calc.GetAge(txtAge.getText());
double child = calc.GetChild(txtChild.getText());
double parent = calc.GetParent(txtParent.getText());
double course = calc.GetCourse(txtCourse.getText());
double maid = calc.GetMaid(txtMaid.getText());
double relief = calc.GetRelief(age, child, parent, course, maid);
double result = calc.GetResult(txtIncome.getText(), relief);
txtPay.setText("$" + Double.toString(result));
else
txtIncome.setText("");
txtAge.setText("");
txtChild.setText("");
txtParent.setText("");
txtCourse.setText("");
txtMaid.setText("");
txtPay.setText("");
} // end actionPerformed()
public class Calculate
private double income;
private double age, ageRelief;
private double child, childRelief;
private double parent, parentRelief;
private double course, courseRelief;
private double maid, maidRelief;
private double totalRelief;
private double result;
public Calculate()
income = 0;
age = 0;
ageRelief = 0;
child = 0;
childRelief = 0;
parent = 0;
parentRelief = 0;
course = 0;
courseRelief = 0;
maid = 0;
maidRelief = 0;
totalRelief = 0;
result = 0;
public double GetAge(String theage) {
age = Double.parseDouble(theage);
//determine age relief
if(age<55)
ageRelief += 3000;
else if(age>=55 && age<= 59)
ageRelief += 8000;
else
ageRelief += 10000;
return ageRelief;
public double GetChild(String thechild) {
child = Double.parseDouble(thechild);
//determine children relief
if(child<=3)
childRelief += (child*2000);
else if(child>3 && child<6)
childRelief += ((child-3)*500 + 6000);
else
childRelief += 0;
return childRelief;
public double GetParent(String theparent) {
parent = Double.parseDouble(theparent);
//determine parent relief
if(parent == 1)
parentRelief += 3000;
else if(parent ==2)
parentRelief += 6000;
else
parentRelief += 0;
return parentRelief;
public double GetCourse(String thecourse) {
course = Double.parseDouble(thecourse);
//determine course subsidy
if(course != 0 ) {
if(course <= 2500)
courseRelief += course;
else
courseRelief += 2500;
return courseRelief;
public double GetMaid(String themaid) {
maid = Double.parseDouble(themaid);
//determine maid levy
if(maid != 0) {
if(maid <= 4000)
maidRelief += 2 * maid;
else
maidRelief += 0;
return maidRelief;
public double GetRelief(double theage, double thechild, double theparent, double thecourse, double themaid) {
double totalRelief = age + child + parent + course + maid;
return totalRelief;
public double GetResult(String theincome, double therelief) {
income = Double.parseDouble(theincome);
totalRelief = therelief;
income =- totalRelief;
if (income <= 7500)
result = income * .02;
else if (income > 7500 && income <= 20000)
result = 150 + ((income - 7500) * .05);
else if (income > 20000 && income <= 35000)
result = ((income - 20000) * .08) + 775;
else if (income> 35000 && income <= 50000)
result = ((income - 35000) * .12) + 1975;
else if (income > 50000 && income <= 75000)
result = ((income - 50000) * .16) + 3775;
else if (income > 75000 && income <= 100000)
result = ((income - 75000) * .2) + 7775;
else if (income > 100000 && income <= 150000)
result = ((income - 100000) * .22) + 12775;
else if (income > 150000 && income <= 200000)
result = ((income - 150000) * .23) + 23775;
else if (income > 200000 && income <= 400000)
result = ((income - 200000) * .26) + 35275;
else if (income > 400000)
result = ((income - 400000) * .28) + 87275;
return result;
} // end of class Calculate
} // end class TaxCalIn order to run an applet you must encapsulate it in a web page using the APPLET tag and open the web page with an internet browser, or include the APPLET tag in the source code of the applet class and run it with the appletviewer.
In order to run your applet in the appletviewer add this in between the import statements and the class implementation.
<APPLET Code="TaxCal" width="300" height="300">
</APPLET>
Good Luck. -
Hi,
I'm new & working on my assignment. I'm working on a tax calculator applet. I'm having problems (cannot work) and would like to ask if anyone can correct my mistakes.
Here's my code
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class TaxCal extends Applet implements ActionListener {
private TextField income, age, child, parent, course, maid, pay;
private Button b2, b3;
public void init() {
setBackground(Color.lightGray);
/* Create the input boxes, and make sure that the background
color is white. (On some platforms, it is automatically.) */
income = new TextField(10);
Panel incomePanel = new Panel();
incomePanel.setLayout(new BorderLayout(2,2));
incomePanel.add( new Label("Input your annual income"), BorderLayout.WEST );
incomePanel.add(income, BorderLayout.CENTER);
age = new TextField(2);
Panel agePanel = new Panel();
agePanel.setLayout(new BorderLayout(2,2));
agePanel.add( new Label("Input your age"), BorderLayout.WEST );
agePanel.add(age, BorderLayout.CENTER);
child = new TextField(2);
Panel childPanel = new Panel();
childPanel.setLayout(new BorderLayout(2,2));
childPanel.add( new Label("Number of children"), BorderLayout.WEST );
childPanel.add(child, BorderLayout.CENTER);
parent = new TextField(1);
Panel parentPanel = new Panel();
parentPanel.setLayout(new BorderLayout(2,2));
parentPanel.add( new Label("Number of parent that live with you"), BorderLayout.WEST );
parentPanel.add(parent, BorderLayout.CENTER);
course = new TextField(5);
Panel coursePanel = new Panel();
coursePanel.setLayout(new BorderLayout(2,2));
coursePanel.add( new Label("Course fee"), BorderLayout.WEST );
coursePanel.add(course, BorderLayout.CENTER);
maid = new TextField(5);
Panel maidPanel = new Panel();
maidPanel.setLayout(new BorderLayout(2,2));
maidPanel.add( new Label("Maid levy paid"), BorderLayout.WEST );
maidPanel.add(maid, BorderLayout.CENTER);
pay = new TextField(10);
pay.setEditable(false);
Panel payPanel = new Panel();
payPanel.setLayout(new BorderLayout(2,2));
payPanel.add( new Label("Please pay"), BorderLayout.WEST );
payPanel.add(pay, BorderLayout.CENTER);
Panel buttonPanel = new Panel();
buttonPanel.setLayout(new GridLayout(1,3));
Button b2 = new Button("Reset");
b2.addActionListener(this); // register listener
buttonPanel.add(b2);
Button b3 = new Button("Calculate");
b3.addActionListener(this); // register listener
buttonPanel.add(b3);
/* Set up the layout for the applet, using a GridLayout,
and add all the components that have been created. */
setLayout(new GridLayout(8,2));
add(incomePanel);
add(agePanel);
add(childPanel);
add(parentPanel);
add(coursePanel);
add(maidPanel);
add(payPanel);
add(buttonPanel);
/* Try to give the input focus to xInput, which is
the natural place for the user to start. */
income.requestFocus();
} // end init()
public Insets getInsets() {
// Leave some space around the borders of the applet.
return new Insets(2,2,2,2);
// event handler for ActionEvent
public void actionPerformed (ActionEvent e) {
if (e.getSource() == b3) {
double x = 0;
double relief = 0;
String incomeString = income.getText();
double income = Double.parseDouble(incomeString);
String ageString = age.getText();
int age = Integer.parseInt(ageString);
String childString = child.getText();
int child = Integer.parseInt(childString);
String parentString = parent.getText();
int parent = Integer.parseInt(parentString);
String courseString = course.getText();
double course = Double.parseDouble(courseString);
String maidString = maid.getText();
double maid = Double.parseDouble(maidString);
//determine age relief
if(age<55) {
relief += 3000;
else if(age>=55 && age<= 59) {
relief += 8000;
else {
relief += 10000;
//determine children relief
if(child<=3) {
relief += (child*2000);
else if(child>3 && child<6) {
relief += ((child-3)*500 + 6000);
else {
relief += 0;
//determine parent relief
if(parent == 1) {
relief += 3000;
else if(parent ==2) {
relief += 6000;
else {
relief += 0;
//determine course subsidy
if(course != 0 ) {
if(course <= 2500) {
relief += course;
else {
relief += 2500;
//determine maid levy
if(maid != 0) {
if(maid <= 4000) {
relief += 2 * maid;
else {
relief += 0;
income =- relief;
if (income <= 7500) {
x = income * .02;
else if (income > 7500 && income <= 20000)
x = 150 + ((income - 7500) * .05);
else if (income > 20000 && income <= 35000)
x = ((income - 20000) * .08) + 775;
else if (income > 35000 && income <= 50000)
x = ((income - 35000) * .12) + 1975;
else if (income > 50000 && income <= 75000)
x = ((income - 50000) * .16) + 3775;
else if (income > 75000 && income <= 100000)
x = ((income - 75000) * .2) + 7775;
else if (income > 100000 && income <= 150000)
x = ((income - 100000) * .22) + 12775;
else if (income > 150000 && income <= 200000)
x = ((income - 150000) * .23) + 23775;
else if (income > 200000 && income <= 400000)
x = ((income - 200000) * .26) + 35275;
else if (income > 400000)
x = ((income - 400000) * .28) + 87275;
pay.setText("$" + x);
else
income.setText("");
age.setText("");
child.setText("");
parent.setText("");
course.setText("");
maid.setText("");
pay.setText("");
} // end actionPerformed()
} // end class TaxCalThe problem that you're having is actually one of scope. At the top of your class, you declare the two buttons:
private Button b2, b3;These Button objects have class scope.
Within the init() method, the lines:
Button b2 = new Button("Reset");
Button b3 = new Button("Calculate");declare another pair of Button objects that have method scope. These are the objects that are added to the panel and that receive the mouse click.
In the actionPerformed() method, the statement:
if (e.getSource() == b3) {cannot refer to the two Button object that are encapsulated in the init() method, but it can and does refer to the Button object with class scope. This is not the object that was added to the panel, so it hasn't received any events and won't be the source of the event that triggered execution of the actionPerformed() method. Since you don't check for any other events, the processing associated with the "Reset" button (b2) will always be executed.
If you change the two lines in the init() method to:
b2 = new Button("Reset");
b3 = new Button("Calculate");
your code will work as originally written (but there are a couple of errors in the computation logic). -
Need help merging these two files togehter
I have the following class files one reads in a file another creates a file, Can somebody help me put the two class files together so i have one file which creates a file and reads it in, as i am stuck as to which bits need to be copied and which bits i only need once.
/////////////////////////////////////////////////Code to create and save data in to file////////////////
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import bank.BankUI;
import bank.*;
public class CreateSequentialFile extends JFrame {
private ObjectOutputStream output;
private BankUI userInterface;
private JButton enterButton, openButton;
private Store store;
private Employee record;
// set up GUI
public CreateSequentialFile()
super( "Creating a Sequential File of Objects" ); // appears in top of gui
// create instance of reusable user interface
userInterface = new BankUI( 9 ); // number of textfields
getContentPane().add( userInterface, BorderLayout.CENTER );
// configure button doTask1 for use in this program
openButton = userInterface.getDoTask1Button();
openButton.setText( "Save to 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
// configure button doTask2 for use in this program
enterButton = userInterface.getDoTask2Button();
enterButton.setText( "Save to file..." );
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( 600, 500 );
setVisible( true );
store = new Store(100);
} // 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;
File fileName = fileChooser.getSelectedFile(); // get selected file
// 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 else
} // end method openFile
// close file and terminate application
private void closeFile()
// close file
try {
int storeSize = store.getCount();
for (int i = 0; i<storeSize;i++)
output.writeObject(store.elementAt(i));
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 );
} // end method closeFile
// add record to file
public void addRecord()
int employeeNumber = 0;
String fieldValues[] = userInterface.getFieldValues();
// if account field value is not empty
if ( ! fieldValues[ BankUI.IDNUMBER ].equals( "" ) ) {
// output values to file
try {
employeeNumber = Integer.parseInt(
fieldValues[ BankUI.IDNUMBER ] );
String dob = fieldValues[ BankUI.DOB ];
String[] dateofBirth = dob.split ("-"); // what used to put between number
String sDate = fieldValues[ BankUI.START ];
String[] startDate = sDate.split ("-");
String sex = fieldValues[ BankUI.GENDER ];
char gender = (sex.charAt(0));
if ( employeeNumber >= 0 ) {
record = new Employee(
fieldValues[ BankUI.NAME ],
gender,
new Date( Integer.parseInt(dateofBirth[0]),
Integer.parseInt(dateofBirth[1]),
Integer.parseInt(dateofBirth[2])),
fieldValues[ BankUI.ADDRESS ],
fieldValues[ BankUI.NATINTNO ],
fieldValues[ BankUI.PHONE ],
fieldValues[ BankUI.IDNUMBER ],
new Date( Integer.parseInt(startDate[0]),
Integer.parseInt(startDate[1]),
Integer.parseInt(startDate[2])),
Float.parseFloat( fieldValues[ BankUI.SALARY ] ));
if (!store.isFull())
store.add(record);
else
JOptionPane.showMessageDialog( this, "The Store is full you cannot add\n"+
"anymore employees. \nPlease Save Current File and Create a New File." );
System.out.println("Store full");
store.displayAll();
System.out.println("Count is " + store.getCount());
// output record and flush buffer
//should be written to fuile in the close file method.
output.flush();
else
JOptionPane.showMessageDialog( this,
"Account number must be greater than 0",
"Bad account number", JOptionPane.ERROR_MESSAGE );
// clear textfields
userInterface.clearFields();
} // end try
// process invalid account number or balance format
catch ( NumberFormatException formatException ) {
JOptionPane.showMessageDialog( this,
"Bad ID number, Date or Salary", "Invalid Number Format",
JOptionPane.ERROR_MESSAGE );
// process exceptions from file output
catch ( ArrayIndexOutOfBoundsException ArrayException ) {
JOptionPane.showMessageDialog( this, "Error with Start Date or Date of Birth",
"IO Exception", JOptionPane.ERROR_MESSAGE );
// process exceptions from file output
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this, "Error writing to file",
"IO Exception", JOptionPane.ERROR_MESSAGE );
closeFile();
} // end if
} // end method addRecord
public static void main( String args[] )
new CreateSequentialFile();
} // end class CreateSequentialFile
/////////////////////////////Code to read and cycle through the file created above///////////
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import bank.*;
public class ReadSequentialFile extends JFrame {
private ObjectInputStream input;
private BankUI userInterface;
private JButton nextButton, openButton, nextRecordButton ;
private Store store = new Store(100);
private Employee employeeList[] = new Employee[100];
private int count = 0, next = 0;
// Constructor -- initialize the Frame
public ReadSequentialFile()
super( "Add Employee" );
// create instance of reusable user interface
userInterface = new BankUI( 9 );
getContentPane().add( userInterface, BorderLayout.CENTER );
// get reference to generic task button doTask1 from BankUI
openButton = userInterface.getDoTask1Button();
openButton.setText( "Open File" );
// register listener to call openFile when button pressed
openButton.addActionListener(
// anonymous inner class to handle openButton event
new ActionListener() {
// close file and terminate application
public void actionPerformed( ActionEvent event )
openFile();
} // end anonymous inner class
); // end call to addActionListener
// register window listener for window closing event
addWindowListener(
// anonymous inner class to handle windowClosing event
new WindowAdapter() {
// close file and terminate application
public void windowClosing( WindowEvent event )
if ( input != null )
closeFile();
System.exit( 0 );
} // end anonymous inner class
); // end call to addWindowListener
// get reference to generic task button doTask2 from BankUI
nextButton = userInterface.getDoTask2Button();
nextButton.setText( "Next Record" );
nextButton.setEnabled( false );
// register listener to call readRecord when button pressed
nextButton.addActionListener(
// anonymous inner class to handle nextRecord event
new ActionListener() {
// call readRecord when user clicks nextRecord
public void actionPerformed( ActionEvent event )
readRecord();
} // end anonymous inner class
); // end call to addActionListener
//get reference to generic task button do Task3 from BankUI
// get reference to generic task button doTask3 from BankUI
nextRecordButton = userInterface.getDoTask3Button();
nextRecordButton.setText( "Get Next Record" );
nextRecordButton.setEnabled( false );
// register listener to call readRecord when button pressed
nextRecordButton.addActionListener(
// anonymous inner class to handle nextRecord event
new ActionListener() {
// call readRecord when user clicks nextRecord
public void actionPerformed( ActionEvent event )
getNextRecord();
} // end anonymous inner class
); // end call to addActionListener
pack();
setSize( 600, 300 );
setVisible( true );
} // end ReadSequentialFile constructor
// enable user to select file to open
private void openFile()
// display file dialog so user can select file to open
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
int result = fileChooser.showOpenDialog( this );
// if user clicked Cancel button on dialog, return
if ( result == JFileChooser.CANCEL_OPTION )
return;
// obtain selected file
File fileName = fileChooser.getSelectedFile();
// display error if file name invalid
if ( fileName == null || fileName.getName().equals( "" ) )
JOptionPane.showMessageDialog( this, "Invalid File Name",
"Invalid File Name", JOptionPane.ERROR_MESSAGE );
else {
// open file
try {
input = new ObjectInputStream(
new FileInputStream( fileName ) );
openButton.setEnabled( false );
nextButton.setEnabled( true );
// process exceptions opening file
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this, "Error Opening File",
"Error", JOptionPane.ERROR_MESSAGE );
} // end else
} // end method openFile
// read record from file
public void readRecord()
Employee record;
// input the values from the file
try {
record = ( Employee ) input.readObject();
employeeList[count++]= record;
store.add(record);
store.displayAll();
System.out.println("Count is " + store.getCount());
// create array of Strings to display in GUI
String values[] = {
String.valueOf(record.getName()),
String.valueOf(record.getGender()),
String.valueOf( record.getDateOfBirth()),
String.valueOf( record.getID()),
String.valueOf( record.getStartDate()),
String.valueOf( record.getSalary()),
String.valueOf( record.getAddress()),
String.valueOf( record.getNatInsNo()),
String.valueOf( record.getPhone())
// i added all those bits above split onto one line to look neater
// display record contents
userInterface.setFieldValues( values );
// display message when end-of-file reached
catch ( EOFException endOfFileException ) {
nextButton.setEnabled( false );
nextRecordButton.setEnabled( true );
JOptionPane.showMessageDialog( this, "No more records in file",
"End of File", JOptionPane.ERROR_MESSAGE );
// display error message if class is not found
catch ( ClassNotFoundException classNotFoundException ) {
JOptionPane.showMessageDialog( this, "Unable to create object",
"Class Not Found", JOptionPane.ERROR_MESSAGE );
// display error message if cannot read due to problem with file
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this,
"Error during read from file",
"Read Error", JOptionPane.ERROR_MESSAGE );
} // end method readRecord
private void getNextRecord()
Employee record = employeeList[next++%count];//cycles throught accounts
//create aray of string to display in GUI
String values[] = {String.valueOf(record.getName()),
String.valueOf(record.getGender()),
String.valueOf( record.getStartDate() ), String.valueOf( record.getAddress()),
String.valueOf( record.getNatInsNo()),
String.valueOf( record.getPhone()),
String.valueOf( record.getID() ),
String.valueOf( record.getDateOfBirth() ),
String.valueOf( record.getSalary() ) };
//display record contents
userInterface.setFieldValues(values);
//display record contents
// again i nicked these write them on one line
// close file and terminate application
private void closeFile()
// close file and exit
try {
input.close();
System.exit( 0 );
// process exception while closing file
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this, "Error closing file",
"Error", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
} // end method closeFile
public static void main( String args[] )
new ReadSequentialFile();
} // end class ReadSequentialFileI tired putting both codes together and got this, it runs but does not do what i want can anybody help me put the above two codes together as one
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import bank.BankUI;
import bank.*;
public class togehter extends JFrame {
private ObjectOutputStream output;
private BankUI userInterface;
private JButton enterButton, openButton;
//private Store store; wont work if i un comment this
private Employee record;
// from read
private ObjectInputStream input;
private JButton nextButton, openButton2, nextRecordButton ;
private Store store = new Store(100);
private Employee employeeList[] = new Employee[100];
private int count = 0, next = 0;
// end of read
// set up GUI
public togehter()
super( "Creating a Sequential File of Objects" ); // appears in top of gui
// create instance of reusable user interface
userInterface = new BankUI( 9 ); // textfields
getContentPane().add( userInterface, BorderLayout.CENTER );
// configure button doTask1 for use in this program
openButton = userInterface.getDoTask1Button();
openButton.setText( "Save to 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
// from read
// get reference to generic task button doTask1 from BankUI
openButton2 = userInterface.getDoTask1Button();
openButton2.setText( "Open File" );
// register listener to call openFile when button pressed
openButton2.addActionListener(
// anonymous inner class to handle openButton2 event
new ActionListener() {
// close file and terminate application
public void actionPerformed( ActionEvent event )
openFile();
} // end anonymous inner class
); // end call to addActionListener
// from read end
// from read
// register window listener for window closing event
addWindowListener(
// anonymous inner class to handle windowClosing event
new WindowAdapter() {
// close file and terminate application
public void windowClosing( WindowEvent event )
if ( input != null )
closeFile();
System.exit( 0 );
} // end anonymous inner class
); // end call to addWindowListener
//from read end
// from read
// get reference to generic task button doTask2 from BankUI
nextButton = userInterface.getDoTask2Button();
nextButton.setText( "Next Record" );
nextButton.setEnabled( false );
// register listener to call readRecord when button pressed
nextButton.addActionListener(
// anonymous inner class to handle nextRecord event
new ActionListener() {
// call readRecord when user clicks nextRecord
public void actionPerformed( ActionEvent event )
readRecord();
} // end anonymous inner class
); // end call to addActionListener
//get reference to generic task button do Task3 from BankUI
// get reference to generic task button doTask3 from BankUI
nextRecordButton = userInterface.getDoTask3Button();
nextRecordButton.setText( "Get Next Record" );
nextRecordButton.setEnabled( false );
// register listener to call readRecord when button pressed
nextRecordButton.addActionListener(
// anonymous inner class to handle nextRecord event
new ActionListener() {
// call readRecord when user clicks nextRecord
public void actionPerformed( ActionEvent event )
getNextRecord();
} // end anonymous inner class
); // end call to addActionListener
// from read end
// configure button doTask2 for use in this program
enterButton = userInterface.getDoTask2Button();
enterButton.setText( "Save to file..." );
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( 600, 500 );
setVisible( true );
store = new Store(100);
} // 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;
File fileName = fileChooser.getSelectedFile(); // get selected file
// 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 else
} // end method openFile
// from read
public void readRecord()
Employee record;
// input the values from the file
try {
record = ( Employee ) input.readObject();
employeeList[count++]= record;
store.add(record);/////////ADDS record to Store
store.displayAll();
System.out.println("Count is " + store.getCount());
// create array of Strings to display in GUI
String values[] = {
String.valueOf(record.getName()),
String.valueOf(record.getGender()),
String.valueOf( record.getDateOfBirth()),
String.valueOf( record.getID()),
String.valueOf( record.getStartDate()),
String.valueOf( record.getSalary()),
String.valueOf( record.getAddress()),
String.valueOf( record.getNatInsNo()),
String.valueOf( record.getPhone())
// display record contents
userInterface.setFieldValues( values );
// display message when end-of-file reached
catch ( EOFException endOfFileException ) {
nextButton.setEnabled( false );
nextRecordButton.setEnabled( true );
JOptionPane.showMessageDialog( this, "No more records in file",
"End of File", JOptionPane.ERROR_MESSAGE );
// display error message if class is not found
catch ( ClassNotFoundException classNotFoundException ) {
JOptionPane.showMessageDialog( this, "Unable to create object",
"Class Not Found", JOptionPane.ERROR_MESSAGE );
// display error message if cannot read due to problem with file
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this,
"Error during read from file",
"Read Error", JOptionPane.ERROR_MESSAGE );
} // end method readRecord
//from read end
// from read
private void getNextRecord()
Employee record = employeeList[next++%count];//cycles throught accounts
//create aray of string to display in GUI
String values[] = {String.valueOf(record.getName()),
String.valueOf(record.getGender()),
String.valueOf( record.getStartDate() ), String.valueOf( record.getAddress()),
String.valueOf( record.getNatInsNo()),
String.valueOf( record.getPhone()),
String.valueOf( record.getID() ),
String.valueOf( record.getDateOfBirth() ),
String.valueOf( record.getSalary() ) };
//display record contents
userInterface.setFieldValues(values);
//display record contents
// from read end
// close file and terminate application
private void closeFile()
// close file
try {
int storeSize = store.getCount();
for (int i = 0; i<storeSize;i++)
output.writeObject(store.elementAt(i));
output.close();
input.close(); // from read
System.exit( 0 );
// process exceptions from closing file
catch( IOException ioException ) {
JOptionPane.showMessageDialog( this, "Error closing file",
"Error", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
} // end method closeFile
// add record to file
public void addRecord()
int employeeNumber = 0;
String fieldValues[] = userInterface.getFieldValues();
// if account field value is not empty
if ( ! fieldValues[ BankUI.IDNUMBER ].equals( "" ) ) {
// output values to file
try {
employeeNumber = Integer.parseInt(
fieldValues[ BankUI.IDNUMBER ] );
String dob = fieldValues[ BankUI.DOB ];
String[] dateofBirth = dob.split ("-"); // what used to put between number chnage to /
String sDate = fieldValues[ BankUI.START ];
String[] startDate = sDate.split ("-");
String sex = fieldValues[ BankUI.GENDER ];
char gender = (sex.charAt(0)); // check if m or f prob check in employee
if ( employeeNumber >= 0 ) {
record = new Employee(
fieldValues[ BankUI.NAME ],
gender,
new Date( Integer.parseInt(dateofBirth[0]),
Integer.parseInt(dateofBirth[1]),
Integer.parseInt(dateofBirth[2])),
fieldValues[ BankUI.ADDRESS ],
fieldValues[ BankUI.NATINTNO ],
fieldValues[ BankUI.PHONE ],
fieldValues[ BankUI.IDNUMBER ],
new Date( Integer.parseInt(startDate[0]),
Integer.parseInt(startDate[1]),
Integer.parseInt(startDate[2])),
Float.parseFloat( fieldValues[ BankUI.SALARY ] ));
if (!store.isFull())
store.add(record);
else
JOptionPane.showMessageDialog( this, "The Store is full you cannot add\n"+
"anymore employees. \nPlease Save Current File and Create a New File." );
System.out.println("Store full");
store.displayAll();
System.out.println("Count is " + store.getCount());
output.flush();
else
JOptionPane.showMessageDialog( this,
"Account number must be greater than 0",
"Bad account number", JOptionPane.ERROR_MESSAGE );
// clear textfields
userInterface.clearFields();
} // end try
// process invalid account number or balance format
catch ( NumberFormatException formatException ) {
JOptionPane.showMessageDialog( this,
"Bad ID number, Date or Salary", "Invalid Number Format",
JOptionPane.ERROR_MESSAGE );
// process exceptions from file output
catch ( ArrayIndexOutOfBoundsException ArrayException ) {
JOptionPane.showMessageDialog( this, "Error with Start Date or Date of Birth",
"IO Exception", JOptionPane.ERROR_MESSAGE );
// process exceptions from file output
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this, "Error writing to file",
"IO Exception", JOptionPane.ERROR_MESSAGE );
closeFile();
} // end if
} // end method addRecord
public static void main( String args[] )
new togehter();
} // end class CreateSequentialFileI GOT IT WORKING BUT THERE WAS A WEIRD ERROR I GET WHEN TRYING TO READ A FILE I JUST WROTE THE THREAD FOR THAT CAN BE FOUND:
http://forum.java.sun.com/thread.jspa?threadID=5147209
Message was edited by:
ajrobson
Maybe you are looking for
-
I'd like to go back to Snow Leopard from Lion.What should I look out for?
I downloaded OS X Lion from the Mac App Store back in February, and I'm getting sick of Lion so I'd like to go back to Snow Leopard. I have the install disc. Will all of my files be used in Snow Leopard, or will I have to save all of them?
-
Professional DVD Recorder for FCP??
Is there a pro DVD recorder/player that can be controlled like a deck (9-pin/FW or both) for input and output of Final Cut Pro? I often need to capture offline clips of sports events that are 3 to 4 hours long. I've been using Amerisoft's DVD ripper,
-
Cannot open preferences in iPhoto 08,what could be the problem
-
MB minor drop, NO video, replaced LCD, still NO video!
Hi Folks, My first experience as a tech installing these new, ultrathin, LED LCD screens. Got a client's MB 13" Unibody (2008 late) and there was no video, no back light, nothing. External screen displays just fine with a MiniDVI to VGA to LCD connec
-
Is there any FM/User Exit exits in the name "CONVT_NO_NUMBER "
Hi All, Is there any FM/User Exit exits in the name "CONVT_NO_NUMBER " 4.6C and 4.6B version? Thanks