Is this code correct?

help me please
in this code the code should make a method for reading form a file
import java.io.*;
public class Basic2
     String contents;
     String fileName = "schools.txt";
     BufferedReader now;
     public static void main(String[] args) throws IOException
          public BufferedReader open(BufferedReader fileReader)
               fileReader = new BufferedReader(new FileReader("schools.txt"));
     contents = open(now).readLine();
     System.out.println (contents);

You are trying to make a method inside a method. Move the open method before or after the main method.
There is a problem with your open method. The return type is BufferedReader but you don't return anything from the method. And you cannot pass in "now" to the method and initialize it in the method like you do. It won't assign anything to your now variable since its a copy of the reference that is passed to the method.
It's also better to make a method that both opens the file, reads the file and the closes the file, and finally return the information you needed from the file, perhaps the whole file in a string or just the first line:
public String readFirstLine(String filename) throws IOException {
  BufferedReader in = new BufferedReader(new FileReader(filename));
  String s = in.readLine();
  in.close();
  return s;
public static void main(String[] args) throws IOException {
  System.out.println(readFirstLine(fileName));
}

Similar Messages

  • How  can i run this code correctly?

    hello, everybody:
        when  i run the code, i found that it dons't work,so ,i  hope somebody can help me!
        the Ball class is this :
        package {
        import flash.display.Sprite;
        [SWF(width = "550", height = "400")]
        public class Ball extends Sprite {
            private var radius:Number;
            private var color:uint;
            private var vx:Number;
            private var vy:Number;
            public function Ball(radius:Number=40, color:uint=0xff9900,
            vx:Number =0, vy:Number =0) {
                this.radius= radius;
                this.color = color;
                this.vx = vx;
                this.vy = vy;
                init();
            private function init():void {
                graphics.beginFill(color);
                graphics.drawCircle(0,0,radius);
                graphics.endFill();
    and the Chain class code is :
    package {
        import flash.display.Sprite;
        import flash.events.Event;
        [SWF(width = "550", height = "400")]
        public class Chain extends Sprite {
            private var ball0:Ball;
            private var ball1:Ball;
            private var ball2:Ball;
            private var spring:Number = 0.1;
            private var friction:Number = 0.8;
            private var gravity:Number = 5;
            //private var vx:Number =0;
            //private var vy:Number = 0;
            public function Chain() {
                init();
            public function init():void {
                ball0  = new Ball(20);
                addChild(ball0);
                ball1 = new Ball(20);
                addChild(ball1);
                ball2 = new Ball(20);
                addChild(ball2);
                addEventListener(Event.ENTER_FRAME, onEnterFrame);
            private function onEnterFrame(event:Event):void {
                moveBall(ball0, mouseX, mouseY);
                moveBall(ball1, ball0.x, ball0.y);
                moveBall(ball2, ball1.x, ball1.y);
                graphics.clear();
                graphics.lineStyle(1);
                graphics.moveTo(mouseX, mouseY);
                graphics.lineTo(ball0.x, ball0.y);
                graphics.lineTo(ball1.x, ball1.y);
                graphics.lineTo(ball2.x, ball2.y);
            private function moveBall(ball:Ball,
                                      targetX:Number,
                                      targetY:Number):void {
                ball.vx += (targetX - ball.x) * spring;
                ball.vy += (targetY - ball.y) * spring;
                ball.vy += gravity;
                ball.vx *= friction;
                ball.vy *= friction;
                ball.x += vx;
                ball.y += vy;
    thanks every body's help!

    ok, thanks for your reply ! I run this code in the Flex builder 3!and the Ball class and the Chain class are all in the same AS project!
      and i changed the ball.pv property as public in the Ball class, and  the Chain class has no wrong syntactic analysis,but the AS code don't run.so this is the problem.
    2010-04-21
    Fang
    发件人: Ned Murphy <[email protected]>
    发送时间: 2010-04-20 23:01
    主 题: how  can i run this code correctly?
    收件人: fang alvin <[email protected]>
    I don't see that the Ball class has a pv property, or that you even try to access a pv property in the Chain class.  All of the properties in your Ball class are declared as private, so you probably cannot access them directly.  They would need to be public.  Also, I still don't see where you import Ball in the chain class such that it can use it.

  • Please, I want to help in correcting this code

    I want to know what mistakes in this code where it gives the message (frm-41214 unable to run report)
    the code
    DECLARE
    v_rep_id REPORT_OBJECT;
    v_repjob VARCHAR2(100);
    v_job_id VARCHAR2(100);
    v_rep_status VARCHAR2(100);
    v_reportsrvr VARCHAR2(50) := 'rep10';
    v_runformat vARCHAR2(50) := 'pdf';
    BEGIN
    IF :date_from IS NULL and :date_to is null and :ITEM4 is null THEN
    RAISE FORM_TRIGGER_FAILURE;
    END IF;
    v_rep_id := FIND_REPORT_OBJECT('REPORT2');
    SET_REPORT_OBJECT_PROPERTY(v_rep_id, REPORT_COMM_MODE, SYNCHRONOUS);
    SET_REPORT_OBJECT_PROPERTY(v_rep_id, REPORT_DESTYPE, CACHE);
    SET_REPORT_OBJECT_PROPERTY(v_rep_id, REPORT_SERVER, v_reportsrvr);
    SET_REPORT_OBJECT_PROPERTY(v_rep_id, REPORT_DESFORMAT, v_runformat);
    SET_REPORT_OBJECT_PROPERTY(v_rep_id, REPORT_OTHER , 'P_date="' || TO_CHAR(:date_from, 'dd/mm/yyyy') || '" P_date1="'|| TO_CHAR(:date_to, 'dd/mm/yyyy') || '"'||'" p_no="' || :ITEM4||'" paramform=no"');
    SET_REPORT_OBJECT_PROPERTY(v_rep_id, REPORT_FILENAME, 'd:\ltvisits_omayma.rdf');
    v_repjob := RUN_REPORT_OBJECT(v_rep_id);
    v_job_id := SUBSTR(v_repjob, LENGTH(v_reportsrvr) + 2, LENGTH(v_repjob) );
    v_rep_status := REPORT_OBJECT_STATUS(v_repjob);
    IF v_rep_status = 'FINISHED' THEN
    WEB.SHOW_DOCUMENT('/reports/rwservlet/getjobid' || v_job_id ||'?server=' || v_reportsrvr || '', '_blank');
    ELSE
    message('Report failed with error message ');
    END IF;
    CLEAR_FORM;
    END;

    Hi,
    You CANNOT use hardcord path in report name
    SET_REPORT_OBJECT_PROPERTY(v_rep_id, REPORT_FILENAME, 'd:\ltvisits_omayma.rdf'); Remove "d:\" part from the report name and then copy your report to FORMS_PATH location.
    *If answer is correct then please mark it.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Can understand whats wrong with this code.

    I'm sort new to Java programing, and I created this simple converter, but when I try to complie it, it gives me an exception error, could some one tell me how to correct this code.
    import java.text.*;
    import javax.swing.*;
    public class Converter
         private final static double EURO = .8295577, YEN = 115.614, CAD = 1.17781;
         public static void main (String[] args)
               String input =null;
               double US= 0.0;
               DecimalFormat twoPrecision = new DecimalFormat("0.00");
             input() = 0
              try{
                   US = Double.parseDouble (input);
                    System.out.print("US to Euro: ");
                    System.out.println(twoPrecision.format(US * EURO));
                  US = Double.parseDouble (input);
                    System.out.print("US to Yen: ");
                    System.out.println(twoPrecision.format(US * YEN));
                  US = Double.parseDouble (input);
                    System.out.print("US to Cad: ");
                    System.out.println(twoPrecision.format(US * CAD));
              catch(NumberFormatException e)
                   JOptionPane.showMessageDialog(null,
                                    "You must enter a number",
                                    "Input data error",
                                    JOptionPane.ERROR_MESSAGE);
    }

    Try this:
    import java.text.*;
    import javax.swing.*;
    import java.io.*;
    public class Converter
         private final static double EURO = .8295577, YEN = 115.614, CAD = 1.17781;
         public static void main (String[] args)
               double US= 0.0;
               DecimalFormat twoPrecision = new DecimalFormat("0.00");
               try{
                   BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
             String input=br.readLine();
                   US = Double.parseDouble (input);
                    System.out.print("US to Euro: ");
                    System.out.println(twoPrecision.format(US * EURO));
                  US = Double.parseDouble (input);
                    System.out.print("US to Yen: ");
                    System.out.println(twoPrecision.format(US * YEN));
                  US = Double.parseDouble (input);
                    System.out.print("US to Cad: ");
                    System.out.println(twoPrecision.format(US * CAD));
              catch(Exception e)
                   JOptionPane.showMessageDialog(null,
                                    "You must enter a number",
                                    "Input data error",
                                    JOptionPane.ERROR_MESSAGE);
    }

  • How do i do with this code

    i´ve got this to link a time line to a url.... is that
    correct?
    to be clear i just need to open a "menu2.swf" related in what
    page i´m ex. if i´m at ww.xxxxxxxxxx.com/clientes.html, i
    needed flash to start a "menu2.swf" from frame 30 and playing
    // AS3
    var url:TextField = new TextField();
    url.text = root.loaderInfo.parameters.clientes;
    gotoAndPlay(30);
    // AS3
    var url:TextField = new TextField();
    url.text = root.loaderInfo.parameters.sevicios;
    gotoAndPlay(20);
    i got this code for the html:
    <script type="text/javascript">
    var so = new SWFObject("flash/menu2.swf", "menu", "100",
    "475", "9", "#FFFFFF");
    so.addVariable("flashvars", value="url=clientes");
    so.write("flashcontent");
    </script>

    your parameter is url, not clientes and not sevicios. those
    are the parameter values.

  • I am stuck with this code- I definitely need a bail out

    I would appreciate if a good samaritan could add this code for me. I am at my wits end.
    The program I am trying to write is supposed to add students with their personal information and then display them in a GUI.
    I should be able to select a student and add a grade for that student.
    Finally I should be able to get the average for all the grades added for this student and display the average grade.
    My challenge is how to obtain all the added scores and show the students average .
    I understand my best shot is to use VECTOR API.
    I tried to write someething but it did not work at , obviously due to inexperience.
    I just can't figure how to link this average display window to the Get Average button.
    A student can have any number of grades.
    I need someone to show me the way, may be little "code guide" I am waaaay lost
    Thanks in advance
    Little Delmarie.
    THIS IS WHAT I HAVE DONE SO FAR . IT COMPILES nicely in DOS and Visual age
    // CODE GradeSystem
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import java.awt.*;
    * UsingJLists.java
    * This is a sample program for the use of JLists. You can add a student by entering their
    * information a clicking on add. You can remove a student by entering their information and
    * clicking on remove. They must be in the list to be removed. You can modify a student by
    * entering their information and clicking add. You will be asked for the new student
    * information when using modify. The add and remove buttons will disappear when modifying
    * is underway and the new information is being collected for updating.
    * @author Delmarie
    public class GradeSystem extends JDialog {
    Vector studentGrades = new Vector();
    JButton add, modify, remove;
    JList theJList;
    JPanel buttonPanel, textPanel, labelPanel, masterPanel, jlistPanel, infoPanel;
    JTextField score, possibleScore, gradeType;
    JLabel label1, label2, label3;
    public class ModifyHandler implements ActionListener {
    public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
    // get the student info from the text boxes
    double dScore = 0;
    double dPossibleScore = 0;
    try {
    String str1 = score.getText();
    if (str1 != null) dScore = Double.parseDouble(str1);
    String str2 = possibleScore.getText();
    if (str2 != null) dPossibleScore = Double.parseDouble(str2);
    catch(NumberFormatException e) {}
    String sGradeType = gradeType.getText();
    Grade grade = (Grade)theJList.getSelectedValue();
    if (grade == null) {
    score.setText("");
    possibleScore.setText("");
    gradeType.setText("");
    return;
    grade.setScore(dScore);
    grade.setPossibleScore(dPossibleScore);
    grade.setGradeType(sGradeType);
    theJList.repaint();
    public class RemoveHandler implements ActionListener {
    public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
    int removeIndex = theJList.getSelectedIndex();
    if (removeIndex == -1) {
    score.setText("");
    possibleScore.setText("");
    gradeType.setText("");
    return;
    DefaultListModel model = (DefaultListModel) theJList.getModel();
    model.removeElementAt(removeIndex);
    studentGrades.removeElementAt(removeIndex);
    // clear the textboxes
    score.setText("");
    possibleScore.setText("");
    gradeType.setText("");
    public class AddHandler implements ActionListener {
    public void actionPerformed(ActionEvent actionEvent) {
    // get the student info from the text boxes
    double dScore = 0;
    double dPossibleScore = 0;
    try {
    String str1 = score.getText();
    if (str1 != null) dScore = Double.parseDouble(str1);
    String str2 = possibleScore.getText();
    if (str2 != null) dPossibleScore = Double.parseDouble(str2);
    catch(NumberFormatException e) {}
    String sGradeType = gradeType.getText();
    // get the model and add the student to the model
    Grade g = new Grade();
    g.setScore(dScore);
    g.setPossibleScore(dPossibleScore);
    g.setGradeType(sGradeType);
    studentGrades.add(g);
    DefaultListModel model = (DefaultListModel) theJList.getModel();
    model.addElement(g);
    // display the added element
    theJList.setSelectedValue(g, true);
    public class WindowHandler extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
    setVisible(false);
    /** Creates a new instance of UsingJLists */
    public GradeSystem(JFrame owner, boolean modal) {
    super(owner, modal);
    // create all of the components, put them in panels, and put the panels in JFrame
    add = new JButton("Add");
    modify = new JButton("Modify");
    remove = new JButton("Remove");
    score = new JTextField("");
    score.setColumns(10);
    possibleScore = new JTextField("");
    gradeType = new JTextField("");
    label1 = new JLabel("score");
    label2 = new JLabel("possibleScore");
    label3 = new JLabel("gradeType");
    FlowLayout flow = new FlowLayout();
    FlowLayout flow1 = new FlowLayout();
    FlowLayout flow2 = new FlowLayout();
    GridLayout grid1 = new GridLayout(7,1);
    GridLayout grid2 = new GridLayout(7,1);
    BorderLayout border3 = new BorderLayout();
    buttonPanel = new JPanel(flow);
    buttonPanel.add(add);
    buttonPanel.add(modify);
    buttonPanel.add(remove);
    labelPanel = new JPanel(grid1);
    //labelPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    labelPanel.add(Box.createVerticalStrut(20));
    labelPanel.add(label1);
    labelPanel.add(Box.createVerticalStrut(20));
    labelPanel.add(label2);
    labelPanel.add(Box.createVerticalStrut(20));
    labelPanel.add(label3);
    labelPanel.add(Box.createVerticalStrut(20));
    textPanel = new JPanel(grid2);
    //textPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    textPanel.add(Box.createVerticalStrut(20));
    textPanel.add(score);
    textPanel.add(Box.createVerticalStrut(20));
    textPanel.add(possibleScore);
    textPanel.add(Box.createVerticalStrut(20));
    textPanel.add(gradeType);
    textPanel.add(Box.createVerticalStrut(20));
    infoPanel = new JPanel(new FlowLayout());
    infoPanel.setBorder(BorderFactory.createTitledBorder("Grade Information"));
    infoPanel.add(Box.createHorizontalStrut(10));
    infoPanel.add(textPanel);
    infoPanel.add(Box.createHorizontalStrut(10));
    infoPanel.add(labelPanel);
    infoPanel.add(Box.createHorizontalStrut(10));
    theJList = new JList(new DefaultListModel());
    theJList.addListSelectionListener(new javax.swing.event.ListSelectionListener(){
    public void valueChanged(ListSelectionEvent evt) {
    Grade grade = (Grade)theJList.getSelectedValue();
    if (grade == null) {
    score.setText("");
    possibleScore.setText("");
    gradeType.setText("");
    return;
    score.setText(Double.toString(grade.getScore()));
    possibleScore.setText(Double.toString(grade.getPossibleScore()));
    gradeType.setText(grade.getGradeType());
    //JLabel theLabel = new JLabel("Students");
    jlistPanel = new JPanel(border3);
    jlistPanel.setBorder(BorderFactory.createTitledBorder("List of Scores"));
    jlistPanel.add(new JScrollPane(theJList));//, BorderLayout.SOUTH);
    masterPanel = new JPanel(new GridLayout(1, 2));
    masterPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    // masterPanel.add(Box.createHorizontalStrut(10));
    masterPanel.add(infoPanel);
    // masterPanel.add(Box.createHorizontalStrut(10));
    masterPanel.add(jlistPanel);
    // masterPanel.add(Box.createHorizontalStrut(10));
    BorderLayout border = new BorderLayout();
    this.getContentPane().setLayout(border);
    Container theContainer = this.getContentPane();
    theContainer.add(buttonPanel,BorderLayout.SOUTH);
    theContainer.add(masterPanel, BorderLayout.CENTER);
    // now add the event handlers for the buttons
    AddHandler handleAdd = new AddHandler();
    ModifyHandler handleModify = new ModifyHandler();
    RemoveHandler handleRemove = new RemoveHandler();
    add.addActionListener(handleAdd);
    modify.addActionListener(handleModify);
    remove.addActionListener(handleRemove);
    // add the event handler for the window events
    WindowHandler handleWindow = new WindowHandler();
    this.addWindowListener(handleWindow);
    setSize(600,300);
    * Insert the method's description here.
    * Creation date: (2/24/03 4:20:07 PM)
    * @param v com.sun.java.util.collections.Vector
    public void setStudentGrades(Vector v) {
    studentGrades = v;
    DefaultListModel model = (DefaultListModel) theJList.getModel();
    model.removeAllElements();
    int size = v.size();
    for (int i = 0; i < size; i++) {
    model.addElement(v.get(i));
    score.setText("");
    possibleScore.setText("");
    gradeType.setText("");
    setVisible(true);
    // CODE2 StudentSystem
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import java.awt.*;
    * UsingJLists.java
    * This is a sample program for the use of JLists. You can add a student by entering their
    * information a clicking on add. You can remove a student by entering their information and
    * clicking on remove. They must be in the list to be removed. You can modify a student by
    * entering their information and clicking add. You will be asked for the new student
    * information when using modify. The add and remove buttons will disappear when modifying
    * is underway and the new information is being collected for updating.
    * @author Delmarie
    public class StudentSystem extends JFrame {
    StudentGradeBook studentGradeBook = new StudentGradeBook();
    GradeSystem gradeSystem = new GradeSystem(this, true);
    JButton add, modify, remove, bGrade;
    JList theJList;
    JPanel buttonPanel, textPanel, labelPanel, masterPanel, jlistPanel, infoPanel;
    JTextField name, address, email, phone, courseName, courseDescription;
    JLabel label1, label2, label3;
    StudentSystem tempObjectRef; // used to hold a class level reference to object for dispose
    boolean getStudentInfo = false;
    int saveIndexInObject;
    public class ModifyHandler implements ActionListener {
    public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
    // get the information for the student to modify
    String studentName = name.getText();
    String studentAddress = address.getText();
    String studentEmail = email.getText();
    if (!getStudentInfo) { // set up to get student info
    // find the correct element of the model to remove and save in class variable
    int removeIndex = -1;
    DefaultListModel model = (DefaultListModel) theJList.getModel();
    for (int i = 0; i < model.size(); i++) {
    String temp = (String) model.elementAt(i);
    if (temp.equals(name.getText())) {
    removeIndex = i;
    break;
    saveIndexInObject = removeIndex;
    if (removeIndex == -1) return;
    // change the text on the border of the info box
    infoPanel.setBorder(BorderFactory.createTitledBorder("Enter new Student Info"));
    // set up to get the modified info and remove some of the buttons
    getStudentInfo = true;
    buttonPanel.removeAll();
    buttonPanel.add(modify);
    buttonPanel.add(bGrade);
    buttonPanel.repaint();
    else {
    // reset the border and change the element at the provided index (from if above)
    getStudentInfo = false;
    infoPanel.setBorder(BorderFactory.createTitledBorder("Student Information"));
    DefaultListModel model = (DefaultListModel) theJList.getModel();
    model.setElementAt(name.getText(), saveIndexInObject);
    Student student = studentGradeBook.findStudent(saveIndexInObject);
    student.setName(name.getText());
    student.setAddress(address.getText());
    student.setEmail(email.getText());
    student.setPhone(phone.getText());
    student.setCourseName(courseName.getText());
    student.setCourseDescription(courseDescription.getText());
    // clear the textboxes
    name.setText("");
    address.setText("");
    email.setText("");
    phone.setText("");
    courseName.setText("");
    courseDescription.setText("");
    // restore all of the buttons
    buttonPanel.removeAll();
    buttonPanel.add(add);
    buttonPanel.add(modify);
    buttonPanel.add(remove);
    buttonPanel.add(bGrade);
    buttonPanel.repaint();
    public class RemoveHandler implements ActionListener {
    public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
    // get the student info from the text boxes
    String studentName = name.getText();
    String studentAddress = address.getText();
    String studentEmail = email.getText();
    // find the element to remove by name (you could use email address etc also)
    int removeIndex = -1; // = theJList.getSelectedIndex();
    DefaultListModel model = (DefaultListModel) theJList.getModel();
    for (int i = 0; i < model.size(); i++) {
    String temp = (String) model.elementAt(i);
    if (temp.equals(name.getText())) {
    removeIndex = i;
    break;
    if (removeIndex == -1) return;
    // remove the element at the index from the for loop
    model.removeElementAt(removeIndex);
    Student student = studentGradeBook.findStudent(removeIndex);
    studentGradeBook.removeStudent(student);
    // clear the textboxes
    name.setText("");
    address.setText("");
    email.setText("");
    phone.setText("");
    courseName.setText("");
    courseDescription.setText("");
    public class AddHandler implements ActionListener {
    public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
    // get the student info from the text boxes
    String studentName = name.getText();
    String studentAddress = address.getText();
    String studentEmail = email.getText();
    String studentPhone = phone.getText();
    String studentCourseName = courseName.getText();
    String studentCourseDescription = courseDescription.getText();
    // get the model and add the student to the model
    studentGradeBook.addStudent(studentName, studentAddress, studentEmail, studentPhone,
    studentCourseName, studentCourseDescription);
    DefaultListModel model = (DefaultListModel) theJList.getModel();
    model.addElement(studentName);
    // reset the text boxes
    name.setText("");
    address.setText("");
    email.setText("");
    phone.setText("");
    courseName.setText("");
    courseDescription.setText("");
    public class WindowHandler extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
    gradeSystem.dispose();
    tempObjectRef.dispose();
    System.exit(0);
    /** Creates a new instance of UsingJLists */
    public StudentSystem() {
    // create all of the components, put them in panels, and put the panels in JFrame
    add = new JButton("Add");
    modify = new JButton("Modify");
    remove = new JButton("Remove");
    bGrade = new JButton("Grades");
    name = new JTextField("");
    name.setColumns(10);
    address = new JTextField("");
    email = new JTextField("");
    phone = new JTextField("");
    courseName = new JTextField("");
    courseDescription = new JTextField("");
    label1 = new JLabel("name");
    label2 = new JLabel("address");
    label3 = new JLabel("email");
    JLabel label4 = new JLabel("phone");
    JLabel label5 = new JLabel("courseName");
    JLabel label6 = new JLabel("courseDescription");
    FlowLayout flow = new FlowLayout();
    FlowLayout flow1 = new FlowLayout();
    FlowLayout flow2 = new FlowLayout();
    GridLayout grid1 = new GridLayout(13,1);
    GridLayout grid2 = new GridLayout(13,1);
    BorderLayout border3 = new BorderLayout();
    buttonPanel = new JPanel(flow);
    buttonPanel.add(add);
    buttonPanel.add(modify);
    buttonPanel.add(remove);
    buttonPanel.add(bGrade);
    bGrade.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    int index = theJList.getSelectedIndex();
    if (index == -1) return;
    Student student = studentGradeBook.findStudent(index);
    gradeSystem.setStudentGrades(student.getStudentGrades());
    labelPanel = new JPanel(grid1);
    //labelPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    labelPanel.add(Box.createVerticalStrut(20));
    labelPanel.add(label1);
    labelPanel.add(Box.createVerticalStrut(20));
    labelPanel.add(label2);
    labelPanel.add(Box.createVerticalStrut(20));
    labelPanel.add(label3);
    labelPanel.add(Box.createVerticalStrut(20));
    labelPanel.add(label4);
    labelPanel.add(Box.createVerticalStrut(20));
    labelPanel.add(label5);
    labelPanel.add(Box.createVerticalStrut(20));
    labelPanel.add(label6);
    labelPanel.add(Box.createVerticalStrut(20));
    textPanel = new JPanel(grid2);
    //textPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    textPanel.add(Box.createVerticalStrut(20));
    textPanel.add(name);
    textPanel.add(Box.createVerticalStrut(20));
    textPanel.add(address);
    textPanel.add(Box.createVerticalStrut(20));
    textPanel.add(email);
    textPanel.add(Box.createVerticalStrut(20));
    textPanel.add(phone);
    textPanel.add(Box.createVerticalStrut(20));
    textPanel.add(courseName);
    textPanel.add(Box.createVerticalStrut(20));
    textPanel.add(courseDescription);
    textPanel.add(Box.createVerticalStrut(20));
    infoPanel = new JPanel(new FlowLayout());
    infoPanel.setBorder(BorderFactory.createTitledBorder("Student Information"));
    infoPanel.add(Box.createHorizontalStrut(10));
    infoPanel.add(textPanel);
    infoPanel.add(Box.createHorizontalStrut(10));
    infoPanel.add(labelPanel);
    infoPanel.add(Box.createHorizontalStrut(10));
    theJList = new JList(new DefaultListModel());
    theJList.addListSelectionListener(new javax.swing.event.ListSelectionListener(){
    public void valueChanged(ListSelectionEvent evt) {
    int index = theJList.getSelectedIndex();
    if (index == -1) return;
    Student student = studentGradeBook.findStudent(index);
    name.setText(student.getName());
    address.setText(student.getAddress());
    email.setText(student.getEmail());
    phone.setText(student.getPhone());
    courseName.setText(student.getCourseName());
    courseDescription.setText(student.getCourseDescription());
    //JLabel theLabel = new JLabel("Students");
    jlistPanel = new JPanel(border3);
    jlistPanel.setBorder(BorderFactory.createTitledBorder("List of Students"));
    jlistPanel.add(new JScrollPane(theJList), BorderLayout.SOUTH);
    masterPanel = new JPanel(flow1);
    masterPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    masterPanel.add(Box.createHorizontalStrut(10));
    masterPanel.add(infoPanel);
    masterPanel.add(Box.createHorizontalStrut(10));
    masterPanel.add(jlistPanel);
    masterPanel.add(Box.createHorizontalStrut(10));
    BorderLayout border = new BorderLayout();
    this.getContentPane().setLayout(border);
    Container theContainer = this.getContentPane();
    theContainer.add(buttonPanel,BorderLayout.SOUTH);
    theContainer.add(masterPanel, BorderLayout.NORTH);
    // now add the event handlers for the buttons
    AddHandler handleAdd = new AddHandler();
    ModifyHandler handleModify = new ModifyHandler();
    RemoveHandler handleRemove = new RemoveHandler();
    add.addActionListener(handleAdd);
    modify.addActionListener(handleModify);
    remove.addActionListener(handleRemove);
    // add the event handler for the window events
    WindowHandler handleWindow = new WindowHandler();
    this.addWindowListener(handleWindow);
    // make the frame visible and set its size and show it.
    this.setVisible(true);
    this.pack();//setSize(600,300);
    this.show();
    public static void main (String [] args) {
    StudentSystem mainObject = new StudentSystem();
    mainObject.setTempObjectRef(mainObject);
    public void setTempObjectRef(StudentSystem obj) {
    // set up a reference to this object for use in closing the window method dispose
    tempObjectRef = obj;
    // CODE 3 Student
    import java.util.*;
    * Insert the type's description here.
    * Creation date: (2/24/03 11:23:58 AM)
    * @author: Delmarie
    public class Student {
    private String name, address, phone, email, courseName, courseDescription;
    private Vector studentGrades;
    * Student constructor comment.
    public Student() {
    studentGrades = new Vector();
    * Insert the method's description here.
    * Creation date: (2/24/03 11:39:56 AM)
    * @param score double
    * @param possibleScore double
    * @param gradeType java.lang.String
    public void addGrade(double score, double possibleScore, String gradeType) {
    Grade g = new Grade();
    g.setScore(score);
    g.setPossibleScore(possibleScore);
    g.setGradeType(gradeType);
    studentGrades.add(g);
    * Insert the method's description here.
    * Creation date: (2/24/03 11:47:01 AM)
    * @return Grade
    * @param index int
    public Grade findGrade(int index) {
    return (Grade)studentGrades.get(index);
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @return java.lang.String
    public java.lang.String getAddress() {
    return address;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @return java.lang.String
    public java.lang.String getCourseDescription() {
    return courseDescription;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @return java.lang.String
    public java.lang.String getCourseName() {
    return courseName;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @return java.lang.String
    public java.lang.String getEmail() {
    return email;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:48:03 AM)
    * @return java.util.Iterator
    public Iterator getGradeIterator() {
    return studentGrades.iterator();
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @return java.lang.String
    public java.lang.String getName() {
    return name;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @return java.lang.String
    public java.lang.String getPhone() {
    return phone;
    * Insert the method's description here.
    * Creation date: (2/25/03 10:56:13 AM)
    * @return java.util.Vector
    public java.util.Vector getStudentGrades() {
    return studentGrades;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:41:52 AM)
    * @param grade Grade
    public void removeGrade(Grade grade) {
    studentGrades.remove(grade);
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @param newAddress java.lang.String
    public void setAddress(java.lang.String newAddress) {
    address = newAddress;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @param newCourseDescription java.lang.String
    public void setCourseDescription(java.lang.String newCourseDescription) {
    courseDescription = newCourseDescription;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @param newCourseName java.lang.String
    public void setCourseName(java.lang.String newCourseName) {
    courseName = newCourseName;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @param newEmail java.lang.String
    public void setEmail(java.lang.String newEmail) {
    email = newEmail;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @param newName java.lang.String
    public void setName(java.lang.String newName) {
    name = newName;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @param newPhone java.lang.String
    public void setPhone(java.lang.String newPhone) {
    phone = newPhone;
    * Insert the method's description here.
    * Creation date: (2/25/03 10:56:13 AM)
    * @param newStudentGrades java.util.Vector
    public void setStudentGrades(Vector newStudentGrades) {
    studentGrades = newStudentGrades;
    //CODE 4 StudentGradeBook
    import java.util.*;
    * Insert the type's description here.
    * Creation date: (2/24/03 11:50:35 AM)
    * @author: delmarie
    public class StudentGradeBook {
    private Vector allStudents;
    * StudentGradeBook constructor comment.
    public StudentGradeBook() {
    allStudents = new Vector();
    * Insert the method's description here.
    * Creation date: (2/24/03 11:54:01 AM)
    * @param name java.lang.String
    * @param address java.lang.String
    * @param email java.lang.String
    * @param phone java.lang.String
    public void addStudent(String name, String address, String email, String phone) {
    Student student = new Student();
    student.setName(name);
    student.setAddress(address);
    student.setEmail(email);
    student.setPhone(phone);
    allStudents.add(student);
    * Insert the method's description here.
    * Creation date: (2/24/03 11:54:01 AM)
    * @param name java.lang.String
    * @param address java.lang.String
    * @param email java.lang.String
    * @param phone java.lang.String
    public void addStudent(String name, String address, String email, String phone,
    String courseName, String courseDescription) {
    Student student = new Student();
    student.setName(name);
    student.setAddress(address);
    student.setEmail(email);
    student.setPhone(phone);
    student.setCourseName(courseName);
    student.setCourseDescription(courseDescription);
    allStudents.add(student);
    * Insert the method's description here.
    * Creation date: (2/24/03 12:00:53 PM)
    * @param index Student
    public Student findStudent(int index) {
    return (Student)allStudents.get(index);
    * Insert the method's description here.
    * Creation date: (2/24/03 12:02:43 PM)
    * @return java.util.Iterator
    public Iterator getStudentIterator() {
    return allStudents.iterator();
    * Insert the method's description here.
    * Creation date: (2/24/03 11:59:41 AM)
    * @param student Student
    public void removeStudent(Student student) {
    allStudents.remove(student);
    // CODE 5 Grade
    * Insert the type's description here.
    * Creation date: (2/24/03 11:29:38 AM)
    * @author: Delmarie
    public class Grade {
    private double score, possibleScore;
    private String gradeType;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:46:07 AM)
    public Grade() {}
    * Insert the method's description here.
    * Creation date: (2/24/03 11:31:13 AM)
    * @return java.lang.String
    public java.lang.String getGradeType() {
    return gradeType;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:31:13 AM)
    * @return double
    public double getPossibleScore() {
    return possibleScore;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:31:13 AM)
    * @return double
    public double getScore() {
    return score;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:31:13 AM)
    * @param newGradeType java.lang.String
    public void setGradeType(java.lang.String newGradeType) {
    gradeType = newGradeType;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:31:13 AM)
    * @param newPossibleScore double
    public void setPossibleScore(double newPossibleScore) {
    possibleScore = newPossibleScore;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:31:13 AM)
    * @param newScore double
    public void setScore(double newScore) {
    score = newScore;
    * Insert the method's description here.
    * Creation date: (2/24/03 4:03:57 PM)
    * @return java.lang.String
    public String toString() {
    return Double.toString(score);

    Ok.
    I had a look at your code and decided against showing you how to
    modify it to do what you want....
    Reason being that it's something of a mess. I guess the reason for that
    mess is a combination of the fact that you're new to Java (new to
    software in general?) and you're using Visual Age.
    So, below is a very quick (far from perfect, I just knocked it up in my
    lunch hour) example of the kind of approach I would take to the problem.
    Feel free to take ideas from it and build them in to your code.
    Whatever you do, don't hand it in as you own work. By all means, hand
    it in in addition to your own work and maybe even get your
    teacher to comment on it.
    Oh yes, if you use it, chuck me some dukes form this and your earlier
    post on the same subject. Too many folks these days are neglecting to
    allocate dukes - don't be one of them!
    Oh, one thing about using the app, double clicking on table entries
    for students and grades brings up the appropriate dialog. To create
    a new grade or delete the selected ones, use the "right mouse" context
    menu.
    Enjoy.
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    import java.text.*;
    public class Rosemary2
         static class GradeDialog
              extends JDialog
              private JTextField mScore= new JTextField();
              private JTextField mPossibleScore= new JTextField();
              private JTextField mGradeType= new JTextField();
              private Grade mGrade;
              public GradeDialog(JDialog owner) { this(owner, null); }
              public GradeDialog(JDialog owner, Grade grade)
                   super(owner, true);
                   mGrade= grade;
                   if (mGrade == null)
                        setTitle("New Grade");
                   else {
                        setTitle("Edit Grade");
                        setGrade();
                   JPanel panel= new JPanel();
                   panel.setBorder(new EmptyBorder(4,4,4,4));
                   panel.setLayout(new GridLayout(0,2,4,4));
                   panel.add(new JLabel("Score:"));
                   panel.add(mScore);
                   panel.add(new JLabel("Possible Score:"));
                   panel.add(mPossibleScore);
                   panel.add(new JLabel("Grade Type:"));
                   panel.add(mGradeType);
                   getContentPane().add(panel, BorderLayout.CENTER);
                   panel= new JPanel();
                   panel.setLayout(new GridLayout(1,0));
                   JButton ok= new JButton("OK");
                   panel.add(ok);
                   ok.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             if (scrapeGrade())
                                  dispose();
                   JButton cancel= new JButton("Cancel");
                   panel.add(cancel);
                   cancel.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             mGrade= null;
                             dispose();
                   JPanel wrapper= new JPanel();
                   wrapper.setBorder(new EmptyBorder(0,4,4,4));
                   wrapper.setLayout(new BorderLayout());
                   wrapper.add(panel, BorderLayout.EAST);
                   getContentPane().add(wrapper, BorderLayout.SOUTH);
                   setResizable(false);
                   pack();
                   setLocation(
                        owner.getLocation().x +
                             (owner.getSize().width/2) -
                                  (getSize().width/2),
                        owner.getLocation().y +
                             (owner.getSize().height/2) -
                                  (getSize().height/2));
              private void setGrade()
                   mScore.setText(String.valueOf(mGrade.getScore()));
                   mPossibleScore.setText(String.valueOf(mGrade.getPossibleScore()));
                   mGradeType.setText(mGrade.getGradeType());
                   mScore.selectAll();
              private boolean scrapeGrade()
                   try {
                        if (mGrade == null) {
                             mGrade= new Grade(
                                  Double.parseDouble(mScore.getText()),
                                  Double.parseDouble(mPossibleScore.getText()),
                                  mGradeType.getText());
                        else {
                             mGrade.setScore(Double.parseDouble(mScore.getText()));
                             mGrade.setPossibleScore(Double.parseDouble(mPossibleScore.getText()));
                             mGrade.setGradeType(mGradeType.getText());
                        return true;
                   catch (NumberFormatException e) {
                        JOptionPane.showMessageDialog(this, "Scores must be numbers, you Muppet!");
                   return false;
              public Grade getGrade() { return mGrade; }
         static class GradesPanel
              extends JPanel
              private Vector mGrades= new Vector();
              private JTable mTable;
              private NumberFormat mFormat= NumberFormat.getInstance();
              private JDialog mParent;
              public GradesPanel(JDialog parent, Iterator grades)
                   mParent= parent;
                   mFormat.setMaximumFractionDigits(2);
                   while (grades != null && grades.hasNext())
                        mGrades.add(grades.next());
                   setLayout(new BorderLayout());
                   setBorder(new EmptyBorder(4,4,4,4));
                   createTable();
                   JScrollPane sp= new JScrollPane(mTable);
                   add(sp, BorderLayout.CENTER);
                   MouseListener listener= new MouseAdapter() {
                        public void mousePressed(MouseEvent e) {
                             if (e.getButton() == e.BUTTON2 || e.getButton() == e.BUTTON3)     
                                  menu(e.getPoint());
                   mTable.addMouseListener(listener);
                   sp.addMouseListener(listener);
                   mTable.addMouseListener(new MouseAdapter() {
                        public void mouseClicked(MouseEvent e) {
                             if (e.getClickCount() >= 2)
                                  editGrade();
              public Iterator getGrades() { return mGrades.iterator(); }
              private void createTable()
                   mTable= new JTable(new AbstractTableModel() {
                        public int getColumnCount() {
                             return 4;
                        public int getRowCount() {
                             return mGrades.size();
                        public String getColumnName(int column) {
                             switch (column) {
                                  case 0: return "Score";
                                  case 1: return "Possible";
                                  case 2: return "Type";
                                  case 3: return "Grade";
                                  default: return "###";
                        public Object getValueAt(int row, int column) {
                             Grade grade= (Grade) mGrades.elementAt(row);
                             switch (column) {
                                  case 0: return mFormat.format(grade.getScore());
                                  case 1: return mFormat.format(grade.getPossibleScore());
                                  case 2: return grade.getGradeType();
                                  case 3: return String.valueOf(grade.getGrade()) +"%";
                                  default: return "###";
                   mTable.setPreferredScrollableViewportSize(new Dimension(10,10));
              private void menu(Point point)
                   JPopupMenu popup= new JPopupMenu();
                   JMenuItem add= new JMenuItem("Add");
                   popup.add(add);
                   add.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) { addGrade(); } });
                   if (mTable.rowAtPoint(point) >= 0 && mTable.rowAtPoint(point) == mTable.getSelectedRow()) {
                        JMenuItem edit= new JMenuItem("Edit");
                        popup.add(edit);
                        edit.addActionListener(new ActionListener() {
                             public void actionPerformed(ActionEvent e) { editGrade(); } });
                        if (mTable.getSelectedRowCount() > 1)
                             edit.setEnabled(false);
                        JMenuItem delete= new JMenuItem("Delete");
                        popup.add(delete);
                        delete.addActionListener(new ActionListener() {
                             public void actionPerformed(ActionEvent e) { deleteGrade(); } });
                   popup.show(this, point.x, point.y);
              private void addGrade()
                   GradeDialog dialog= new GradeDialog(mParent);
                   dialog.setVisible(true);
                   Grade grade= dialog.getGrade();
                   if (grade != null) {
                        mGrades.add(grade);
                        ((AbstractTableModel) mTable.getModel()).fireTableRowsInserted(
                             mGrades.size()-1, mGrades.size()-1);
              private void editGrade()
                   GradeDialog dialog= new GradeDialog(
                        mParent, (Grade) mGrades.get(mTable.getSelectedRow()));
                   dialog.setVisible(true);
                   if (dialog.getGrade() != null) {
                        ((AbstractTableModel) mTable.getModel()).fireTableRowsUpdated(
                             mTable.getSelectedRow(), mTable.getSelectedRow());
              private void deleteGrade()
                   while (true) {
                        int row= mTable.getSelectedRow();
                        if (row < 0)
                             break;
                        mGrades.removeElementAt(row);
                        ((AbstractTableModel) mTable.getModel()).fireTableRowsDeleted(row, row);
         static class StudentDialog
              extends JDialog
              private JTextField mName= new JTextField(12);
              private JTextField mAddress= new JTextField();
              private JTextField mPhone= new JTextField();
              private JTextField mEmail= new JTextField();
              private JTextField mCourseName= new JTextField();
              private JTextField mCourseDescription= new JTextField();
              private GradesPanel mGradesPanel;
              private Student mStudent;
              public StudentDialog(JFrame owner) { this(owner, null); }
              public StudentDialog(JFrame owner, Student student)
                   super(owner, true);
                   mStudent= student;
                   if (mStudent == null) {
                        setTitle("New Student");
                        mGradesPanel= new GradesPanel(this, null);
                   else {
                        setTitle("Edit Student: " +mStudent.getName());
                        mGradesPanel= new GradesPanel(this, mStudent.getGrades());
                   JTabbedPane tab= new JTabbedPane();
                   tab.setBorder(new EmptyBorder(4,4,4,4));
                   getContentPane().add(tab, BorderLayout.CENTER);
                   tab.add("Details", getDetailsPanel());
                   tab.add("Grades", mGradesPanel);
                   JPanel panel= new JPanel();
                   panel.setLayout(new GridLayout(1,0));
                   JButton ok= new JButton("OK");
                   panel.add(ok);
                   ok.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             scrapeStudent();
                             dispose();
                   JButton cancel= new JButton("Cancel");
                   panel.add(cancel);
                   cancel.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             mStudent= null;
                             dispose();
                   JPanel wrapper= new JPanel();
                   wrapper.setBorder(new EmptyBorder(0,4,4,4));
                   wrapper.setLayout(new BorderLayout());
                   wrapper.add(panel, BorderLayout.EAST);
                   getContentPane().add(wrapper, BorderLayout.SOUTH);
                   setResizable(false);
                   pack();
                   if (mStudent != null)
                        setStudent();
                   setLocation(
                        owner.getLocation().x +
                             (owner.getSize().width/2) -
                                  (getSize().width/2),
                        owner.getLocation().y +
                             (owner.getSize().height/2) -
                                  (getSize().height/2));
              private JPanel getDetailsPanel()
                   JPanel panel= new JPanel();
                   panel.setBorder(new EmptyBorder(4,4,4,4));
                   panel.setLayout(new GridLayout(0,2,4,4));
                   panel.add(new JLabel("Name:"));
                   panel.add(mName);
                   panel.add(new JLabel("Address:"));
                   panel.add(mAddress);
                   panel.add(new JLabel("Phone:"));
                   panel.add(mPhone);
                   panel.add(new JLabel("E-Mail:"));
                   panel.add(mEmail);
                   panel.add(new JLabel("Course Name:"));
                   panel.add(mCourseName);
                   panel.add(new JLabel("Course Description:"));
                   panel.add(mCourseDescription);
                   return panel;
              private void setStudent()
                   mName.setEnabled(false);
                   mName.setText(mStudent.getName());
                   mAddress.setText(mStudent.getAddress());
                   mPhone.setText(mStudent.getPhone());
                   mEmail.setText(mStudent.getEmail());
                   mCourseName.setText(mStudent.getCourseName());
                   mCourseDescription.setText(mStudent.getCourseDescription());
              private void scrapeStudent()
                   if (mStudent == null) {
                        mStudent= new Student(
                             mName.getText(),
                             mAddress.getText(),
                             mPhone.getText(),
                             mEmail.getText(),
                             mCourseName.getText(),
                             mCourseDescription.getText());
                   else {
                        mStudent.setName(mName.getText());
                        mStudent.setAddress(mAddress.getText());
                        mStudent.setPhone(mPhone.getText());
                        mStudent.setEmail(mEmail.getText());
                        mStudent.setCourseName(mCourseName.getText());
                        mStudent.setCourseDescription(mCourseDescription.getText());
                   mStudent.clearGrades();
                   Iterator grades= mGradesPanel.getGrades();
                   while (grades.hasNext())
                        mStudent.addGrade((Grade) grades.next());
              public Student getStudent() { return mStudent; }
         static class StudentFrame
              extends JFrame
              private Vector mStudents;
              private JTable mTable;
              private JButton mBtnEdit;
              private JButton mBtnDelete;
              public StudentFrame(Vector students)
                   super("Students");
                   mStudents= students;
                   createTable();
                   getContentPane().add(new JScrollPane(mTable), BorderLayout.CENTER);
                   JPanel panel= new JPanel();
                   panel.setLayout(new GridLayout(1,0));
                   JButton btn= new JButton("Add");
                   panel.add(btn);
                   btn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) { addStudent(); } });
                   mBtnEdit= new JButton("Edit");
                   panel.add(mBtnEdit);
                   mBtnEdit.setEnabled(false);
                   mBtnEdit.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) { editStudent(); } });
                   mBtnDelete= new JButton("Delete");
                   panel.add(mBtnDelete);
                   mBtnDelete.setEnabled(false);
                   mBtnDelete.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) { deleteStudent(); } });
                   JPanel wrapper= new JPanel();
                   wrapper.setLayout(new BorderLayout());
                   wrapper.add(panel, BorderLayout.WEST);
                   getContentPane().add(wrapper, BorderLayout.SOUTH);
                   btn= new JButton("Exit");
                   wrapper.add(btn, BorderLayout.EAST);
                   btn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) { System.exit(0); } });
                   pack();
              private void createTable()
                   mTable= new JTable(new AbstractTableModel() {
                        public int getColumnCount() {
                             return 7;
                        public int getRowCount() {
                             return mStudents.size();
                        public String getColumnName(int column) {
                             switch (column) {
                                  case 0: return "Name";
                                  case 1: return "Address";
                                  case 2: return "Phone";
                                  case 3: return "Email";
                                  case 4: return "Course";
                                  case 5: return "Description";
                                  case 6: return "Grade Average";
                                  default: return "###";
                        public Object getValueAt(int row, int column) {
                             Student student= (Student) mStudents.elementAt(row);
                             switch (column) {
                                  case 0: return student.getName();
                                  case 1: return student.getAddress();
                                  case 2: return student.getPhone();
                                  case 3: return student.getEmail();
                                  case 4: return student.getCourseName();
                                  case 5: return student.getCourseDescription();
                                  case 6: return student.getGrade() >= 0 ? String.valueOf(student.getGrade()) +"%": "n/a";
                                  default: return "###";
                   mTable.getSelectionModel().addListSelectionListener(
                        new ListSelectionListener() {
                             public void valueChanged(ListSelectionEvent e) {
                                  if (e.getValueIsAdjusting())
                                       return;
                                  switch (mTable.getSelectedRowCount()) {
                                       case 0:
                                            mBtnEdit.setEnabled(false);
                                            mBtnDelete.setEnabled(false);
                                            break;
                                       case 1:
                                            mBtnEdit.setEnabled(true);
                                            mBtnDelete.setEnabled(true);
                                            break;
                                       default:
                                            mBtnEdit.setEnabled(false);
                                            mBtnDelete.setEnabled(true);
                                            break;
                   mTable.addMouseListener(new MouseAdapter() {
                        public void mouseClicked(MouseEvent e) {
                             if (e.getClickCount() >= 2)
                                  editStudent();
              private void addStudent()
                   StudentDialog dialog= new StudentDialog(this);
                   dialog.setVisible(true);
                   Student student= dialog.getStudent();
                   if (student != null) {
                        mStudents.add(student);
                        ((AbstractTableModel) mTable.getModel()).fireTableRowsInserted(
                             mStudents.size()-1, mStudents.size()-1);
              private void editStudent()
                   StudentDialog dialog= new StudentDialog(
                        this, (Student) mStudents.get(mTable.getSelectedRow()));
                   dialog.setVisible(true);
                   if (dialog.getStudent() != null) {
                        ((AbstractTableModel) mTable.getModel()).fireTableRowsUpdated(
                             mTable.getSelectedRow(), mTable.getSelectedRow());
              private void deleteStudent()
                   while (true) {
                        int row= mTable.getSelectedRow();
                        if (row < 0)
                             break;
                        mStudents.removeElementAt(row);
                        ((AbstractTableModel) mTable.getModel()).fireTableRowsDeleted(row, row);
         static class Student
              private String name;
              private String address;
              private String phone ;
              private String email;
              private String courseName;
              private String courseDescription;
              private Vector grades= new Vector();
              public Student(
                   String name,
                   String address,
                   String phone,
                   String email,
                   String courseName,
                   String courseDescription)
                   setName(name);
                   setAddress(address);
                   setPhone(phone);
                   setEmail(email);
                   setCourseName(courseName);
                   setCourseDescription(courseDescription);
              public Iterator getGrades() { return grades.iterator(); }
              public void addGrade(Grade grade) { grades.add(grade); }
              public void removeGrade(Grade grade) { grades.remove(grade); }
              public void clearGrades() { grades.clear(); }
              public int getGrade()
                   if (grades.size() == 0)
                        return -1;
                   int total= 0;
                   for (int i= 0; i< grades.size(); i++)
                        total += ((Grade) grades.get(i)).getGrade();
                   return (int) (total/grades.size());
              public String getAddress() { return address; }
              public void setAddress(String newAddress) { address = newAddress; }
              public String getCourseDescription() { return courseDescription; }
              public void setCourseDescription(String newCourseDescription) { courseDescription = newCourseDescription; }
              public String getCourseName() { return courseName; }
              public void setCourseName(String newCourseName) { courseName = newCourseName; }
              public String getEmail() { return email; }
              public void setEmail(String newEmail) { email = newEmail; }
              public String getName() { return name; }
              public void setName(String newName) { name = newName; }
              public String getPhone() { return phone; }
              public void setPhone(String newPhone) { phone = newPhone; }
         static class Grade
              private double score;
              private double possibleScore;
              private String gradeType;
              public Grade(
                   double score,
                   double possibleScore,
                   String gradeType)
                   setScore(score);
                   setPossibleScore(possibleScore);
                   setGradeType(gradeType);
              public int getGrade() { return (int) ((100/possibleScore)*score); }
              public String getGradeType() { return gradeType; }
              public void setGradeType(String newGradeType) { gradeType = newGradeType; }
              public double getPossibleScore() { return possibleScore; }
              public void setPossibleScore(double newPossibleScore) { possibleScore = newPossibleScore; }
              public double getScore() { return score; }
              public void setScore(double newScore) { score = newScore; }
              public String toString() { return Double.toString(score); }
         public static void main (String [] args)
              Vector students= new Vector();
              students.add(new Student(
                   "Fred Flitstone",
                   "6 Boulder Close, Bedrock",
                   "555 1234",
                   "[email protected]",
                   "Masonary 101",
                   "Elementary chipping bits off rocks"));
              students.add(new Student(
                   "Barney Rubble",
                   "7 Boulder Close, Bedrock",
                   "555 6789",
                   "[email protected]",
                   "Masonary 101",
                   "Elementary chipping bits off rocks"));
              for (int i= 0; i< 10; i++) {
                   Student student= new Student(
                        "Student " +i,
                        i +" Dorm St, Campus",
                        "555 1234",
                        "student" +i +"@college.edu",
                        "CS 101",
                        "CS for dummies");
                   student.addGrade(new Grade(Math.random()*100, 100.0, "Passing?"));
                   student.addGrade(new Grade(Math.random()*100, 100.0, "Failing?"));
                   students.add(student);
              StudentFrame frame= new StudentFrame(students);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setBounds(32,32,640,480);
              frame.setVisible(true);
    }

  • PLZZZ Help me out in this code

    hi friends..
    Problem in this code is trial of accessing a value that dsnt exist,i.e.,
    words[i+1] . This throws an ArrayOutOfBoundException as it is supposed to. But i nyhow want to access words[i+1] ,may it be null. How do i do that? PLZZ suggest me n rewrite this code for me correctly.
    ( Here words is a string array with values in it . str1,str2,str3,str4 are strings)
    for (i=0;i<words.length;i++)
       String str3=words[ i ];
      if(str3!=null)
           k=words.indexOf("/");
    str1=words[i].substring(k);
    String str4=words[i+1]; //error is here
    if(str4!=null)
         l=words[i+1].indexOf("/");
         str2=words[i+1].substring(l);
    }>

    oh! both the forums r same???erm, no. they're both on the same site, though

  • Error in this code?

    hi friends,
    when I run this code it is giving error as
    Cause: FDPSTP failed due to ORA-01427: single-row subquery returns more than one row
    ORA-06512: at "APPS.UPD_VAC", line 18
    ORA-06512: at line 1
    can some one suggest a solution pls
    the table vac_table has a single column... and it has only 1 record right now
    CREATE OR REPLACE package body APPS.upd_vac is
    procedure upd_prc(p_err_buf out VARCHAR2
    ,p_ret_code out NUMBER)
    is
    l_attr varchar2(100);
    l_attr1 varchar2(100);
    l_attr2 varchar2(100);
    l_attr3 varchar2(100);
    l_attr4 varchar2(100);
    begin
    SELECT MAX(ATTRIBUTE18) INTO L_ATTR FROM PER_VACANCIES;
    select (regexp_substr (l_attr, '.*C')) into l_attr1 from dual;
    select regexp_replace(l_attr,'^.*C(.+)$','\1') into l_attr2 from dual;
    select to_number(l_attr2)+1 into l_attr3 from dual;
    select l_attr1||l_attr3 into l_attr4 from dual;
    insert into vac_table
    (select l_attr4 from dual);
    UPDATE PER_VACANCIES SET ATTRIBUTE18 =(select attribute from kdd_vacancy)
    where vacancy_id =(select max(vacancy_id) from per_vacancies);
    commit;
    end;
    end;

    CREATE OR replace PACKAGE BODY apps.upd_vac
    IS
      PROCEDURE Upd_prc(p_err_buf  OUT VARCHAR2,
                        p_ret_code OUT NUMBER)
      IS
        l_attr  VARCHAR2(100);
        l_attr1 VARCHAR2(100);
        l_attr2 VARCHAR2(100);
        l_attr3 VARCHAR2(100);
        l_attr4 VARCHAR2(100);
      BEGIN
        SELECT MAX(attribute18)
        INTO   l_attr
        FROM   per_vacancies;
        SELECT ( Regexp_substr (l_attr, '.*C') )
        INTO   l_attr1
        FROM   dual;
        SELECT Regexp_replace(l_attr, '^.*C(.+)$', '\1')
        INTO   l_attr2
        FROM   dual;
        SELECT To_number(l_attr2) + 1
        INTO   l_attr3
        FROM   dual;
        SELECT l_attr1
               ||l_attr3
        INTO   l_attr4
        FROM   dual;
        INSERT INTO vac_table
        (SELECT l_attr4
         FROM   dual);
        UPDATE per_vacancies
        SET    attribute18 = (SELECT attribute FROM   kdd_vacancy)
        WHERE  vacancy_id = (SELECT MAX(vacancy_id)
                             FROM   per_vacancies);
        COMMIT;
      END;
    END; 
    (SELECT attribute FROM kdd_vacancy)must return only a single row
    ATTRIBUTE18 is a scalar & can only accept one value; which is correct value FROM KDD_VACANCY?

  • Please give me flowchart for this code...

    Writing a Java applet to communicate with a serial device attached to the Device
    Server is very straightforward. However, familiarity with Java programming and a
    Java compiler are required.
    As with any network application, open a communication channel to the remote
    device. In our example, a socket is opened and and two data streams are created to
    perform the actual sending and receiving of data.
    The following example uses a new Java Class called tcpip. Copy the following code
    into a file called tcpip.java.
    import java.*;
    import java.lang.*;
    import java.net.*;
    import java.util.*;
    import java.io.*;
    * This class opens a TCP connection, and allows reading and writing of byte
    arrays.
    public class tcpip
    protected Socket s = null;
    public DataInputStream dis = null;
    protected DataOutputStream dos = null;
    public tcpip(InetAddress ipa, int port)
    Socket s1 = null;
    try { // Open the socket
    s1 = new Socket(ipa.getHostAddress(), port);
    catch (IOException e) {
    System.out.println("Error opening socket");
    return;
    s = s1;
    try { // Create an input stream
    dis = new DataInputStream(new
    BufferedInputStream(s.getInputStream()));
    catch(Exception ex) {
    System.out.println("Error creating input stream");
    try { // Create an output stream
    dos = new DataOutputStream(new
    BufferedOutputStream(s.getOutputStream()));
    catch(Exception ex) {
    System.out.println("Error creating output stream");
    public synchronized void disconnect()
    if (s != null) {
    try {
    s.close();
    catch (IOException e){}
    public synchronized void send(byte[] temp)
    try {
    dos.write(temp, 0, temp.length);
    dos.flush();
    catch(Exception ex) {
    System.out.println("Error sending data : " + ex.toString());
    public synchronized void send(byte[] temp, int len)
    try {
    dos.write(temp, 0, len);
    dos.flush();
    catch(Exception ex) {
    System.out.println("Error sending data : " + ex.toString());
    public synchronized void send(String given)
    // WARNING: this routine may not properly convert Strings to bytes
    int length = given.length();
    byte[] retvalue = new byte[length];
    char[] c = new char[length];
    given.getChars(0, length, c, 0);
    for (int i = 0; i < length; i++) {
    retvalue[i] = (byte)c;
    send(retvalue);
    public synchronized byte[] receive()
    byte[] retval = new byte[0];
    try {
    while(dis.available() == 0); /* Wait for data */
    catch (IOException e){}
    try {
    retval = new byte[dis.available()];
    catch (IOException e){}
    try {
    dis.read(retval);
    catch (IOException e){}
    return(retval);
    public int available()
    int avail;
    avail = 0;
    try {
    avail = dis.available();
    catch (IOException e) {}
    return(avail);
    Next, create the Text_io class as the application. Copy the following code
    into a file called �Text_io.java�.
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.*;
    public class Text_io extends Panel implements Runnable,
    TextListener {
    private tcpip gtp;
    String oldmessage = new String("");
    TextArea input_box = new TextArea("", 10, 60, 3);
    TextArea output_box = new TextArea("", 10, 60, 3);
    Thread timer;
    public Text_io(tcpip tp) {
    gtp = tp;
    setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.insets = new Insets(5,5,5,5);
    setBackground(java.awt.Color.lightGray);
    setSize(561,380);
    c.gridx = 0; c.gridy = 2; c.gridwidth = 1; c.gridheight =
    1;
    c.weightx = 0.0; c.weighty = 0.0; c.anchor =
    GridBagConstraints.WEST;
    c.fill = GridBagConstraints.NONE;
    add((new Label("To Device Server: (Type Here--->)")), c);
    //input_box
    input_box.addTextListener(this);
    c.gridx = 1; c.gridy = 2; c.gridwidth = 3; c.gridheight =
    1;
    c.weightx = 0.5; c.weighty = 0.0; c.anchor =
    GridBagConstraints.CENTER;
    c.fill = GridBagConstraints.BOTH;
    add(input_box,c);
    c.gridx = 0; c.gridy = 4; c.gridwidth = 1; c.gridheight =
    1;
    c.weightx = 0.0; c.weighty = 0.0; c.anchor =
    GridBagConstraints.WEST;
    c.fill = GridBagConstraints.NONE;
    add((new Label("From Device Server:")), c);
    c.gridx = 1; c.gridy = 4; c.gridwidth = 3; c.gridheight =
    1;
    c.weightx = 0.5; c.weighty = 0.0; c.anchor =
    GridBagConstraints.CENTER;
    c.fill = GridBagConstraints.BOTH;
    add(output_box,c);
    output_box.setEditable(false);
    timer = new Thread(this);
    timer.start();
    public void run() {
    int i;
    byte[] in;
    Thread me = Thread.currentThread();
    while (timer == me) {
    try {
    Thread.currentThread().sleep(200);
    catch (InterruptedException e) { }
    if ( (gtp != null) && ((i = gtp.available()) > 0) ) {
    in = gtp.receive();
    /* remove non-printing bytes */
    for (i = 0; i < in.length; i++) {
    if (in[i] < 0x20)
    in[i] = 0x20;
    output_box.append((new String(in)));
    public void textValueChanged(TextEvent e) {
    int len, i;
    String str = new String("");
    String message = input_box.getText();
    len = message.length() - oldmessage.length();
    if (len < 0) {
    for (i = 0; i < -len; i++)
    str += "\b";
    //System.out.println("Backspace");
    else if (len > 0) {
    str = message.substring(oldmessage.length());
    //System.out.println("len = "+str.length()+" str =
    "+str);
    oldmessage = message;
    if ( (len != 0) && (gtp != null) )
    gtp.send(str);
    Next, create the actual applet that uses the tcpip and Text_io classes. Copy
    the following code into a file called �Test.java�.
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.Applet;
    import java.net.*;
    import java.io.*;
    import java.lang.*;
    import java.text.*;
    import java.util.*;
    public class Test extends Applet {
    static private boolean isapplet = true;
    static private InetAddress arg_ip = null;
    static private int arg_port = 0;
    public tcpip gtp = null;;
    InetAddress reader_ip = null;
    int port = 10001;
    public void init()
    gtp = null;
    reader_ip = null;
    port = 10001;
    public void start()
    String st = new String("TCP/IP connection status: ");
    setFont(new Font("Dialog",Font.BOLD,16));
    setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.gridx = 0; c.gridy = 0; c.gridwidth = 1; c.gridheight
    = 1;
    c.anchor = GridBagConstraints.CENTER;
    c.fill = GridBagConstraints.BOTH;
    c.insets = new Insets(5,5,5,5);
    setBackground(Color.yellow);
    setSize(600,500);
    /* Either get the IP address from the HTTP server if
    we're an applet, or from the commandline (if passed).
    if (isapplet) {
    try{
    reader_ip = InetAddress.getByName(getCodeBase().getHost());
    catch (UnknownHostException e){}
    else {
    reader_ip = arg_ip;
    if (arg_port != 0) {
    port = arg_port;
    /* Open a socket to the Device Server's serial port
    if (reader_ip != null) {
    if (gtp == null) {
    gtp = new tcpip(reader_ip, port);
    if (gtp.s == null) {
    st += "Connection FAILED! ";
    gtp = null;
    if (gtp == null) {
    st += "Not Connected";
    add((new Label(st)), c);
    return;
    st += "Connected";
    add((new Label(st)), c);
    /* You may now perform IO with the Device Server via
    * gtp.send(byte[] data_out);
    * byte[] data_in = gtp.receive();
    * functions.
    * In our example we'll use two TextBoxes which have
    * been extended to handle IO to the Device Server.
    *Data typed in the upper text box will be sent to
    * the Device Server, and data received will be
    *displayed in the lower text box.
    /* Start of custom application code */
    /* ADD YOUR CODE HERE */
    c.gridx = 0; c.gridy = 2; c.gridwidth = 3; c.gridheight =
    1;
    c.anchor = GridBagConstraints.WEST;
    add((new Text_io(gtp)), c);
    /* End of custom application code */
    public void destroy()
    if (gtp != null)
    gtp.disconnect();
    gtp = null;
    public void stop() {
    public static void main(String[] args) {
    Frame frame = new Frame("TCP/IP Test");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    if (args.length > 0) {
    try{
    arg_ip = InetAddress.getByName(args[0]);
    catch (UnknownHostException e){}
    if (args.length > 1) {
    try {
    arg_port = Integer.valueOf(args[1]).intValue();
    catch (NumberFormatException e) {}
    Test ap = new Test();
    frame.add(ap);
    ap.init();
    isapplet = false;
    ap.start();
    frame.pack();
    frame.show();

    Let's see a decent try by you towards a solution first. I've found that usually the more thought and effort posters put into creating and solving their questions, the better their chances are of a volunteer here taking the time and effort to consider it and give a helpful answer. In other words, show that you are putting effort into doing your own homework first.
    Also, when posting your code, please use code tags so that your code will retain its formatting and be readable. To do this, you will need to paste already formatted code into the forum, highlight this code, and then press the "code" button at the top of the forum Message editor prior to posting the message. You may want to click on the Preview tab to make sure that your code is formatted correctly. Another way is to place the tag &#91;code] at the top of your block of code and the tag &#91;/code] at the bottom, like so:
    &#91;code]
      // your code block goes here.
      // note the differences between the tag at the top vs the bottom.
    &#91;/code]or
    {&#99;ode}
      // your code block goes here.
      // note here that the tags are the same.
    {&#99;ode}good luck

  • Please Find the error in this code

    Hi ,  I am new to ajax.My problem is that i cannot insert a value in to a textfield which is fetched from a database(MySql).  I have two jsp pages.Definition1.jsp and definition.jsp. I am giving the code below.[b]But it does not work[/b]. I don't know where is the problem. I am using Mozilla Firefox..  [b]Definition1.jsp[/b]  <html>  <%@ page language="java"%>  <%@page contentType="text/html" %>   <script language="Javascript" type="text/javascript">   function createRequestObject() { var tmpXmlHttpObject;   if (window.XMLHttpRequest) {   tmpXmlHttpObject = new XMLHttpRequest();       } else if (window.ActiveXObject) {   tmpXmlHttpObject = new ActiveXObject("Microsoft.XMLHTTP"); }  return tmpXmlHttpObject; }  //call the above function to create the XMLHttpRequest object var http = createRequestObject();  function makeGetRequest(wordId) { //make a connection to the server ... specifying that you intend to make a GET request  //to the server. Specifiy the page name and the URL parameters to send http.open('get','definition.jsp?id='+wordId);       //assign a handler for the response http.onreadystatechange = processResponse;       //actually send the request to the server http.send(null); }  function processResponse() { //check if the response has been received from the server if(http.readyState == 4){       //read and assign the response from the server           var result2 = http.responseText;  var result = http.responseXML.documentElement;                  //do additional parsing of the response, if needed            //in this case simply assign the response to the contents of the <div> on the page.  document.getElementById('description').innerHTML = result2;//[b]this works correctly[/b]           alert(result.getElementByTagName('p')[0].childNodes[0].nodeValue);//nothing happends here            document.getElementById('name').value=result.getElementsByTagName('p')[0].childNodes[0].nodeValue;           [u][b]//above code does not works and this is my problem[/b][/b[/u]] } }   </script> <body>  <form> <input type="text" id="name" size=10 value=" "></input>  </form> <h1>Have you heard these terms before?</h1>  Ceraunophobia More about Ceraunophobia<br> Astraphobia More about Astraphobia<br>   <div id="description">  </div>  </body>  </html>     [b]Definition.jsp[/b]    <%@ page language="java"%><%@ page import="java.sql.*,java.io.*,java.util.*,javax.servlet.*"%> <?xml version="1.0" encoding="UTF-8"?>  <% response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("pragma","no-cache"); Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection con=DriverManager.getConnection("jdbc:mysql://itserver:3306/manzor?user=root&password="); Statement st= con.createStatement(); Statement st1= con.createStatement();  ResultSet rs,rs1; String id=request.getParameter("id");  rs=st.executeQuery("select * from user where USERTYPE='"+id+"'");  if(rs.next()){    %>  // p tag is here , can't display it //<p> <p> <%=rs.getString(1)%></p>  //<p>  <%  }  %>[code]  [/code]  please help
    Message was edited by:
    manu_am
    Message was edited by:
    manu_am

    I'm not an AWT expert, but here's my best guess to the problem...
    I'm not sure that the ActionListener is the correct event listener to use here.
    I don't think the straight TextArea throws action events, I could be wrong here I mainly have experience with swing.
    What event are you trying to react to here? Also is there any reason for not using Swing? Then you can use the JTextArea.
    Hope I'm of some help :)

  • Check this code

    PLEASE compile this code on your pc and add some new items then try to update it using update button and we will see my problem clearly which
    is:
    I have a main window ,by clicking on (add new item) , another window
    open to fill the form
    on clicking on (save to file),my form will be saved in text file.
    if I open this text file using notepad for example,then I found my data
    stored but concatenated ,although I add to the saved string "\n"
    [hint:you will find two ## to direct u to this line in my code text]
    if I change it to "\n\n" then my data is stored in separate lines which
    I need.
    the Problem that when I read the saved file by clicking on "update data
    item" ,the returned
    data in the form is not as saved
    my code::
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class dataDictionary extends JFrame implements ActionListener
    JButton addItem,updateItem,searchItem,exit;
    JFileChooser filechooser;
    JTextField text1 ;
    JTextField text2 ;
    JTextField text3 ;
    JTextArea area4 ;
    JButton saveFile;
    public dataDictionary()
    super("Main Window");
    setSize(400,200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    addItem = new JButton("add new item");
    updateItem = new JButton("update data item");
    searchItem = new JButton("search for item");
    exit = new JButton ("Exit Program");
    addItem.addActionListener(this);
    updateItem.addActionListener(this);
    searchItem.addActionListener(this);
    exit.addActionListener(this);
    JLabel label = new JLabel("Data Dictionary Program");
    JPanel pane = new JPanel();
    pane.setLayout(new GridLayout(5,1,10,10));
    pane.add(label);
    pane.add(addItem);
    pane.add(updateItem);
    pane.add(searchItem);
    pane.add(exit);
    setContentPane(pane);
    setVisible(true);
    public dataDictionary (String name)
    super(name);
    setSize(350,500);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    text1 = new JTextField (30);
    text2 = new JTextField (30);
    text3 = new JTextField (30);
    area4 = new JTextArea (10,30);
    saveFile = new JButton("save to file");
    JLabel label1 = new JLabel ("Name");
    JLabel label2 = new JLabel ("Type");
    JLabel label3 = new JLabel ("Date");
    JLabel label4 = new JLabel ("Description");
    saveFile.addActionListener(this);
    JPanel pane =new JPanel();
    pane.add(label1);
    pane.add(text1);
    pane.add(label2);
    pane.add(text2);
    pane.add(label3);
    pane.add(text3);
    pane.add(label4);
    pane.add(area4);
    pane.add(saveFile);
    setContentPane(pane);
    area4.setLineWrap(true);
    area4.setWrapStyleWord(true);
    setVisible(true);
    public static void main (String[] args)
    dataDictionary main = new dataDictionary();
    public void actionPerformed (ActionEvent ave )
    Object ob = ave.getSource();
    if(ob == addItem )
    dataDictionary f= new dataDictionary( "form");
    if(ob==saveFile )
    String a = text1.getText()+"\n"+text2.getText()+"\n"+text3.getText() +"\n"+area4.getText();
    String f =text1.getText();
    saveInFile(a,f);
    JOptionPane.showMessageDialog(null,"The New Data Item save correctly");
    if(ob == updateItem)
    dataDictionary form= new dataDictionary ("form");
    File file = getAFileToOpen();
    writeFileToEditor(file);
    if(ob == searchItem)
    if(ob == exit)
    System.exit(0);
    public File getAFileToOpen()
    File file = null;
    File currentdirectory = new File(".");
    JFileChooser filechooser = new JFileChooser(currentdirectory);
    int replycode = filechooser.showOpenDialog(null);
    if (replycode == JFileChooser.APPROVE_OPTION){
    file = filechooser.getSelectedFile();
    return file;
    public void writeFileToEditor(File file)
    try{
    FileReader filereader = new FileReader(file);
    BufferedReader bufferedreader = new BufferedReader(filereader);
    String lineread = "";
    text1.setText(bufferedreader.readLine());
    text2.setText(bufferedreader.readLine());
    text3.setText(bufferedreader.readLine());
    while ((lineread = bufferedreader.readLine()) != null){
    area4.setText(lineread + "\n");
    filereader.close();
    }catch (IOException ioe){
    System.err.println("IOException: " + ioe.getMessage());
    public void saveInFile(String s,String fileName)
    try{
    File f=new File(fileName+".txt");;
    FileWriter fw = new FileWriter(f);
    StringReader sr = new StringReader(s);
    BufferedReader br = new BufferedReader(sr);
    String lineread = "";
    while((lineread=br.readLine()) != null )
    fw.write(lineread+"\n\r");
    fw.flush();
    fw.close();
    catch(IOException io){
    System.err.println();
    }

    This can't be called a good design but works fine and sound.
    Study this code and compare it against your original code.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class BlackHorse extends JFrame implements ActionListener{
      JButton addItem,updateItem,searchItem,exit;
      JFileChooser filechooser;
      JTextField text1 ;
      JTextField text2 ;
      JTextField text3 ;
      JTextArea area4 ;
      JButton saveFile;
      BlackHorse form;
      public BlackHorse(){
        super("Main Window");
        setSize(400,200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addItem = new JButton("add new item");
        updateItem = new JButton("update data item");
        searchItem = new JButton("search for item");
        exit = new JButton ("Exit Program");
        addItem.addActionListener(this);
        updateItem.addActionListener(this);
        searchItem.addActionListener(this);
        exit.addActionListener(this);
        JLabel label = new JLabel("Data Dictionary Program");
        JPanel pane = new JPanel();
        pane.setLayout(new GridLayout(5,1,10,10));
        pane.add(label);
        pane.add(addItem);
        pane.add(updateItem);
        pane.add(searchItem);
        pane.add(exit);
        setContentPane(pane);
        setVisible(true);
        form = new BlackHorse("form");
      public BlackHorse (String name){
        super(name);
        setSize(350,500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        text1 = new JTextField (30);
        text2 = new JTextField (30);
        text3 = new JTextField (30);
        area4 = new JTextArea (10,30);
        saveFile = new JButton("save to file");
        JLabel label1 = new JLabel ("Name");
        JLabel label2 = new JLabel ("Type");
        JLabel label3 = new JLabel ("Date");
        JLabel label4 = new JLabel ("Description");
        saveFile.addActionListener(this);
        JPanel pane = new JPanel();
        pane.add(label1);
        pane.add(text1);
        pane.add(label2);
        pane.add(text2);
        pane.add(label3);
        pane.add(text3);
        pane.add(label4);
        pane.add(area4);
        pane.add(saveFile);
        setContentPane(pane);
        area4.setLineWrap(true);
        area4.setWrapStyleWord(true);
        setVisible(false);
      public static void main (String[] args){
        BlackHorse main = new BlackHorse();
      public void actionPerformed (ActionEvent ave ){
        Object ob = ave.getSource();
        if (ob == addItem ){
          form.setVisible(true);
          form.text1.setText("");
          form.text2.setText("");
          form.text3.setText("");
          form.area4.setText("");
        else if (ob == saveFile){
          String a = text1.getText() + "\n"
                     + text2.getText() +"\n"
                     + text3.getText() +"\n"
                     + area4.getText() + "\n"; // just in case ....
          String f = text1.getText();
          saveInFile(a,f);
          JOptionPane.showMessageDialog(null,"The New Data Item save correctly");
        else if(ob == updateItem){
          form.setVisible(true);
          File file = getAFileToOpen();
          writeFileToEditor(file);
        else if(ob == searchItem){
        else if(ob == exit){
          System.exit(0);
      public File getAFileToOpen(){
        File file = null;
        JFileChooser filechooser = new JFileChooser(".");
        int replycode = filechooser.showOpenDialog(null);
        if (replycode == JFileChooser.APPROVE_OPTION){
          file = filechooser.getSelectedFile();
        return file;
      public void writeFileToEditor(File file){
        try{
          BufferedReader br = new BufferedReader(new FileReader(file));
          String lineread = "";
          form.text1.setText(br.readLine());
          form.text2.setText(br.readLine());
          form.text3.setText(br.readLine());
          form.area4.setText("");
          while ((lineread = br.readLine()) != null){
            form.area4.append(lineread + "\n");
          br.close();
        catch (IOException ioe){
          System.err.println("IOException: " + ioe.getMessage());
      public void saveInFile(String s, String fileName){
        try{
          File f = new File(fileName+".txt");
          PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(f)));
          StringReader sr = new StringReader(s);
          BufferedReader br = new BufferedReader(sr);
          String lineread = "";
          while ((lineread = br.readLine()) != null){
            pw.println(lineread);
          pw.close();
        catch(IOException io){
          System.err.println();
    }

  • Dbx cannot locate the (DLM) source codes correctly for 64bit app

    It's hard for me to prepare a test case. Because it seems for a simple "hello world" it works.
    The reason I raise this issue here is because my project was recently upgraded to compile with 64bit. And since then dbx cannot locate the source codes correctly, especially for some DLM codes. (sometimes it shows to "/usr/include/iso/..." which it should never be!). While it works fine on a 32bit compiled mode.
    Did anyone experience the similar situation and can share your idea?
    Thanks in advance.

    Can't think of any good reason why going to 64 bit would confuse dbx (except for unknown bug in dbx, which is not impossible).
    I'd first look for changes in your build - for example, 32-bit code used to go to bin/ directory, but 64-bit goes to bin/sparcv9, which happens to be a symlink somewhere else or something like that. Symlinks might sometimes confuse dbx, please read
    (dbx) help finding-filestopic (in dbx console, type "help finding-files").
    Since you are using CC 5.9 that generates DWARF info by default, location and even presence of .o files is not important. All debug info should be in the shared library itself.
    Here's another idea: inspect DWARF info by hand and see if it looks correct to you.
    $ dwarfdump a.out | lessLook for
                    DW_AT_name                  a.ccand
                    DW_AT_comp_dir              /home/maxim/tempThose two should give location of source file (/home/maxim/temp/a.cc in my case). Maybe this will give you some clue.

  • SNOTE (Note Assistant) list expected "source code corrections" of a note?

    Is it possible, in current versions of SNOTE, to print the "source code corrections" that the note is supposed to contain?
    This was possible in "good old OSS" and also, I think, in early versions of SNOTE.
    Why do I ask?
    Sometimes you have a note that SNOTE cannot handle by itself. You must then open the "splitscreen editor" and guide SNOTE through the process.
    In such cases I like to have a listing, on paper, of the expected changes, so that I keep some overview and that I can check the corrections as I go through them.

    I have found a second possibility - the following little program based on some code found in the 4.6C implementation of SNOTE.
    report  zztmp_snote_displ line-size 080.
    type-pools bcwbn.
    parameter p_note like cwbnthead-numm.
    data gs_note type bcwbn_note.
    start-of-selection.
      clear gs_note.
      select numm versno
        from  cwbnthead
        into (gs_note-key-numm,gs_note-key-versno)
             where  numm        = p_note
             and    incomplete  = space
             order by primary key.
      endselect.
      if not ( gs_note-key is initial ) .
        call function 'SCWB_NOTE_READ'
          exporting
            iv_read_attributes                = 'X'
            iv_read_short_text                = 'X'
            iv_read_all_texts                 = 'X'
            iv_read_validity                  = 'X'
            iv_read_corr_instructions         = 'X'
            iv_read_customer_logfile          = 'X'
            iv_use_fallback_languages         = 'X'
            iv_read_loghndl                   = 'X'
            iv_read_fixes                     = 'X'
            iv_read_customer_attributes       = 'X'
    *   IV_READ_READ_BY_USER              = ' '
    *   IV_READ_SOL_MGR_REFERENCE         = ' '
    *   IV_READ_SAP_STATUS                = ' '
          changing
            cs_note                           = gs_note
          exceptions
            note_not_found                    = 1
            language_not_found                = 2
            unreadable_text_format            = 3
            corr_instruction_not_found        = 4
            others                            = 5
        if sy-subrc eq 0.
          call function 'SCWB_NOTE_DISPLAY'
            changing
              cs_note = gs_note.
        endif.
      endif.

  • Can soemone explain this code to me

    can someone explain this code to me
    import javax.swing.*;
    import BreezySwing.*;
    import java.util.Random;
    public class PennyPinch extends GBFrame
         private JButton enterButton;
         private JTextArea outputArea;
         private int[][] board = {{1,1,1,1,1},{1,2,2,2,1},{1,2,3,2,1},{1,2,2,2,1},{1,1,1,1,1}};
         private boolean[][] landing = new boolean[5][5];
         private int total;
         public PennyPinch()
         enterButton = addButton ("Pitch",2,1,1,1);
         outputArea = addTextArea("",4,1,3,4);
         public void pitch()
              Random generator = new Random();          
              int randomRow = generator.nextInt(5);
              int randomColumn = generator.nextInt(5);
              total += board[randomRow][randomColumn];
              landing[randomRow][randomColumn] = true;
         public void buttonClicked (JButton buttonObj)
              pitch();
              displayList(board, outputArea);
         private void displayList(int a[][], JTextArea output)
    output.setText("");
              for (int row = 0; row < 5; row++)
    for (int col = 0; col < 5; col++){
    if(landing[row][col] ==true)
                                  output.append(Format.justify('r',"P", 3) + " ");
                                  if (col == 4)
    output.append("\n");
                             else
                             output.append(Format.justify('r', a[row][col], 3) + " ");
                             if (col == 4)
    output.append("\n");                    }
              output.append("the total is " + total);
         public static void main (String[] args)
    PennyPinch theGUI = new PennyPinch();
    theGUI.setSize (300, 300);
    theGUI.setVisible(true);
    }

    Knowing toilets or studying under George?What kind pervert are you?
    What is written in public toilets o/c!Ah yes I see, I found example questions.
    2:3.4 please complete the following well known saying
    by filling in the blank
    Whilst you are reading what I put
    You are blank on your foot
    2:3.5 Upon seeing the announcement 'Toilet
    tennis' and following the instruction ' please
    see other wall for details' what is the standard
    message on the other wall.2:3.4. is the correct answer 'micturating' ?
    2:3.5. I believe the answer is Ibidem.

  • Performance issue in this code

    public int[][] init(int[][] a, int m, int n){
      for(int j=0; j<n; j++){
        for(int i=0; i<m; i++){
          a[i][j] = i+j;
      return a;
    }Just a technical quest faced in one of the interview...
    There is a performance issue in this code. Can you identify, correct and justify your answer?
    Edited by: EJP on 17/10/2011 20:29

    mithu wrote:
    public int[][] init(int[][] a, int m, int n){
    for(int j=0; j<n; j++){
    for(int i=0; i<m; i++){
    a[i][j] = i+j;
    return a;
    }Just a technical quest faced in one of the interview...
    There is a performance issue in this code. Can you identify, correct and justify your answer?Not a good question at all. There's no performance issue here that can be positively identified by inspection. The only potentially significant one is, as EJP pointed out, loss of locality of reference because of the order of the loops. But even that's not a guarantee, since I don't think array layouts are defined by the spec. We could only determine for sure that that's a performance problem by profiling.

Maybe you are looking for

  • Runtime error when executing driver program

    when im executing my report after passing smartform to it , by giving invoice number in selectionscreen,it's generating runtime error as the call to the function module     '/1BCDWB/SF00000032'   is incorrect: in the function module interface, u can

  • TURNING ON MY COMPUTER

    I HOPE SOME BODY CAN HELP ME WITH THIS PROBLEM. WHEN I TURN ON MY COMP A SMALL SQUARE APPEARS IN SIDE THE SQUARE IS A BLUE GLOBE LIKE CIRCLE. THIS CONTINUES FOR ABOUT 10 MINUTES THEN IT DISAPEARS AND IS REPLACED BY A SMALL SQUARE WITH A MANS PROFILE

  • Login error wwc-41655.  Urgent.  Production is down.

    My client has been using portal 9.03 something for a while now but has recently run into a problem. They can no longer log in. Any attempt returns the error message: There is an error in the setup of the directory used for authentication. Please cont

  • Attached style sheet wont work

    Hi, Im on the cs3 in a winxpPro environment. Start cs3 Create simple page Link in a style sheet for simplicity I just grabbed one of dreamweavers <link href="file:///C|/websites/membership design/system/application/CSS/Level1_Arial.css" rel="styleshe

  • Regarding Jar file

    Hi, i need to download a jar file which would help me in accessing the methods present in IWD Bussiness Graphics Interface. Can you please let me help in these. Regards, Raju