JTextField.setText() please help...

i have a field in my table that is in date format.
txtempdate.setText(rsmastempl.getDate("empdate"));
this produce an error.
how will i display my date filed in my table in a TextBox?
thank you for helping.
killuasoft

Christ boy! Did that hurt?
Try txtempdate.setText(String.valueOf(whatever));
I'm pretty drunk now, so I'm gonna hit the party.
L8r

Similar Messages

  • How to empty the JTextField automatically? Please HELP me.

    Hello,
    This is my full listing program:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    public class PortGUI extends JFrame
         private     JButton btOk;
         private JButton btCancel;
         private     JButton btReply;
         private     JLabel lblServIP;
         private     JLabel lblAuth;
         private JLabel lblThrd;
         private JLabel lblAcc;
         private JLabel lblMax;
         private JLabel lblAuthent;
         private JLabel lblAdm;
         private JLabel lblReplServ;
         private JCheckBox chkUsers;
         private JCheckBox chkEnbDbg;
         private JOptionPane pnlErr = new JOptionPane();
         public PortGUI()
              // Create main panel
              JPanel topPanel     = new JPanel();
              topPanel.setLayout(null);
              getContentPane().add( topPanel );
         // Create Server Settings panel
              JPanel panelsett = new JPanel();
              panelsett.setLayout(null);
              panelsett.setBounds(5,5,680, 200);
              // panelsett containers
              final JTextField fldServIP = new JTextField();
              fldServIP.setBounds( 160, 30, 100, 25 );
              fldServIP.setFocusAccelerator( 'v' );
              panelsett.add(fldServIP);
              lblServIP = new JLabel( "Server IP"     );
              lblServIP.setBounds( 20, 30, 100, 25 );
              lblServIP.setLabelFor(     fldServIP );
              panelsett.add(lblServIP);
              final JTextField fldAuth = new JTextField();
              fldAuth.setBounds( 600, 30, 50, 25 );
              fldAuth.setFocusAccelerator( 'v' );
              panelsett.add(fldAuth);
              lblAuth = new JLabel( "Incoming Radius Authentication Port");
              lblAuth.setBounds( 350, 30, 300, 25 );
              lblAuth.setLabelFor(fldAuth);
              panelsett.add(lblAuth);                                        
              final JTextField fldThrd =     new     JTextField();
              fldThrd.setBounds( 160, 60, 50, 25 );
              fldThrd.setFocusAccelerator( 'a' );
              panelsett.add(fldThrd);
              lblThrd = new JLabel( "Worker Threads" );
              lblThrd.setBounds( 20, 60, 100, 25 );
              lblThrd.setLabelFor(fldThrd);
              panelsett.add(lblThrd);
              final JTextField fldAcc =     new     JTextField();
              fldAcc.setBounds( 600, 60, 50, 25 );
              fldAcc.setFocusAccelerator( 'a' );
              panelsett.add( fldAcc );
              lblAcc = new JLabel( "Incoming Radius Accounting Port" );
              lblAcc.setBounds( 350, 60, 300, 25 );
              lblAcc.setLabelFor(     fldAcc );
              panelsett.add( lblAcc );
              final JTextField fldMax =     new     JTextField();
              fldMax.setBounds( 160, 90, 50, 25 );
              fldMax.setFocusAccelerator( 'c' );
              panelsett.add( fldMax );
              lblMax = new JLabel( "Maximum Consoles" );
              lblMax.setBounds( 20, 90, 200, 25 );
              lblMax.setLabelFor(     fldMax );
              panelsett.add(lblMax);
              // Create combo box
              String[] AuthStrings = {"Local Server", "Proxy Server", "Local and Proxy"};
              JComboBox AuthList = new JComboBox(AuthStrings);
              AuthList.setSelectedIndex(2);
              AuthList.setSelectedItem(null);
              AuthList.setBounds(450, 90, 200, 25);
              panelsett.add(AuthList);          
              lblAuthent = new JLabel( "Authenticator" );
              lblAuthent.setBounds( 350, 90, 100, 25 );
              lblAuthent.setLabelFor(     AuthList);
              panelsett.add(lblAuthent);
              final JTextField fldAdm =     new     JTextField();
              fldAdm.setBounds( 160, 120, 50, 25 );
              fldAdm.setFocusAccelerator( 'c' );
              panelsett.add( fldAdm );
              lblAdm = new JLabel( "Admin TCP Port" );
              lblAdm.setBounds( 20, 120, 150, 25 );
              lblAdm.setLabelFor(     fldAdm );
              panelsett.add(lblAdm);
              // create checkbox
              chkUsers = new JCheckBox("Cache Users in Memory");
              chkUsers.setBounds(350, 120, 250, 25);
    chkUsers.setMnemonic('m');
    chkUsers.setSelected(false);
    panelsett.add(chkUsers);
              final JTextField fldReplServ =     new     JTextField();
              fldReplServ.setBounds( 160, 150, 100, 25 );
              fldReplServ.setFocusAccelerator( 'c' );
              panelsett.add( fldReplServ );
              lblReplServ = new JLabel( "Replication Server IP" );
              lblReplServ.setBounds( 20, 150, 200, 25 );
              lblReplServ.setLabelFor(fldReplServ);
              panelsett.add(lblReplServ);
              chkEnbDbg = new JCheckBox("Enable Debug Trace Output");
    chkEnbDbg.setBounds(350, 150, 250, 25);
    chkEnbDbg.setMnemonic('n');
    chkEnbDbg.setSelected(false);
    panelsett.add(chkEnbDbg);
              Border etched;
              etched = BorderFactory.createLoweredBevelBorder();
         TitledBorder title;
         title = BorderFactory.createTitledBorder(etched, "Server Settings");
    title.setTitleJustification(TitledBorder.LEFT);
    panelsett.setBorder(title);
    topPanel.add(panelsett);
              // Create a button
              btOk = new JButton( "OK" );
              btOk.setBorder(BorderFactory.createRaisedBevelBorder());
              btOk.setBounds( 170, 270, 100, 35 );
              btOk.setEnabled(false );
              topPanel.add(btOk);
              btReply = new JButton( "Apply" );
              btReply.setBorder(BorderFactory.createRaisedBevelBorder());
              btReply.setBounds( 300, 270, 100, 35 );
              topPanel.add(btReply);
              btCancel = new JButton( "Cancel" );
              btCancel.setBorder(BorderFactory.createRaisedBevelBorder());
              btCancel.setBounds( 420, 270, 100, 35 );
              btCancel.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
         System.exit(0);
              topPanel.add(btCancel);
              // Action for each components
              fldServIP.getDocument().addDocumentListener(new DocumentListener()
                   public void     insertUpdate( DocumentEvent event )
                        String     sString     = fldServIP.getText();
                        try     
                             int     iValue = Integer.parseInt( sString );
                             btOk.setEnabled( true );
                        catch( NumberFormatException e )
                             if(     fldServIP.getText().length() == 4 )
                   JOptionPane.showMessageDialog(pnlErr,
    "Please try again",
    "Error Message",
    JOptionPane.ERROR_MESSAGE);
    public void removeUpdate( DocumentEvent event )
         // Prevent the user     from entering a blank field
         if(     fldServIP.getText().length() == 0 )
         btOk.setEnabled( false );
         else
              // Do the same error checking as insertUpdate()
              insertUpdate( event );
    public void changedUpdate( DocumentEvent event )
         // Nothing to do here
              fldAuth.getDocument().addDocumentListener(new DocumentListener()
                   public void     insertUpdate( DocumentEvent event )
                        String     sString     = fldAuth.getText();
                        try     
                             int     iValue = Integer.parseInt( sString );
                             btOk.setEnabled( true );
                        catch( NumberFormatException e )
                             if(     fldAuth.getText().length() == 4 )
                   JOptionPane.showMessageDialog(pnlErr,
    "Please try again",
    "Error Message",
    JOptionPane.ERROR_MESSAGE);
    public void removeUpdate( DocumentEvent event )
         // Prevent the user     from entering a blank field
         if(     fldAuth.getText().length() == 0 )
         btOk.setEnabled( false );
         else
              // Do the same error checking as insertUpdate()
              insertUpdate( event );
    public void changedUpdate( DocumentEvent event )
         // Nothing to do here
         fldThrd.getDocument().addDocumentListener(new DocumentListener()
                   public void     insertUpdate( DocumentEvent event )
                        String     sString     = fldThrd.getText();
                        try     
                             int     iValue = Integer.parseInt( sString );
                             btOk.setEnabled( true );
                        catch( NumberFormatException e )
                             if(     fldThrd.getText().length() == 4 )
                   JOptionPane.showMessageDialog(pnlErr,
    "Please try again",
    "Error Message",
    JOptionPane.ERROR_MESSAGE);
    public void removeUpdate( DocumentEvent event )
         // Prevent the user     from entering a blank field
         if(     fldThrd.getText().length() == 0 )
         btOk.setEnabled( false );
         else
              // Do the same error checking as insertUpdate()
              insertUpdate( event );
    public void changedUpdate( DocumentEvent event )
         // Nothing to do here
    fldAcc.getDocument().addDocumentListener(new DocumentListener()
                   public void     insertUpdate( DocumentEvent event )
                        String     sString     = fldAcc.getText();
                        try     
                             int     iValue = Integer.parseInt( sString );
                             btOk.setEnabled( true );
                        catch( NumberFormatException e )
                             if(     fldAcc.getText().length() == 4 )
                   JOptionPane.showMessageDialog(pnlErr,
    "Please try again",
    "Error Message",
    JOptionPane.ERROR_MESSAGE);
    public void removeUpdate( DocumentEvent event )
         // Prevent the user     from entering a blank field
         if(     fldAcc.getText().length() == 0 )
         btOk.setEnabled( false );
         else
              // Do the same error checking as insertUpdate()
              insertUpdate( event );
    public void changedUpdate( DocumentEvent event )
         // Nothing to do here
    fldMax.getDocument().addDocumentListener(new DocumentListener()
                   public void     insertUpdate( DocumentEvent event )
                        String     sString     = fldMax.getText();
                        try     
                             int     iValue = Integer.parseInt( sString );
                             btOk.setEnabled( true );
                        catch( NumberFormatException e )
                             if(     fldMax.getText().length() == 4 )
                   JOptionPane.showMessageDialog(pnlErr,
    "Please try again",
    "Error Message",
    JOptionPane.ERROR_MESSAGE);
    public void removeUpdate( DocumentEvent event )
         // Prevent the user     from entering a blank field
         if(     fldMax.getText().length() == 0 )
         btOk.setEnabled( false );
         else
              // Do the same error checking as insertUpdate()
              insertUpdate( event );
    public void changedUpdate( DocumentEvent event )
         // Nothing to do here
    fldAdm.getDocument().addDocumentListener(new DocumentListener()
                   public void     insertUpdate( DocumentEvent event )
                        String     sString     = fldAdm.getText();
                        try     
                             int     iValue = Integer.parseInt( sString );
                             btOk.setEnabled( true );
                        catch( NumberFormatException e )
                             if(     fldAdm.getText().length() == 4 )
                   JOptionPane.showMessageDialog(pnlErr,
    "Please try again",
    "Error Message",
    JOptionPane.ERROR_MESSAGE);
    public void removeUpdate( DocumentEvent event )
         // Prevent the user     from entering a blank field
         if(     fldAdm.getText().length() == 0 )
         btOk.setEnabled( false );
         else
              // Do the same error checking as insertUpdate()
              insertUpdate( event );
    public void changedUpdate( DocumentEvent event )
         // Nothing to do here
    fldReplServ.getDocument().addDocumentListener(new DocumentListener()
                   public void     insertUpdate( DocumentEvent event )
                        String     sString     = fldReplServ.getText();
                        try     
                             int     iValue = Integer.parseInt( sString );
                             btOk.setEnabled( true );
                        catch( NumberFormatException e )
                             if(     fldReplServ.getText().length() == 4 )
                   JOptionPane.showMessageDialog(pnlErr,
    "Please try again",
    "Error Message",
    JOptionPane.ERROR_MESSAGE);
    public void removeUpdate( DocumentEvent event )
         // Prevent the user     from entering a blank field
         if(     fldReplServ.getText().length() == 0 )
         btOk.setEnabled( false );
         else
              // Do the same error checking as insertUpdate()
              insertUpdate( event );
    public void changedUpdate( DocumentEvent event )
         // Nothing to do here
         public static void main(String[] args)
              //int windowWidth, windowHeight;
              int windowWidth = 700;
    int windowHeight = 400;
              PortGUI window = new PortGUI();
              window.setTitle("");
              Dimension windowSize = window.getSize();
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              window.setSize(windowWidth, windowHeight);
              window.setLocation((screenSize.width - windowWidth) / 2, (screenSize.height - windowHeight) / 2);
              window.setVisible(true);
              window.setResizable(false);
    On that listing program, my problem is in field document listener, that is:
    fldThrd.getDocument().addDocumentListener(new DocumentListener()
                   public void     insertUpdate( DocumentEvent event )
                        String     sString     = fldThrd.getText();
                        try     
                             int     iValue = Integer.parseInt( sString );
                             btOk.setEnabled( true );
                        catch( NumberFormatException e )
                             if(     fldThrd.getText().length() == 4 )
                   JOptionPane.showMessageDialog(pnlErr,
    "Please try again",
    "Error Message",
    JOptionPane.ERROR_MESSAGE);
    if I execute this program, the textfield can only receive integer input. If input is string til 4 times, the dialog panel will display error message. After that, textfield must be empty (delete automatically).
    I want to ask you about how I can emptying that textfield automatically after the dialog panel is appear?
    Please help me to get out from my problem.
    Thank's for your help,
    har

    Hi,
    To empty the text file, use the method setText("").
    eg. fldServIP.setText("");
    fldServIP is one of your textfield. So whereever you are showing the dialog box, use setText("") for the corresponding textfields.
    All the best

  • SetText() is not working ....please help

    hello all,
    i am really stuck at something silly in my program, my code is huge to post in here, so i will try to describe as much as i can.
    well my problem is i have a class which listen to a socket, when some data has been changed, i want it to modify a JPanel in "another" class, which is the main class of my GUI, by changing the text in that panel.
    i am using setText(Sting), but it doesnt work.
    i tried to call a method from the listen class to the main and that method have a print statment and setText() call, i checked that the statment is being printed, "which tells me that the listen class is calling that method in the main class, but the text doesnt change.. i tried repaint, revalidate... please help ..
    thx for ur time.

    i am trying to give u the closest picture of my code:
    public class SetTextTest extends JPanel{
         public JPanel updateHistory;
         private JButton updateHistoryButton;
    public JLabel updateLabel;
         public String updateStatus = "Updates: ";
         String updatesList ="";
    String updatesIds="", updatesTimes="";
         int numOfupdates = 0;
         public SetTextTest() {
              super(new BorderLayout());
              updateHistory = new JPanel();
              //Set up Updates History Panel
              updateHistory.setLayout(new BoxLayout(updateHistory,BoxLayout.Y_AXIS));//new BorderLayout());
              updateHistory.setMaximumSize(new Dimension(300,250));
              updateLabel = new JLabel(updateStatus + numOfupdates);
              updateHistoryButton = new JButton("Check Updates");
              updateHistoryButton.setPreferredSize(new Dimension(120,25));
              updateHistoryButton.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        //open a table
         updateHistory.add(updateLabel);
         updateHistory.add(updateHistoryButton);
         public void newUpdates(){
              numOfupdates++;
              java.awt.Toolkit.getDefaultToolkit().beep();
              System.out.println(updateStatus + numOfupdates);
              updateLabel.setText(updateStatus + numOfupdates);
    }

  • Please help me to avoid this Exception.

    I have a JTextField which will accept only non-negative integer. To get the Document roll_doc for the constructor of JTextField
    I have a class maxLengthText which will make sure that the JTextfield accepts only non-negative integer.
    I have a problem while resetting the content of the JTextField. As I have made sure that only integers are allowed in my text field.
    So while using setText(" "). The code executes the exception in my actionListener. I don't want this exceptuion to get executed when I reset the content of my JTextField using setText(String).
    Please help. Suggest any workaround for this. Thanks in advance
    The code is as follows:
    package marksheet;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.BorderFactory;
    import javax.swing.*;
    import javax.swing.text.*;
    public class SpringApplet1 extends JApplet implements ActionListener {
         JLabel l_instruction1;
         JLabel l_instruction2;
         JLabel l_instruction3;
         JLabel l_instruction4;
         JLabel l_instruction5;
         JLabel l_instruction6;
         JLabel l_instruction7;
         JLabel l_instruction8;
         JLabel l_space;
         JLabel label1;
         JLabel label2;
         JLabel label3;
         JLabel label4;
         JTextField text1;
         JTextField text2;
         JTextField text3;
         JTextField text4;
         JLabel l_name;
         JLabel l_fname;     
         JLabel l_course;
         JLabel l_specialization;
         JLabel l_batch;
         JLabel l_semester;
         JLabel l_rollno;
         JLabel l_enrolno;
         JTextField t_name;
         JTextField t_fname;
         JTextField t_rollno;
         JTextField t_enrollno;
         JComboBox cb_course;
         JComboBox cb_branch;
         JComboBox cb_batch;
         JComboBox cb_semester;
         JCheckBox c_parttime;
         JCheckBox c_fulltime;
         JButton Submit;
         JButton enterMarks;
         JButton reset;
         JTextField txtInt;
         JPanel p;
         JPanel p1;
         JPanel p2;
         JPanel p3;
         public void init () {
         l_space = new JLabel(" ");
         Document roll_doc = new maxLengthText(5); // set maximum length to 5
         Document enroll_doc = new maxLengthText(6); // set maximum length to 6
         t_rollno= new JTextField(roll_doc, "", 6);
         t_enrollno= new JTextField(enroll_doc, "", 7);
         Document name_doc = new maxLengthAlpha(15); // set maximum length to 15
         t_name = new JTextField(name_doc, "", 7);
         l_instruction1 = new JLabel("All names should be alphabets",JLabel.LEFT);
         l_instruction1.setForeground(Color.blue);
         l_instruction1.setVisible(false);
         l_instruction1.setVisible(true);
         l_instruction2 = new JLabel("Name can not be greater than 15 characters",JLabel.LEFT);
         l_instruction2.setForeground(Color.blue);
         l_instruction2.setVisible(false);
         l_instruction2.setVisible(true);
         l_instruction3 = new JLabel("Seperate firstname and last name with a 'space'",JLabel.LEFT);
         l_instruction3.setForeground(Color.blue);
         l_instruction3.setVisible(false);
         l_instruction3.setVisible(true);
         l_instruction4 = new JLabel("All marks are out of 100, Marks obtained are non-negative integers",JLabel.LEFT);
         l_instruction4.setForeground(Color.blue);
         l_instruction4.setVisible(false);
         l_instruction4.setVisible(true);
         l_instruction8 = new JLabel("Marks obtained can not be greater than 100 ",JLabel.LEFT);
         l_instruction8.setForeground(Color.blue);
         l_instruction8.setVisible(false);
         l_instruction8.setVisible(true);
         l_instruction5 = new JLabel("Roll number should be of length 5 and only numeric",JLabel.LEFT);
         l_instruction5.setForeground(Color.blue);
         l_instruction5.setVisible(false);
         l_instruction5.setVisible(true);
         l_instruction6 = new JLabel("Enrolment number should be of length 6 and only numeric",JLabel.LEFT);
         l_instruction6.setForeground(Color.blue);
         l_instruction6.setVisible(false);
         l_instruction6.setVisible(true);
         l_instruction7 = new JLabel("All fields are Mandatory",JLabel.LEFT);
         l_instruction7.setForeground(Color.blue);
         l_instruction7.setVisible(false);
         l_instruction7.setVisible(true);
         l_name = new JLabel("Name",JLabel.LEFT);
         l_name.setForeground(Color.blue);
         l_fname = new JLabel("Father's Name",JLabel.LEFT);
         l_fname.setForeground(Color.blue);
         l_course = new JLabel("Course",JLabel.LEFT);
         l_course.setForeground(Color.blue);
         l_specialization = new JLabel("Specialization",JLabel.LEFT);
         l_specialization.setForeground(Color.blue);
         l_batch = new JLabel("Batch",JLabel.LEFT);
         l_batch.setForeground(Color.blue);
         l_semester = new JLabel("Semester",JLabel.LEFT);
         l_semester.setForeground(Color.blue);
         l_rollno = new JLabel("Roll Number",JLabel.LEFT);
         l_rollno.setForeground(Color.blue);
         l_enrolno = new JLabel("Enrolment Number",JLabel.LEFT);
         l_enrolno.setForeground(Color.blue);
         //t_name = new JTextField(20);
         t_name.setEditable(true);
    //     t_name.setBackground(Color.YELLOW);
         t_fname = new JTextField(20);
         t_fname.setEditable(true);
    //     t_fname.setBackground(Color.YELLOW);
         //t_rollno = new JTextField(20);
         t_rollno.setEditable(true);
    //     t_rollno.setBackground(Color.YELLOW);
         //t_enrollno = new JTextField(20);
         t_enrollno.setEditable(true);
    //     t_enrollno.setBackground(Color.YELLOW);
         label1 = new JLabel("Data Structures",JLabel.LEFT);
         label1.setForeground(Color.blue);
         label1.setVisible(true);
         label2 = new JLabel("Compiler Design",JLabel.LEFT);
         label2.setForeground(Color.blue);
         label2.setVisible(true);
         label3 = new JLabel("Numerical Analysis",JLabel.LEFT);
         label3.setForeground(Color.blue);
         label3.setVisible(true);
         label4 = new JLabel("Discrete Matehmatics",JLabel.LEFT);
         label4.setForeground(Color.blue);
         label4.setVisible(true);
         text1 = new JTextField(20);
         text1.setEditable(false);
    //     text1.setBackground(Color.green);
         text1.setVisible(true);
         text2 = new JTextField(20);
         text2.setEditable(false);
    //     text2.setBackground(Color.green);
         text2.setVisible(true);
         text3 = new JTextField(20);
         text3.setEditable(false);
    //     text3.setBackground(Color.green);
         text3.setVisible(true);
         text4 = new JTextField(20);
         text4.setEditable(false);
    //     text4.setBackground(Color.green);
         text4.setVisible(true);
         String a_course[] =
              {" ","BE","MCA"};
         String a_branch[] =
              {" ","Computer Science","Electronics"};
         String a_batch[] =
              {" ","2000-2001","2001-2002","2002-2003","2003-2004","2004-2005"};
         String a_semester[] =
              {" ","I","II","III","IV","V","VI","VII","VIII"};
         cb_course = new JComboBox(a_course);
         cb_branch = new JComboBox(a_branch);
         cb_batch = new JComboBox(a_batch);
         cb_semester = new JComboBox(a_semester);
         c_parttime = new JCheckBox("Part Time");
         c_fulltime = new JCheckBox("Full Time");
         Submit = new JButton ("Generate Marksheet");
         Submit.setVisible(true);
    //     Submit.addActionListener(this);
         enterMarks = new JButton ("Enter Marks");
         enterMarks.setVisible(true);
    // enterMarks.addActionListener(this);
         reset= new JButton ("Reset");
         reset.setVisible(true);
    //reset.addActionListener(this);
         p = new JPanel(new GridLayout(5,2,2,2));
    p.setBorder(BorderFactory.createTitledBorder("Student Details"));
         p.add(l_name);
         p.add(t_name);
    p.add(l_fname);
         p.add(t_fname);
    p.add(l_rollno);
         p.add(t_rollno);
    p.add(l_enrolno);
         p.add(t_enrollno);
         p.add(l_space);
         p.add(l_space);
         p1 = new JPanel(new GridLayout(0,2,2,2));
         p1.setBorder(BorderFactory.createTitledBorder("Course Details"));
         p1.add(l_course);
         p1.add(cb_course);
         p1.add(l_specialization);
         p1.add(cb_branch);
         p1.add(l_batch);
         p1.add(cb_batch);
         p1.add(l_semester);
         p1.add(cb_semester);
         p1.add(c_parttime);
         p1.add(c_fulltime);
         p1.add(reset);
         p1.add(enterMarks);
         p2 = new JPanel(new GridLayout(0,2,2,2));
         p2.setBorder(BorderFactory.createTitledBorder("Marks Details"));
         p2.add(label1);
         p2.add(text1);
         p2.add(label2);
         p2.add(text2);
         p2.add(label3);
         p2.add(text3);
         p2.add(label4);
         p2.add(text4);
         p2.add(Submit);
         p2.setVisible(true);
         p3 = new JPanel(new GridLayout(0,1,2,2));
         p3.setBorder(BorderFactory.createTitledBorder("Instructions"));
         p3.add(l_instruction1);
         p3.add(l_instruction2);
         p3.add(l_instruction3);
         p3.add(l_instruction4);
         p3.add(l_instruction8);
         p3.add(l_instruction5);
         p3.add(l_instruction6);
         p3.add(l_instruction7);
         JFrame f = new JFrame("Student Marksheet System");
    f.getContentPane().setLayout(new GridLayout(2,2,3,3));
    f.getContentPane().add(p3);
         f.getContentPane().add(p);
    f.getContentPane().add(p1);
         f.getContentPane().add(p2);
         enterMarks.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                   String message = "Are you sure all information is correct";
                   String get_text1;
                   String title = "Confirmation";
                   int getcourseindex;
                   int getbranchindex;
                   int getsemesterindex;
                   int getbatchindex;
                   getcourseindex = cb_course.getSelectedIndex();
                   getbranchindex = cb_branch.getSelectedIndex();
                   getsemesterindex = cb_semester.getSelectedIndex();
                   getbatchindex = cb_branch.getSelectedIndex();
                   if (c_fulltime.isSelected() == false && c_parttime.isSelected() == false)
                        JOptionPane.showMessageDialog(null,"Atleast one mandatory field is missing","TextField",1);
                             return;
                   if(getcourseindex == 0)
                             JOptionPane.showMessageDialog(null,"Atleast one mandatory field is missing","TextField",1);
                             return;
                   if(getbranchindex == 0)
                             JOptionPane.showMessageDialog(null,"Atleast one mandatory field is missing","TextField",1);
                             return;
                   if(getsemesterindex == 0)
                             JOptionPane.showMessageDialog(null,"Atleast one mandatory field is missing","TextField",1);
                             return;
                   if(getbatchindex == 0)
                             JOptionPane.showMessageDialog(null,"Atleast one mandatory field is missing","TextField",1);
                             return;
                   int n = JOptionPane.showConfirmDialog(null,message,title, JOptionPane.YES_NO_OPTION);
                   if(n==0)
                        get_text1 = t_name.getText();
                        t_name.setEditable(false);
                        t_fname.setEditable(false);
                        t_rollno.setEditable(false);
                        t_enrollno.setEditable(false);     
                        cb_course.setEnabled(false);     
                        cb_branch.setEnabled(false);     
                        cb_batch.setEnabled(false);     
                        cb_semester.setEnabled(false);
                        reset.setEnabled(false);
         reset.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                   String message = "Are you sure to reset the fields";
                   String title = "Confirmation";
                   int n = JOptionPane.showConfirmDialog(null,message,title, JOptionPane.YES_NO_OPTION);
                   if(n==0)
                        Submit.setEnabled(true);
                        cb_course.setSelectedIndex(0);
                        cb_branch.setSelectedIndex(0);
                        cb_batch.setSelectedIndex(0);
                        cb_semester.setSelectedIndex(0);
                        t_rollno.setText("");
         Submit.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                   String message = "Confirmation will generate the marksheet";
                   String title = "Confirmation";
                   int n = JOptionPane.showConfirmDialog(null,message,title, JOptionPane.YES_NO_OPTION);
                   if(n==0)
                        Submit.setEnabled(true);
         c_parttime.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                   if (c_fulltime.isSelected() == true)
                        c_fulltime.setSelected(false);
         c_fulltime.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                   if (c_parttime.isSelected() == true)
                        c_parttime.setSelected(false);
    f.pack();
    f.setVisible(true);
         public void paint(Graphics g) {
         //Draw a Rectangle around the applet's display area.
    g.drawRect(0, 0, size().width - 1, size().height - 1);
         public void actionPerformed(ActionEvent event){
         package marksheet;
         import javax.swing.*;
         import javax.swing.text.*;
         import java.awt.*;
         public class maxLengthText extends PlainDocument
              int maxVal=0;
              public maxLengthText(int maxLength)
                   maxVal = maxLength;
              publ1ic void insertString(int offset, String str, AttributeSet a) throws BadLocationException
                   if (getLength() + str.length() > maxVal)
                        return;
                   else
                        try
                             if(!Double.isNaN(Double.parseDouble(str)))
                                  super.insertString(offset, str, a);
                        catch(Exception e)
                             JOptionPane.showMessageDialog(null,"Numbers Only","TextField",1);
                             offset=0;
         }

    When you post code, please use the [co[i]de][co[i]de] tags. There is a code button above the message textfield.

  • Please help getString()

    hi,
    this might sound like a question that shouln't have been asked but
    i'm new to java, studied it for a few months (haven't learnt any kind of programming languages before )and been assigned to do a project, tried my best at it but got stuck on this GetString() method
    what's wrong with this code
    i tried to compile it but came up with errors
    cannot find symbol
    symbol : method getString()
    location: class java.lang.String
    stm.setString(4,strdate.getString());
    cannot find symbol
    symbol : method strtimegetString()
    location: class javaproject
    stm.setString(5, strtimegetString());
    2 errors
    here's the code
    //javaproject.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.sql.*;
    public class javaproject extends JApplet implements ActionListener,Runnable
    JPanel panel; JLabel lname, lcode,lterm,ltime,ldate;
    JTextField tfname , tfcode;
    JButton bttsaved, bttcancel, bttclose;
    JComboBox cbterm;     
    String term[] ={"Semester A","Semester B","Semester C","Semester D"};
    String strdate, strtime ;
    Thread time;
    GregorianCalendar calendar;
    public void init()
         panel = new JPanel();
         lcode = new JLabel ("Code : ");
         lname = new JLabel("Name : ");
         lterm = new JLabel("Term : ");
         ltime = new JLabel();
         ldate = new JLabel();
         tfcode = new JTextField(20);
         tfname = new JTextField(20);
         cbterm = new JComboBox(term);
    bttsaved = new JButton(" Saved ");
    bttcancel = new JButton(" Cancel ");
    bttclose = new JButton(" Close ");
         calendar = new GregorianCalendar();
         time =new Thread(this);
         time.start();
         display();
         panel.add(ldate); panel.add(ltime);
         panel.add(lcode); panel.add(tfcode);
         panel.add(lname); panel.add(tfname);
         panel.add(lterm); panel.add(cbterm);
         panel.add(bttsaved); panel.add(bttcancel); panel.add(bttclose);
         getContentPane().add(panel);
         bttsaved.addActionListener(this);
         bttcancel.addActionListener(this);
         bttclose.addActionListener(this);
    public void run()
         for(;;)
         calendar = new GregorianCalendar();
              strtime = calendar.get(Calendar.HOUR)+":"+calendar.get(Calendar.MINUTE)
              +":"+calendar.get(Calendar.SECOND);
              ltime.setText(strtime);
              try
              time.sleep(1000);
              catch(InterruptedException e)
              showStatus("ThreadInterrupted");          
    public void display()
         strdate = calendar.get(Calendar.DATE) + "/" + (calendar.get(Calendar.MONTH)+1) + "/"+calendar.get(Calendar.YEAR);
         ldate.setText(strdate);
    public void actionPerformed(ActionEvent evt)
         if(evt.getSource() == bttcancel )
         tfcode.setText(" ");
         tfname.setText(" ");
         showStatus(" ..... Please enter new information ..... ");
         if(evt.getSource() == bttclose )
         System.exit(0);          
         if(evt.getSource() ==bttsaved )
         try
              String blankcode = tfcode.getText();
              if(blankcode.length() == 0)
                   showStatus("Student's code cannot be empty");
                   return;          
              String blankname = tfname.getText();
              if(blankname.length() == 0)
                   showStatus("..... Student's name cannot be empty ......");
              return;
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              Connection con;
              con = DriverManager.getConnection("jdbc:odbc:kayteej","sa", null);
              PreparedStatement stm;
              stm = con.prepareStatement("insert into Students values(?,?,?)");
              stm.setString(1,tfcode.getText());     
              stm.setString(2,tfname.getText());
              stm.setString(3,(String)cbterm.getSelectedItem());
              stm.setString(4,strdate.getString());
              stm.setString(5, strtimegetString());
              stm.executeUpdate();     
              showStatus("..... Please enter new information ..... ");
              JOptionPane.showMessageDialog(null, "Data Saved","Congrats!!",1);
         catch(Exception err)
              showStatus("Error occured while interacting with sql");
    //<Applet code="javaproject.class" width=800 height=600></applet>
    should i use the getString method or is it possible to use other type of methods. please help I'm really stuck
    Thank you in advance

    So when you run it, the code throws an exception? Then there's something wrong with your code, or with your setup.
    The exception's stack trace contains useful information which would help you (or us) figure out just what is wrong. Hopefully you have a catch-block that calls the printStackTrace() method of the exception.

  • Problem in socket communication please help me!

    server
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    class SocketServer extends JFrame
              implements ActionListener {
         JLabel text1, text2;
         JButton button1, button2;
         JPanel panel;
         JTextField textField1, textField2;
    ServerSocket server = null;
    Socket socket = null;
    BufferedReader in1 = null;
    PrintWriter out1 = null;
    String line1;
    String line2;
    SocketServer(){ //Begin Constructor
              text1 = new JLabel("Send Information:");
              text2 = new JLabel("Receive Information:");
              textField1 = new JTextField(20);
              textField2 = new JTextField(20);
              button1 = new JButton("Send");
              button2 = new JButton("Receive");
              button1.addActionListener(this);
              button2.addActionListener(this);
              panel = new JPanel();
              panel.setLayout(new GridLayout(2,3));
              panel.setBackground(Color.lightGray);
              getContentPane().add(panel);
              panel.add(text1);
              panel.add(textField1);
              panel.add(button1);
              panel.add(text2);
              panel.add(textField2);
              panel.add(button2);
              setSize(500,100);
    } //End Constructor
         public void actionPerformed(ActionEvent event) {
              Object source = event.getSource();
              if(source == button1){
                   //Send data over socket
                   String text = textField1.getText();
                   out1.println(text);
                   textField1.setText(new String(""));
                   //Receive text from server
                   try{
                        String line1 = in1.readLine();
                        System.out.println("Text received :" + line1);
                   } catch (IOException e){
                        System.out.println("Read failed");
                        System.exit(1);
              if(source == button2){
                   textField2.setText(line2);
         public void listenSocket(){
              try{
                   server = new ServerSocket(4444);
              } catch (IOException e) {
                   System.out.println("Could not listen on port 4444");
                   System.exit(-1);
              try{
                   socket = server.accept();
              } catch (IOException e) {
                   System.out.println("Accept failed: 4444");
                   System.exit(-1);
              try{
                   in1 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                   out1 = new PrintWriter(socket.getOutputStream(), true);
              } catch (IOException e) {
                   System.out.println("Accept failed: 4444");
                   System.exit(-1);
              while(true){
                   try{
                        line2 = in1.readLine();
                        //Send data back to client
                        out1.println(line2);
                   } catch (IOException e) {
                        System.out.println("Read failed");
                        System.exit(-1);
         protected void finalize(){
              //Clean up
              try{
                   in1.close();
                   out1.close();
                   server.close();
              } catch (IOException e) {
                   System.out.println("Could not close.");
                   System.exit(-1);
         public static void main(String[] args){
              SocketServer frame = new SocketServer();
              frame.setTitle("Chat (Server)");
              WindowListener l = new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              frame.addWindowListener(l);
              frame.pack();
              frame.setVisible(true);
              frame.listenSocket();
    client
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    class SocketClient extends JFrame
              implements ActionListener {
    JLabel text1, text2;
    JButton button1, button2;
    JPanel panel;
    JTextField textField1, textField2;
    Socket socket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    String line3;
    String line4;
    SocketClient(){ //Begin Constructor
    text1 = new JLabel("Send Information:");
         text2 = new JLabel("Receive Information:");
    textField1 = new JTextField(20);
         textField2 = new JTextField(20);
    button1 = new JButton("Send");
         button2 = new JButton("Receive");
    button1.addActionListener(this);
         button2.addActionListener(this);
    panel = new JPanel();
    panel.setLayout(new GridLayout(2,3));
    panel.setBackground(Color.lightGray);
    getContentPane().add(panel);
    panel.add(text1);
    panel.add(textField1);
    panel.add(button1);
         panel.add(text2);
         panel.add(textField2);
         panel.add(button2);
         setSize(500,100);
    } //End Constructor
         public void actionPerformed(ActionEvent event){
              Object source = event.getSource();
              if(source == button1){
                   //Send data over socket
                   String text = textField1.getText();
                   out.println(text);
                   textField1.setText(new String(""));
                   //Receive text from server
                   try{
                        String line3 = in.readLine();
                        System.out.println("Text received :" + line3);
                   } catch (IOException e){
                        System.out.println("Read failed");
                        System.exit(1);
              if(source == button2){
                   textField2.setText(line4);
         public void listenSocket(){
              //Create socket connection
              try{
                   socket = new Socket("Localhost", 4444);
                   out = new PrintWriter(socket.getOutputStream(), true);
                   in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              } catch (UnknownHostException e) {
                   System.out.println("Unknown host: Localhost");
                   System.exit(1);
              } catch (IOException e) {
                   System.out.println("No I/O");
                   System.exit(1);
              while(true){
                   try{
                        line4 = in.readLine();
                        //Send data back to client
                        out.println(line4);
                   } catch (IOException e) {
                        System.out.println("Read failed");
                        System.exit(-1);
         public static void main(String[] args){
              SocketClient frame = new SocketClient();
              frame.setTitle("Chat (Client)");
              WindowListener l = new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              frame.addWindowListener(l);
              frame.pack();
              frame.setVisible(true);
              frame.listenSocket();
    There were problems when executing the application
    please help me

    i had no problem running this... make sure you open the server part first and have that sitting and waiting for the client to connect.... then it should work.
    Would you believe that i too am working on the server / socket thing... however my problem is getting the server to read from a database and report back to the client....

  • Scroll bar problems ..Please help!!!!!!

    This is what the program looks like. topPanel has newItemPanel on top of it. when you click continue newItemPanel becomes invisible and newItemDescriptionPanel becomes visible. When you click continue newItemDescriptionPanel becomes invisible and priceEnterPanel becomes visible.
    I want newItemDescriptionPanel and priceEnterPanel to have a scroll bar. but everything I have tried hasn't worked. I am new. You will see the code is ugly and there is an attempt to add a scrollbar.
    Please help
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import java.lang.System;
    public class MainPanel extends      JFrame implements     ActionListener
         private boolean      firstRun = true;
         private final int     ITEM_PLAIN     =     0;     // Item types
         private final int     ITEM_CHECK     =     1;
         private final int     ITEM_RADIO     =     2;
         private     JPanel          topPanel;
         private JPanel          newItemPanel;
         private JRadioButton onlineAuctionRadio;
         private JRadioButton fixedPriceRadio;
         private ButtonGroup bg;
         private JButton     continueButton;
         private JLabel      blankLabel;       //used to give space between things
         private JPanel           newItemDescriptionPanel;
         private JPanel      takeAdditionalSpacePanelCheckBox;
         private JPanel      takeAdditionalSpacePanel;
         private JPanel          takeAdditionalSpacePanelLabel;
         private JPanel          takeAdditionalSpacePanelLabel2;
         private JPanel      takeAdditionalSpacePanel2;
         private JPanel      takeAdditionalSpacePanel3;
         private JPanel           takeAdditionalSpacePanel4;
         private JPanel           takeAdditionalSpacePanel5;
         JScrollPane displayScroller;
         JEditorPane itemDescriptionTextArea;
         GridBagLayout gridbag;
         GridBagConstraints gbc;
         private JCheckBox   secondCategoryCheckBox;
         private JLabel          itemTitleLabel;
         private JLabel          requiredLabel, requiredLabel2;
         private JLabel      requiredStarLabel;
         private JTextField  itemTitleTextField;
         private JLabel           subtitleLabel;
         private JTextField      subtitleTextField;
         private JLabel          itemDescriptionLabel;
         private JButton     itemDescriptionContinueButton;
         private JLabel          percentageLabel;
         //------- price enter page ----------------
         private JLabel          startingPriceLabel;
         private JLabel           dollarSignLabel;
         private JTextField     startingPriceTextField;
         private JPanel          fillUpSpacePanel;
         private JPanel          fillUpSpacePanel1;
         private JPanel          fillUpSpacePanel2;
         private JLabel          buyItNowLabel;
         private JPanel          fillUpSpacePanel3;
         private JLabel          dollarSignLabel2;
         private JTextField     buyItNowTextField;
         private JPanel          fillUpSpacePanel4;
         private JPanel          fillUpSpacePanel5;
         private JPanel          fillUpSpacePanel6;
         private JPanel          fillUpSpacePanel7;
         private JPanel          fillUpSpacePanel8;
         private JPanel          fillUpSpacePanel9;
         private JPanel          fillUpSpacePanel10;
         private JPanel          fillUpSpacePanel11;
         private JPanel          fillUpSpacePanel12;
         private JPanel          fillUpSpacePanel13;
         private JPanel          fillUpSpacePanel14;
         private JPanel          fillUpSpacePanel15;
         private JPanel          fillUpSpacePanel16;
         private JPanel          fillUpSpacePanel17;
         private JPanel          fillUpSpacePanel18;
         private JLabel          donatePercentageLabel;
         private JTextField     donatePercentageTextField;
         private JPanel          fSp; // fill space panel
         private JPanel          fSp1;
         private JPanel          fSp2;
         private JPanel          fSp3;
         private JPanel          fSp4;
         private JPanel          fSp5;
         private JPanel          fSp6;
         private JPanel          fSp7;
         private JPanel          fSp8;
         private JPanel          fSp9;
         private JLabel           numberOfPicturesLabel;
         private JTextField     numberOfPicturesTextField;
         private JCheckBox     superSizePicturesCheckBox;
         private JLabel          superSizePicturesLabel;
         private JRadioButton standardPictureRadioButton;
         private JRadioButton picturePackRadioButton;
         private JCheckBox     listingDesignerCheckBox;
         private ButtonGroup bgPictures;
         private JCheckBox      valuePackCheckBox;
         private JCheckBox     galleryPictureCheckBox;
         private JCheckBox     subtitleCheckBox;
         private JCheckBox     boldCheckBox;
         private JCheckBox     borderCheckBox;
         private JCheckBox     highlightCheckBox;
         private JCheckBox     featuredPlusCheckBox;
         private JCheckBox     galleryFeaturedCheckBox;
         private JLabel          homePageFeaturedLabel;
         private JComboBox     homePageFeaturedComboBox;
         private JCheckBox     giftCheckBox;
         JScrollPane priceEnterPanelScroll;
         private JButton          backToRadioButton;
         private JButton          backToItemDescriptionButton;
         private JPanel           priceEnterPanel;
         private final static String RADIOPANEL = "JPanel with radios";
         private final static String DESCRIPTIONPANEL = "JPanel with description";
         private final static String PRICEENTERPANEL = "JPanel with price entering";
         private JPanel           cards;
         private     JMenuBar     menuBar;
         private     JMenu          menuFile;
         private     JMenu          menuEdit;
         private     JMenu          menuProperty;
         private     JMenuItem     menuPropertySystem;
         private     JMenuItem     menuPropertyEditor;
         private     JMenuItem     menuPropertyDisplay;
         private     JMenu        menuFileNew;
         private JMenuItem   menuFileNewAccount;
         private JMenuItem   menuFileNewItem;
         private     JMenuItem     menuFileOpen;
         private     JMenuItem     menuFileSave;
         private     JMenuItem     menuFileSaveAs;
         private     JMenuItem     menuFileExit;
         private     JMenuItem     menuEditCopy;
         private     JMenuItem     menuEditCut;
         private     JMenuItem     menuEditPaste;
         public MainPanel()
              requiredLabel = new JLabel ("* Required");
              requiredLabel.setForeground (Color.red);
              requiredLabel2 = new JLabel ("* Required");
              requiredLabel2.setForeground (Color.red);
              requiredStarLabel = new JLabel ("*");
              requiredStarLabel.setForeground (Color.green);
              setTitle( "photo galleries" );
              setSize( 310, 130 );
              topPanel = new JPanel();
              topPanel.setLayout( new BorderLayout() );
              topPanel.setBorder (BorderFactory.createTitledBorder ("TopPanel"));
              //topPanel.setPreferredSize(new Dimension (300,300));
              getContentPane().add( topPanel );
              topPanel.setVisible (false);
              //     For New Item Panel
              ButtonListener ears = new ButtonListener();
              blankLabel = new JLabel ("  ");  // used to give space between radio buttons and continue button
              continueButton = new JButton ("Continue >");
              continueButton.addActionListener (ears);
              backToRadioButton = new JButton ("< back");
              backToRadioButton.addActionListener (ears);
              itemDescriptionContinueButton = new JButton ("Continue >");
              itemDescriptionContinueButton.addActionListener (ears);
              backToItemDescriptionButton = new JButton ("< back");
              backToItemDescriptionButton.addActionListener (ears);
              newItemPanel = new JPanel();
              newItemPanel.setLayout (new BoxLayout(newItemPanel, BoxLayout.Y_AXIS));
              //topPanel.add (newItemPanel, BorderLayout.NORTH);
              newItemPanel.setBorder (BorderFactory.createTitledBorder ("NewItemPanel"));
              newItemPanel.setVisible (false);
              onlineAuctionRadio = new JRadioButton ("Sold item at online Auction"     );
              fixedPriceRadio = new JRadioButton ("Sold at a Fixed Price");
              bg = new ButtonGroup();
              bg.add(onlineAuctionRadio);
              bg.add(fixedPriceRadio);
              onlineAuctionRadio.addActionListener (ears);
              fixedPriceRadio.addActionListener (ears);
              newItemPanel.add (onlineAuctionRadio);
              newItemPanel.add (fixedPriceRadio);
              newItemPanel.add (blankLabel);
              newItemPanel.add (continueButton);
              // ------ After continue pressed ---------
              newItemDescriptionPanel = new JPanel();
              newItemDescriptionPanel.setLayout (new BoxLayout(newItemDescriptionPanel, BoxLayout.Y_AXIS));
              newItemPanel.add (newItemDescriptionPanel, BorderLayout.NORTH);
              newItemDescriptionPanel.setBorder (BorderFactory.createTitledBorder ("newItemDescriptionPanel"));
              secondCategoryCheckBox = new JCheckBox ("The item was listed in a second category");
              newItemDescriptionPanel.setVisible (false);
              itemTitleLabel = new JLabel ("Item title");
              itemTitleTextField = new JTextField (30);
              subtitleLabel = new JLabel ("Subtitle ($0.50)");
              subtitleTextField = new JTextField (30);
              itemDescriptionLabel = new JLabel ("Item description");
              itemDescriptionTextArea = new JEditorPane();
              itemDescriptionTextArea.setContentType( "text/html" );
              itemDescriptionTextArea.setEditable( false );
              itemDescriptionTextArea.setPreferredSize(new Dimension (500,250));
              itemDescriptionTextArea.setFont(new Font( "Serif", Font.PLAIN, 12 ));
              itemDescriptionTextArea.setForeground( Color.black );
              gbc = new GridBagConstraints();
              gbc.gridx = 0;
              gbc.gridy = 4;
              displayScroller = new JScrollPane( itemDescriptionTextArea );
              gridbag = new GridBagLayout ();
              gridbag.setConstraints( displayScroller, gbc );
              itemDescriptionTextArea.setEditable( true );
              takeAdditionalSpacePanelCheckBox = new JPanel(new FlowLayout(FlowLayout.LEFT));
              takeAdditionalSpacePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
              takeAdditionalSpacePanelLabel = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
              takeAdditionalSpacePanelLabel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
              takeAdditionalSpacePanel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
              takeAdditionalSpacePanel3 = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
              takeAdditionalSpacePanel4 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              takeAdditionalSpacePanel5 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              //takeAdditionalSpacePanel2.setBorder (BorderFactory.createTitledBorder ("Additonal 2"));
              takeAdditionalSpacePanelCheckBox.add (secondCategoryCheckBox);
              newItemDescriptionPanel.add (takeAdditionalSpacePanelCheckBox);
              //newItemDescriptionPanel.add (blankLabel);
              takeAdditionalSpacePanelLabel.add (itemTitleLabel);
              takeAdditionalSpacePanelLabel.add (requiredLabel);
              newItemDescriptionPanel.add (takeAdditionalSpacePanelLabel);
              //newItemDescriptionPanel.add (itemTitleTextField);
              takeAdditionalSpacePanel.add(itemTitleTextField);//<--add textfield to panel
              newItemDescriptionPanel.add (takeAdditionalSpacePanel);//<--add panel to boxlayout panel
              takeAdditionalSpacePanelLabel2.add (subtitleLabel);
              newItemDescriptionPanel.add (takeAdditionalSpacePanelLabel2);
              takeAdditionalSpacePanel2.add (subtitleTextField);
              newItemDescriptionPanel.add (takeAdditionalSpacePanel2);
              takeAdditionalSpacePanel4.add (itemDescriptionLabel);
              //takeAdditionalSpacePanel4.add (requiredLabel2);
              newItemDescriptionPanel.add (takeAdditionalSpacePanel4);
              takeAdditionalSpacePanel3.add (displayScroller);
              newItemDescriptionPanel.add (takeAdditionalSpacePanel3);
              takeAdditionalSpacePanel5.add (backToRadioButton);
              takeAdditionalSpacePanel5.add (itemDescriptionContinueButton);
              newItemDescriptionPanel.add (takeAdditionalSpacePanel5);
              //newItemDescriptionPanel.setLayout (new BoxLayout(newItemDescriptionPanel, BoxLayout.Y_AXIS));
              //----------- Price Enter Page ----------------
              priceEnterPanel = new JPanel();
              priceEnterPanel.setLayout (new BoxLayout(priceEnterPanel, BoxLayout.Y_AXIS));
              newItemDescriptionPanel.add (priceEnterPanel, BorderLayout.NORTH);
              priceEnterPanel.setBorder (BorderFactory.createTitledBorder ("Price enter Panel"));
              priceEnterPanel.setVisible (false);
              priceEnterPanelScroll = new JScrollPane (priceEnterPanel);
              topPanel.add (priceEnterPanelScroll);
              standardPictureRadioButton = new JRadioButton ("Standard");
              picturePackRadioButton = new JRadioButton ("Picture Pack ($1.00 for up to 6 pictures or $1.50 for 7 to 12 pictures)");
              bgPictures = new ButtonGroup();
              bgPictures.add(standardPictureRadioButton);
              bgPictures.add(picturePackRadioButton);
              standardPictureRadioButton.addActionListener (ears);
              picturePackRadioButton.addActionListener (ears);
              superSizePicturesCheckBox = new JCheckBox ("Supersize Pictures ($0.75)");
              listingDesignerCheckBox = new JCheckBox ("Listing designer $0.10");
              valuePackCheckBox = new JCheckBox ("Get the Essentials for less! Gallery, Subtitle, Listing Designer. $0.65 (save $0.30)");
              superSizePicturesCheckBox.setEnabled (false);
              superSizePicturesCheckBox.addActionListener (ears);
              listingDesignerCheckBox.addActionListener (ears);
              valuePackCheckBox.addActionListener (ears);
              startingPriceLabel = new JLabel ("Starting Price");
              dollarSignLabel = new JLabel ("$");
              startingPriceTextField = new JTextField (10);
              buyItNowLabel = new JLabel ("Buy It Now");
              dollarSignLabel2 = new JLabel ("$");
              buyItNowTextField = new JTextField (10);
              donatePercentageLabel = new JLabel ("Donate percentage of sale");
              donatePercentageTextField = new JTextField (2);
              donatePercentageTextField.setText ("0");
              percentageLabel = new JLabel ("%");
              // Right-justify the text
             donatePercentageTextField.setHorizontalAlignment(JTextField.RIGHT);
              numberOfPicturesLabel = new JLabel ("Number of pictures used");
              numberOfPicturesTextField = new JTextField (1);
              numberOfPicturesTextField.setText ("0");
              galleryPictureCheckBox = new JCheckBox ("Gallery ($0.35) [Requires a picture]");
              subtitleCheckBox = new JCheckBox ("Subtitle ($0.50)");
              boldCheckBox = new JCheckBox ("Bold ($1.00)");
              borderCheckBox = new JCheckBox ("Border ($3.00)");
              highlightCheckBox = new JCheckBox ("Highlight ($5.00)");
              featuredPlusCheckBox = new JCheckBox ("Featured Plus! ($19.95)");
              galleryFeaturedCheckBox = new JCheckBox ("Gallery Featured ($19.95) [Requires a picture]");
              homePageFeaturedLabel = new JLabel ("Home Page Featured ($39.95 for 1 item, $79.95 for 2 or more items)");
              homePageFeaturedComboBox = new JComboBox ();
              homePageFeaturedComboBox.addItem (("None..."));
              homePageFeaturedComboBox.addItem (("1 item"));
              homePageFeaturedComboBox.addItem (("2 or more items"));
              giftCheckBox = new JCheckBox ("Show as a gift ($0.25)");
              fillUpSpacePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel3 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel4 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel5 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel6 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel7 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel8 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel9 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel10 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel11 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel12 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel13 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel14 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel15 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel16 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel17 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel18 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp1     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp2     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp3     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp4     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp5     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp6     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp7     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp8     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp9     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel.add (startingPriceLabel);
              fillUpSpacePanel.add (requiredLabel2);
              priceEnterPanel.add (fillUpSpacePanel);
              fillUpSpacePanel2.add (dollarSignLabel);
              fillUpSpacePanel2.add (startingPriceTextField);
              priceEnterPanel.add (fillUpSpacePanel2);     
         //     fillUpSpacePanel1.add (backToItemDescriptionButton);
         //     priceEnterPanel.add (fillUpSpacePanel1);
              fillUpSpacePanel3.add (buyItNowLabel);
              priceEnterPanel.add (fillUpSpacePanel3);
              fillUpSpacePanel4.add (dollarSignLabel2);
              fillUpSpacePanel4.add (buyItNowTextField);
              priceEnterPanel.add (fillUpSpacePanel4);
              fillUpSpacePanel1.add (donatePercentageLabel);
              priceEnterPanel.add (fillUpSpacePanel1);
              fillUpSpacePanel5.add (donatePercentageTextField);
              fillUpSpacePanel5.add (percentageLabel);
              priceEnterPanel.add (fillUpSpacePanel5);
              fillUpSpacePanel6.add (numberOfPicturesLabel);
              priceEnterPanel.add (fillUpSpacePanel6);
              fillUpSpacePanel7.add (numberOfPicturesTextField);
              priceEnterPanel.add (fillUpSpacePanel7);
              fillUpSpacePanel8.add (standardPictureRadioButton);
              priceEnterPanel.add (fillUpSpacePanel8);
              fillUpSpacePanel10.add (blankLabel);
              fillUpSpacePanel10.add (superSizePicturesCheckBox);
              priceEnterPanel.add (fillUpSpacePanel10);
              fillUpSpacePanel9.add (picturePackRadioButton);
              priceEnterPanel.add (fillUpSpacePanel10);
              fillUpSpacePanel11.add (picturePackRadioButton);
              priceEnterPanel.add (fillUpSpacePanel11);
              fillUpSpacePanel12.add (listingDesignerCheckBox);
              priceEnterPanel.add (fillUpSpacePanel12);
              fillUpSpacePanel13.add (valuePackCheckBox);
              priceEnterPanel.add (fillUpSpacePanel13);
              fSp.add (galleryPictureCheckBox);
              priceEnterPanel.add (fSp);
              fSp1.add (subtitleCheckBox);
              priceEnterPanel.add (fSp1);
              fSp2.add (boldCheckBox);
              priceEnterPanel.add (fSp2);
              fSp3.add (borderCheckBox);
              priceEnterPanel.add (fSp3);
              fSp4.add (highlightCheckBox);
              priceEnterPanel.add (fSp4);
              fSp5.add (featuredPlusCheckBox);
              priceEnterPanel.add (fSp5);
              fSp6.add (galleryFeaturedCheckBox);
              priceEnterPanel.add (fSp6);
              fSp7.add (homePageFeaturedLabel);
              priceEnterPanel.add (fSp7);
              fSp8.add (homePageFeaturedComboBox);
              priceEnterPanel.add (fSp8);
              fSp9.add (giftCheckBox);
              priceEnterPanel.add (fSp9);
              newItemDescriptionPanel.add (priceEnterPanelScroll);
              //Create the panel that contains the "cards".
              cards = new JPanel(new CardLayout());
              cards.add(newItemPanel, RADIOPANEL);
              cards.add(newItemDescriptionPanel, DESCRIPTIONPANEL);
              cards.add(priceEnterPanel, PRICEENTERPANEL);
              topPanel.add(cards, BorderLayout.NORTH);
              // Create the menu bar
              menuBar = new JMenuBar();
              // Set this instance as the application's menu bar
              setJMenuBar( menuBar );
              // Build the property sub-menu
              menuProperty = new JMenu( "Properties" );
              menuProperty.setMnemonic( 'P' );
              // Create property items
              menuPropertySystem = CreateMenuItem( menuProperty, ITEM_PLAIN,
                                            "System...", null, 'S', null );
              menuPropertyEditor = CreateMenuItem( menuProperty, ITEM_PLAIN,
                                            "Editor...", null, 'E', null );
              menuPropertyDisplay = CreateMenuItem( menuProperty, ITEM_PLAIN,
                                            "Display...", null, 'D', null );
              //Build the File-New sub-menu
              menuFileNew = new JMenu ("New");
              menuFileNew.setMnemonic ('N');
              //Create File-New items
              menuFileNewItem = CreateMenuItem( menuFileNew, ITEM_PLAIN,
                                            "Item", null, 'A', null );
              menuFileNewAccount = CreateMenuItem( menuFileNew, ITEM_PLAIN,
                                            "Account", null, 'A', null );
              // Create the file menu
              menuFile = new JMenu( "File" );
              menuFile.setMnemonic( 'F' );
              menuBar.add( menuFile );
              //Add the File-New menu
              menuFile.add( menuFileNew );
              // Create the file menu
              // Build a file menu items
              menuFileOpen = CreateMenuItem( menuFile, ITEM_PLAIN, "Open...",
                                            new ImageIcon( "open.gif" ), 'O',
                                            "Open a new file" );
              menuFileSave = CreateMenuItem( menuFile, ITEM_PLAIN, "Save",
                                            new ImageIcon( "save.gif" ), 'S',
                                            " Save this file" );
              menuFileSaveAs = CreateMenuItem( menuFile, ITEM_PLAIN,
                                            "Save As...", null, 'A',
                                            "Save this data to a new file" );
              // Add the property menu     
              menuFile.addSeparator();
              menuFile.add( menuProperty );
              menuFile.addSeparator();
              menuFileExit = CreateMenuItem( menuFile, ITEM_PLAIN,
                                            "Exit", null, 'X',
                                            "Exit the program" );
              //menuFileExit.addActionListener(this);
              // Create the file menu
              menuEdit = new JMenu( "Edit" );
              menuEdit.setMnemonic( 'E' );
              menuBar.add( menuEdit );
              // Create edit menu options
              menuEditCut = CreateMenuItem( menuEdit, ITEM_PLAIN,
                                            "Cut", null, 'T',
                                            "Cut data to the clipboard" );
              menuEditCopy = CreateMenuItem( menuEdit, ITEM_PLAIN,
                                            "Copy", null, 'C',
                                            "Copy data to the clipboard" );
              menuEditPaste = CreateMenuItem( menuEdit, ITEM_PLAIN,
                                            "Paste", null, 'P',
                                            "Paste data from the clipboard" );
         public JMenuItem CreateMenuItem( JMenu menu, int iType, String sText,
                                            ImageIcon image, int acceleratorKey,
                                            String sToolTip )
              // Create the item
              JMenuItem menuItem;
              switch( iType )
                   case ITEM_RADIO:
                        menuItem = new JRadioButtonMenuItem();
                        break;
                   case ITEM_CHECK:
                        menuItem = new JCheckBoxMenuItem();
                        break;
                   default:
                        menuItem = new JMenuItem();
                        break;
              // Add the item test
              menuItem.setText( sText );
              // Add the optional icon
              if( image != null )
                   menuItem.setIcon( image );
              // Add the accelerator key
              if( acceleratorKey > 0 )
                   menuItem.setMnemonic( acceleratorKey );
              // Add the optional tool tip text
              if( sToolTip != null )
                   menuItem.setToolTipText( sToolTip );
              // Add an action handler to this menu item
              menuItem.addActionListener( this );
              menu.add( menuItem );
              return menuItem;
         public void actionPerformed( ActionEvent event )
              CardLayout cl = (CardLayout)(cards.getLayout());
              if (event.getSource() == menuFileExit)
                   System.exit(0);
              if (event.getSource() == menuFileNewAccount)
                   System.out.println ("hlkadflkajfalkdjfalksfj");
              if (event.getSource() == menuFileNewItem){
                   if (firstRun){
                        newItemPanel.setVisible (true);
                        topPanel.setVisible (true);
                   cl.show(cards,RADIOPANEL);
                   firstRun = false;
              //System.out.println( event );
         private class ButtonListener implements ActionListener
              public void actionPerformed(ActionEvent event)
                   CardLayout cl = (CardLayout)(cards.getLayout());
             //     cl.show(cards, (String)evt.getItem());
                   if (event.getSource() == continueButton){
                        if (!(onlineAuctionRadio.isSelected()) && !(fixedPriceRadio.isSelected()))
                             JOptionPane.showMessageDialog(null, "You must select at least one.", "Error", JOptionPane.ERROR_MESSAGE);
                        else{
                             if (onlineAuctionRadio.isSelected()){
                                  cl.show (cards, DESCRIPTIONPANEL);
                                  //newItemPanel.setVisible (false);
                                  //newItemDescriptionPanel.setVisible (true);
                   if (event.getSource() == itemDescriptionContinueButton){
                       if (itemTitleTextField.getText().trim().equalsIgnoreCase(""))
                            JOptionPane.showMessageDialog(null, "You must enter a title.", "Error", JOptionPane.ERROR_MESSAGE);
                        else
                             cl.show (cards, PRICEENTERPANEL);
                   if (event.getSource() == backToRadioButton){
                        cl.show (cards, RADIOPANEL);
                   if (event.getSource() == backToItemDescriptionButton){
                        cl.show(cards, DESCRIPTIONPANEL);
                   if (standardPictureRadioButton.isSelected()){
                        superSizePicturesCheckBox.setEnabled (true);
                   if (picturePackRadioButton.isSelected()){
                        superSizePicturesCheckBox.setEnabled (false);
              } //end of action performed
    }

    Mostly I see there is about 100 times as much code as I care to look at.
    So you don't know how to get a panel in a scroll pane, and then get that scroll pane into your GUI? Then try doing that by itself, not encumbered with 10000 lines of irrelevant code. Once you have it working, plug it into the big lump of code. Or if you can't get it working, ask about the small problem here.

  • Please Help - Need Help with Buttons for GUI for assignment. URGENT!!

    Can someone please help me with the buttons on this program? I cannot figure out how to get them to work.
    Thanks!!!
    import java.awt.*;
    import java.awt.event.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.JButton;
    public class InventoryTAH implements ActionListener
        Maker[] proMaker;
        JTextField[] fields;
        NumberFormat nf;
        public void actionPerformed(ActionEvent e)
            int index = ((JComboBox)e.getSource()).getSelectedIndex();
            populateFields(index);
        public static void main(String[] args)
            try
                UIManager.setLookAndFeel(
                        "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            catch (Exception e)
                System.err.println(e.getClass().getName() + ": " + e.getMessage());
            InventoryTAH test = new InventoryTAH();
            test.initMakers();
            test.showGUI();
            test.populateFields(0);
        private void initMakers() {
            proMaker = new Maker[10];
            proMaker[0] = new Maker( 1, "Pens",1.59,100,"Bic");
            proMaker[1] = new Maker( 2, "Pencils", .65, 100,"Mead");
            proMaker[2] = new Maker( 3, "Markers", 1.29, 100,"Sharpie");
            proMaker[3] = new Maker( 4, "Paperclips", 1.19, 100,"Staples");
            proMaker[4] = new Maker( 5, "Glue", .85, 100,"Elmer's");
            proMaker[5] = new Maker( 6, "Tape", .50, 100,"3m");
            proMaker[6] = new Maker( 7, "Paper", 1.85, 100,"Mead");
            proMaker[7] = new Maker( 8, "Stapler", 2.21, 100,"Swingline");
            proMaker[8] = new Maker( 9, "Folders", .50, 100,"Mead");
            proMaker[9] = new Maker( 10, "Rulers", .27, 100,"Stanley");      
          int maxNum = 10;
          int currentNum = 0;
          int currentInv = 0;
             Action firstAction = new AbstractAction("First")
              public void actionPerformed(ActionEvent evt)
                   currentInv = 0;
                   int populateFields;
          JButton firstButton = new JButton(firstAction);
          Action previousAction = new AbstractAction("Previous")
              public void actionPerformed(ActionEvent evt)
                   currentInv--;
                   if (currentInv < 0)
                        currentInv = maxNum - 1;
                   int populateFields;
          JButton previousButton = new JButton(previousAction);
          Action nextAction  = new AbstractAction("Next")
              public void actionPerformed(ActionEvent evt)
                   currentInv++;
                   if (currentInv >= currentNum)
                        currentInv = 0;
                  int populateFields;
          JButton nextButton = new JButton(nextAction);
          Action lastAction = new AbstractAction("Last")
              public void actionPerformed(ActionEvent evt)
                   currentInv = currentNum - 1;
                   int populateFields;
          JButton lastButton = new JButton(lastAction);
              JPanel buttonPanel = new JPanel( );
        private void showGUI() {
            JLabel l;
            JButton button1;
                JButton button2;
            fields = new JTextField[8];
            JFrame f = new JFrame("Inventory");
            Container cp = f.getContentPane();
            cp.setLayout(new GridBagLayout());
            cp.setBackground(UIManager.getColor(Color.BLACK));
            GridBagConstraints c = new GridBagConstraints();
            c.gridx = 0;
            c.gridy = GridBagConstraints.RELATIVE;
            c.gridwidth = 1;
            c.gridheight = 1;
            c.insets = new Insets(2, 2, 2, 2);
            c.anchor = GridBagConstraints.EAST;
            cp.add(l = new JLabel("Item Number:", SwingConstants.CENTER), c);
            l.setDisplayedMnemonic('a');
            cp.add(l = new JLabel("Item Name:", SwingConstants.CENTER), c);
            l.setDisplayedMnemonic('b');
            cp.add(l = new JLabel("Number of Units in Stock:", SwingConstants.CENTER), c);
            l.setDisplayedMnemonic('c');
            cp.add(l = new JLabel("Price per Unit: $", SwingConstants.CENTER), c);
            l.setDisplayedMnemonic('d');
            cp.add(l = new JLabel("Total cost of Item: $", SwingConstants.CENTER), c);
            l.setDisplayedMnemonic('e');
            cp.add(l = new JLabel("Total Value of Merchandise in Inventory: $", SwingConstants.CENTER), c);
            l.setDisplayedMnemonic('f');
            cp.add(l = new JLabel("Manufacturer:", SwingConstants.CENTER), c);
            l.setDisplayedMnemonic('g');
            cp.add(l = new JLabel("Restocking Fee: $", SwingConstants.CENTER), c);
            l.setDisplayedMnemonic('h');
                c.gridx = 1;
            c.gridy = 0;
            c.weightx = 1.0;
            c.fill = GridBagConstraints.HORIZONTAL;
            c.anchor = GridBagConstraints.CENTER;
            cp.add(fields[0] = new JTextField(), c);
            fields[0].setFocusAccelerator('a');
            c.gridx = 1;
            c.gridy = GridBagConstraints.RELATIVE;
            cp.add(fields[1] = new JTextField(), c);
            fields[1].setFocusAccelerator('b');
            cp.add(fields[2] = new JTextField(), c);
            fields[2].setFocusAccelerator('c');
            cp.add(fields[3] = new JTextField(), c);
            fields[3].setFocusAccelerator('d');
            cp.add(fields[4] = new JTextField(), c);
            fields[4].setFocusAccelerator('e');
            cp.add(fields[5] = new JTextField(), c);
            fields[5].setFocusAccelerator('f');
            cp.add(fields[6] = new JTextField(), c);
            fields[6].setFocusAccelerator('g');
            cp.add(fields[7] = new JTextField(), c);
            fields[7].setFocusAccelerator('h');
            c.weightx = 0.0;
            c.fill = GridBagConstraints.NONE;
              cp.add(firstButton);
              cp.add(previousButton);
              cp.add(nextButton);
              cp.add(lastButton);
                          JComboBox combo = new JComboBox();
            for(int j = 0; j < proMaker.length; j++)
                combo.addItem(proMaker[j].getName());
            combo.addActionListener(this);
                cp.add(combo);
                cp.add(button1 = new JButton("   "), c);
            f.pack();
            f.addWindowListener(new WindowAdapter()
                public void windowClosing(WindowEvent evt)
                    System.exit(0);
            f.setVisible(true);
      private void populateFields(int index) {
            Maker maker = proMaker[index];
            fields[0].setText(Long.toString(maker.getNumberCode()));
            fields[1].setText(maker.getName());
            fields[2].setText(Long.toString(maker.getUnits()));
            fields[3].setText(Double.toString(maker.getPrice()));
            fields[4].setText(Double.toString(maker.getSum()));
            fields[5].setText(Double.toString(maker.totalAllInventory(proMaker)));
            fields[6].setText(maker.getManufact());
            fields[7].setText(Double.toString(maker.getSum()*.05));       
    class Maker {
        int itemNumber;
        String name;
        int units;
        double price;
        String manufacturer;
        public Maker(int n, String name, double price, int units, String manufac) {
            itemNumber = n;
            this.name = name;
            this.price = price;
            this.units = units;
            manufacturer = manufac;
        public int getNumberCode() { return itemNumber; }
        public String getName() { return name; }
        public int getUnits() { return units; }
        public double getPrice() { return price; }
        public double getSum() { return units*price; }
        public String getManufact() { return manufacturer; }
        public double totalAllInventory(Maker[] makers) {
            double total = 0;
            for(int j = 0; j < makers.length; j++)
                total += makers[j].getSum();
            return total;
    }}

    // I have made some modifications. Please try this.
    import java.awt.*;
    import java.awt.event.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.JButton;
    public class InventoryTAH implements ActionListener
    Maker[] proMaker;
    JTextField[] fields;
    NumberFormat nf;
    int currentInv = 0;
    public void actionPerformed(ActionEvent e)
    currentInv= ((JComboBox)e.getSource()).getSelectedIndex();
    populateFields(currentInv);
    public static void main(String[] args)
    try
    UIManager.setLookAndFeel(
    "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    catch (Exception e)
    System.err.println(e.getClass().getName() + ": " + e.getMessage());
    InventoryTAH test = new InventoryTAH();
    test.initMakers();
    test.showGUI();
    test.populateFields(0);
    private void initMakers() {
    proMaker = new Maker[10];
    proMaker[0] = new Maker( 1, "Pens",1.59,100,"Bic");
    proMaker[1] = new Maker( 2, "Pencils", .65, 100,"Mead");
    proMaker[2] = new Maker( 3, "Markers", 1.29, 100,"Sharpie");
    proMaker[3] = new Maker( 4, "Paperclips", 1.19, 100,"Staples");
    proMaker[4] = new Maker( 5, "Glue", .85, 100,"Elmer's");
    proMaker[5] = new Maker( 6, "Tape", .50, 100,"3m");
    proMaker[6] = new Maker( 7, "Paper", 1.85, 100,"Mead");
    proMaker[7] = new Maker( 8, "Stapler", 2.21, 100,"Swingline");
    proMaker[8] = new Maker( 9, "Folders", .50, 100,"Mead");
    proMaker[9] = new Maker( 10, "Rulers", .27, 100,"Stanley");
         int maxNum = 10;
         int currentNum = 0;
    Action firstAction = new AbstractAction("First")
              public void actionPerformed(ActionEvent evt)
                   currentInv = 0;
                   populateFields(currentInv);
         JButton firstButton = new JButton(firstAction);
         Action previousAction = new AbstractAction("Previous")
              public void actionPerformed(ActionEvent evt)
                   currentInv--;
                   if (currentInv < 0)
                        currentInv = maxNum - 1;
                   populateFields(currentInv);
         JButton previousButton = new JButton(previousAction);
         Action nextAction = new AbstractAction("Next")
              public void actionPerformed(ActionEvent evt)
                   currentInv++;
                   if (currentInv >= maxNum)
                        currentInv = 0;
              populateFields(currentInv);
         JButton nextButton = new JButton(nextAction);
         Action lastAction = new AbstractAction("Last")
              public void actionPerformed(ActionEvent evt)
                   currentInv = maxNum-1;
                   populateFields(currentInv);
         JButton lastButton = new JButton(lastAction);
              JPanel buttonPanel = new JPanel( );
    private void showGUI() {
    JLabel l;
    JButton button1;
              JButton button2;
    fields = new JTextField[8];
    JFrame f = new JFrame("Inventory");
    Container cp = f.getContentPane();
    cp.setLayout(new GridBagLayout());
    cp.setBackground(UIManager.getColor(Color.BLACK));
    GridBagConstraints c = new GridBagConstraints();
    c.gridx = 0;
    c.gridy = GridBagConstraints.RELATIVE;
    c.gridwidth = 1;
    c.gridheight = 1;
    c.insets = new Insets(2, 2, 2, 2);
    c.anchor = GridBagConstraints.EAST;
    cp.add(l = new JLabel("Item Number:", SwingConstants.CENTER), c);
    l.setDisplayedMnemonic('a');
    cp.add(l = new JLabel("Item Name:", SwingConstants.CENTER), c);
    l.setDisplayedMnemonic('b');
    cp.add(l = new JLabel("Number of Units in Stock:", SwingConstants.CENTER), c);
    l.setDisplayedMnemonic('c');
    cp.add(l = new JLabel("Price per Unit: $", SwingConstants.CENTER), c);
    l.setDisplayedMnemonic('d');
    cp.add(l = new JLabel("Total cost of Item: $", SwingConstants.CENTER), c);
    l.setDisplayedMnemonic('e');
    cp.add(l = new JLabel("Total Value of Merchandise in Inventory: $", SwingConstants.CENTER), c);
    l.setDisplayedMnemonic('f');
    cp.add(l = new JLabel("Manufacturer:", SwingConstants.CENTER), c);
    l.setDisplayedMnemonic('g');
    cp.add(l = new JLabel("Restocking Fee: $", SwingConstants.CENTER), c);
    l.setDisplayedMnemonic('h');
              c.gridx = 1;
    c.gridy = 0;
    c.weightx = 1.0;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.anchor = GridBagConstraints.CENTER;
    cp.add(fields[0] = new JTextField(), c);
    fields[0].setFocusAccelerator('a');
    c.gridx = 1;
    c.gridy = GridBagConstraints.RELATIVE;
    cp.add(fields[1] = new JTextField(), c);
    fields[1].setFocusAccelerator('b');
    cp.add(fields[2] = new JTextField(), c);
    fields[2].setFocusAccelerator('c');
    cp.add(fields[3] = new JTextField(), c);
    fields[3].setFocusAccelerator('d');
    cp.add(fields[4] = new JTextField(), c);
    fields[4].setFocusAccelerator('e');
    cp.add(fields[5] = new JTextField(), c);
    fields[5].setFocusAccelerator('f');
    cp.add(fields[6] = new JTextField(), c);
    fields[6].setFocusAccelerator('g');
    cp.add(fields[7] = new JTextField(), c);
    fields[7].setFocusAccelerator('h');
    c.weightx = 0.0;
    c.fill = GridBagConstraints.NONE;
              cp.add(firstButton);
              cp.add(previousButton);
              cp.add(nextButton);
              cp.add(lastButton);
                        JComboBox combo = new JComboBox();
    for(int j = 0; j < proMaker.length; j++)
    combo.addItem(proMaker[j].getName());
    combo.addActionListener(this);
              cp.add(combo);
              cp.add(button1 = new JButton(" "), c);
    f.pack();
    f.addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent evt)
    System.exit(0);
    f.setVisible(true);
    private void populateFields(int index) {
    Maker maker = proMaker[index];
    fields[0].setText(Long.toString(maker.getNumberCode()));
    fields[1].setText(maker.getName());
    fields[2].setText(Long.toString(maker.getUnits()));
    fields[3].setText(Double.toString(maker.getPrice()));
    fields[4].setText(Double.toString(maker.getSum()));
    fields[5].setText(Double.toString(maker.totalAllInventory(proMaker)));
    fields[6].setText(maker.getManufact());
    fields[7].setText(Double.toString(maker.getSum()*.05));
    class Maker {
    int itemNumber;
    String name;
    int units;
    double price;
    String manufacturer;
    public Maker(int n, String name, double price, int units, String manufac) {
    itemNumber = n;
    this.name = name;
    this.price = price;
    this.units = units;
    manufacturer = manufac;
    public int getNumberCode() { return itemNumber; }
    public String getName() { return name; }
    public int getUnits() { return units; }
    public double getPrice() { return price; }
    public double getSum() { return units*price; }
    public String getManufact() { return manufacturer; }
    public double totalAllInventory(Maker[] makers) {
    double total = 0;
    for(int j = 0; j < makers.length; j++)
    total += makers[j].getSum();
    return total;
    }}

  • Please help...my browser can't display applets

    I know it might sound inept to be asking something about my mozilla browser in this forum but right now I am studying Java and using my browser to view the applet exercises I make. I am particularly in the methods section where you have to make recursions (I am using JAVA 2 how to program Third Edition by Deitel). I made my own version of the fibonacci program in the book . It has a GUI, action listener and the method where all the calculations take place. Unfortunately, when I test it on my brower, Mozilla Fireforx, it just displays the GUI and whole program does not work. The compiler, in this case javac, cannot sense anything wrong and I take it that my code is correct. However nothing still happens when I test it on my browser. As previously mentioned, it just displays the GUI and that's all. I really do not know what is wrong. Is it with my code or with the browser? Or is with the fact that I am using an outdated version of JAVA 2 how to program with a new version of J2SDK that makes my code incompatible with the new technology? please help. TY
    Here's my code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class AppletCode extends JApplet implements ActionListener {
         JLabel inputLabel, outputLabel;
         JTextField input, output;
         public void init(){
              Container c = getContentPane();
              c.setLayout(new FlowLayout());
              JLabel inputLabel = new JLabel();
              inputLabel.setText("Enter an Integer and press Enter");
              c.add(inputLabel);
              JTextField input = new JTextField(10);
              input.addActionListener(this);
              c.add(input);
              JLabel outputLabel = new JLabel();
              outputLabel.setText("Fibonacci Value is");
              c.add(outputLabel);
              JTextField output = new JTextField(20);
              output.setEditable(false);
              c.add(output);
         } // GUI
         public void actionPerformed(ActionEvent e) {
              long number, fibonacciValue;
              number = Long.parseLong(input.getText());
              fibonacciValue = fibonacci(number);
              output.setText(Long.toString(fibonacciValue));
         } // Action Listener
         public long fibonacci(long x) {
              if (x==0 || x==1)
                   return x;
              else
                   return fibonacci(x-1) + fibonacci(x-2);
         } // Fibonacci Module
    }

    I don't see anything obviously wrong with your code, but it's been a while since i coded applets, so there might still be something wrong. What exactly does not work? You see the 2 labels and the text fields? Can you enter any text into the text field? Have you looked into the Java Console wether it prints any exceptions? (and please use the [ code][ /code] tags to mark your code (without the spaces obviously))

  • Button to frame | button going back to the main frame (please help)

    these are the codes, by clicking the "FCFS" button it will generate another frame and from that frame another button will be pressed "accept" and it will go to another frame....
    my problem is that i nid to put codes on the "back" button to go back to the main frame were it started... please help me... thnks
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Oscon extends JFrame
         private JButton fcfsB, priorityB, sjfB, rrB, exitB, creditsB;
         private fcfsButtonHandler fbHandler;
         private priorityButtonHandler pbHandler;
         private sjfButtonHandler sbHandler;
         private rrButtonHandler rbHandler;
         private exitButtonHandler ebHandler;
         private creditsButtonHandler cbHandler;     
         public Oscon()// main frame
              fcfsB = new JButton ("FCFS");
              fbHandler = new fcfsButtonHandler();
              fcfsB.addActionListener(fbHandler);
              priorityB = new JButton ("PRIORITY");
              pbHandler = new priorityButtonHandler();
              priorityB.addActionListener(pbHandler);
              sjfB = new JButton ("SJF");
              sbHandler = new sjfButtonHandler();
              sjfB.addActionListener(sbHandler);
              rrB = new JButton ("RR");
              rbHandler = new rrButtonHandler();
              rrB.addActionListener(rbHandler);
              exitB = new JButton ("EXIT");
              ebHandler = new exitButtonHandler();
              exitB.addActionListener(ebHandler);
              creditsB = new JButton ("CREDITS");
              cbHandler = new creditsButtonHandler();
              creditsB.addActionListener(cbHandler);
              setTitle("CPU SCHEDULING");
              Container pane =getContentPane ();     
              pane.setLayout(new GridLayout(2,3));
              pane.add(fcfsB);
              pane.add(priorityB);
              pane.add(sjfB);
              pane.add(rrB);
              pane.add(exitB);
              pane.add(creditsB);
              setSize(500,100);
              setVisible(true);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
         public class fcfsButtonHandler implements ActionListener
              public void actionPerformed(ActionEvent e)
                   JFrame frame = new JFrame("FCFCS setting");
         final JLabel FCFSProcessL, FCFSp1L,FCFSp2L,FCFSp3L,FCFSp4L, FCFSbt;
              final JTextField FCFSp1TF,FCFSp2TF,FCFSp3TF,FCFSp4TF;
                        FCFSProcessL = new JLabel("PROCESS", SwingConstants.CENTER);
                        FCFSp1L     = new JLabel("P1:", SwingConstants.CENTER);
                        FCFSp2L     = new JLabel("P2:", SwingConstants.CENTER);
                        FCFSp3L     = new JLabel("P3:", SwingConstants.CENTER);
                        FCFSp4L     = new JLabel("P4:", SwingConstants.CENTER);
                        FCFSbt      = new JLabel("BT:", SwingConstants.CENTER);
                        FCFSp1TF= new JTextField (10);
                        FCFSp2TF= new JTextField (10);
                        FCFSp3TF= new JTextField (10);
                        FCFSp4TF= new JTextField (10);
                        JButton     FCFSokB = new JButton ("Accept");
                        FCFSokB.addActionListener(new ActionListener() {   
                        public void actionPerformed(ActionEvent e)
                                  JFrame frame2 = new JFrame("FCFCS");
                                  frame2.setSize(500,500);
                                  frame2.setVisible(true);
                                  frame2.setDefaultCloseOperation(EXIT_ON_CLOSE);
                                  JButton     FCFSclearB = new JButton ("clear");
                                  FCFSclearB.addActionListener(new ActionListener() {   
                                  public void actionPerformed(ActionEvent e)
                                  FCFSp1TF.setText("");
                                  FCFSp2TF.setText("");
                                  FCFSp3TF.setText("");
                                  FCFSp4TF.setText("");
                        JButton     FCFSBackB = new JButton ("Back");
                        FCFSBackB.addActionListener(new ActionListener() {   
                        public void actionPerformed(ActionEvent e)
                                  setTitle("CPU SCHEDULING");
                                  frame.setLayout(new GridLayout(7,2));
                                  frame.add(FCFSProcessL);
                                  frame.add(FCFSbt);
                                  frame.add(FCFSp1L);
                                  frame.add(FCFSp1TF);
                                  frame.add(FCFSp2L);
                                  frame.add(FCFSp2TF);
                                  frame.add(FCFSp3L);
                                  frame.add(FCFSp3TF);
                                  frame.add(FCFSp4L);
                                  frame.add(FCFSp4TF);
                                  frame.add(FCFSokB);
                                  frame.add(FCFSclearB);
                                  frame.add(FCFSBackB);
                                  frame.setSize(200,250);
                                  frame.setVisible(true);
                                  frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
         public class priorityButtonHandler implements ActionListener
              public void actionPerformed(ActionEvent e)
         public class sjfButtonHandler implements ActionListener
              public void actionPerformed(ActionEvent e)
                   System.exit (0);          
         public class rrButtonHandler implements ActionListener
              public void actionPerformed(ActionEvent e)
                   System.exit (0);          
         public class exitButtonHandler implements ActionListener
              public void actionPerformed(ActionEvent e)
                   System.exit (0);          
         public class creditsButtonHandler implements ActionListener
              public void actionPerformed(ActionEvent e)
                   System.exit (0);          
              public static void main (String [] args)
              Oscon O = new Oscon();
    }

    please help me revise my program, im almost done, i just nid to set the progress bar that it will run according to the waiting time, or set the progress bar to run in order.. these are the variable names of the progress bar(current1, then current2, then current3 then current4).
    i looked it up on the site and i cant really understand it... i just did the part where i included the progress bar to the interface. ijust want the 4 progress bars to run after clicking the accept button.... Please help me!!! its for my project and i didnt slept last night just working on this... i just nid help sir... thnks...
    these are the codes i made:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JProgressBar;
    public class CPUSched
              public CPUSched()
              JFrame frame = new JFrame();
                   JProgressBar current1, current2, current3, current4;
                   Thread runner;
                   int num = 0;
              final JLabel ProcessL, p1L,p2L,p3L,p4L, bt, prioL, tqL, wtL, awtL, awtLA;
                   final JTextField p1TF,p2TF,p3TF,p4TF, prio1TF, prio2TF,prio3TF,prio4TF, tqTF ;
                   final JLabel      blank1, blank2, blank3, blank4, blank5, blank6, blank7, blank8, blank9, blank10, blank11,
                                       blank12, blank13, blank14, blank15;
                   final JLabel     blank16, blank17, blank18, blank19, blank20, blank21, blank22, blank23, blank24, blank25,
                                       blank26, blank27, blank28, blank29, blank30;
                   current1 = new JProgressBar(0, 2000);
                   current1.setValue(0);
         current1.setStringPainted(true);
                   current2 = new JProgressBar(0, 2000);
                   current2.setValue(0);
         current2.setStringPainted(true);
                   current3= new JProgressBar(0, 2000);
                   current3.setValue(0);
         current3.setStringPainted(true);
                   current4 = new JProgressBar(0, 2000);
                   current4.setValue(0);
         current4.setStringPainted(true);
                        ProcessL = new JLabel("PROCESS", SwingConstants.CENTER);
                        p1L     = new JLabel("P1:", SwingConstants.CENTER);
                        p2L     = new JLabel("P2:", SwingConstants.CENTER);
                        p3L     = new JLabel("P3:", SwingConstants.CENTER);
                        p4L     = new JLabel("P4:", SwingConstants.CENTER);
                        bt      = new JLabel("Burst Time:", SwingConstants.CENTER);
                        prioL= new JLabel("Priority (1-4):", SwingConstants.CENTER);
                        tqL= new JLabel("Time Quantum:", SwingConstants.CENTER);
                        wtL= new JLabel("Waiting time:", SwingConstants.CENTER);
                        awtL= new JLabel("Average Waiting time:");
                        awtLA= new JLabel("");
                        blank1= new JLabel("");
                        blank2= new JLabel("");
                        blank3= new JLabel("" ,SwingConstants.CENTER);
                        blank4= new JLabel("");
                        blank5= new JLabel("", SwingConstants.CENTER);
                        blank6= new JLabel("");
                        blank7= new JLabel("");
                        blank8= new JLabel("" ,SwingConstants.CENTER);
                        blank9= new JLabel("");
                        blank10= new JLabel("");
                        blank11= new JLabel("", SwingConstants.CENTER);
                        blank12= new JLabel("");
                        blank13= new JLabel("");
                        blank14= new JLabel("");
                        blank15= new JLabel("");
                        blank16= new JLabel("");
                        blank17= new JLabel("");
                        blank18= new JLabel("");
                        blank19= new JLabel("");
                        blank20= new JLabel("");
                        blank21= new JLabel("");
                        blank22= new JLabel("");
                        blank23= new JLabel("");
                        blank24= new JLabel("");
                        blank25= new JLabel("");
                        blank26= new JLabel("");
                        blank27= new JLabel("");
                        blank28= new JLabel("");
                        blank29= new JLabel("");
                        blank30= new JLabel("");
                        p1TF= new JTextField (2);
                        p2TF= new JTextField (2);
                        p3TF= new JTextField (2);
                        p4TF= new JTextField (2);
                        prio1TF= new JTextField (2);
                        prio2TF= new JTextField (2);
                        prio3TF= new JTextField (2);
                        prio4TF= new JTextField (2);
                        tqTF= new JTextField (2);
                             prio1TF.setEditable(false);
                             prio2TF.setEditable(false);
                             prio3TF.setEditable(false);
                             prio4TF.setEditable(false);
                             tqTF.setEditable(false);
                        JButton     okB = new JButton ("Accept");
                        okB.addActionListener(new ActionListener() {   
                        public void actionPerformed(ActionEvent e)
                             double iw=0, wtp1, wtp2, wtp3, wtp4;
                             double bt1, bt2, bt3, bt4;
                             double averageWT, sumWT;
                             bt1=Double.parseDouble(p1TF.getText());
                             bt2=Double.parseDouble(p2TF.getText());
                             bt3=Double.parseDouble(p3TF.getText());
                             bt4=Double.parseDouble(p4TF.getText());
                             wtp1 = iw;
                             wtp2 = wtp1+bt1;
                             wtp3 = wtp2+bt2;
                             wtp4 = wtp3+bt3;
                             sumWT = wtp1+wtp2+wtp3+wtp4;
                             averageWT = sumWT/4;
                             awtLA.setText(""+averageWT);
                             blank3.setText(""+wtp1);
                             blank5.setText(""+wtp2);
                             blank8.setText(""+wtp3);
                             blank11.setText(""+wtp4);
                        JButton     clearB = new JButton ("Clear");
                        clearB.addActionListener(new ActionListener() {   
                        public void actionPerformed(ActionEvent e)
                                  p1TF.setText("");
                                  p2TF.setText("");
                                  p3TF.setText("");
                                  p4TF.setText("");
                             awtLA.setText("");
                             blank3.setText("");
                             blank5.setText("");
                             blank8.setText("");
                             blank11.setText("");
                             frame.setTitle("First Come First Serve");
                                  frame.setLayout(new GridLayout(6,6));
                                  frame.add(ProcessL);
                                  frame.add(blank1);
                                  frame.add(wtL);
                                  frame.add(bt);
                                  frame.add(prioL);
                                  frame.add(tqL);
                                  frame.add(p1L);
                                  frame.add(current1);
                                  frame.add(blank3);                              
                                  frame.add(p1TF);
                                  frame.add(prio1TF);
                                  frame.add(tqTF);
                                  frame.add(p2L);
                                  frame.add(current2);
                                  frame.add(blank5);
                                  frame.add(p2TF);
                                  frame.add(prio2TF);
                                  frame.add(blank6);
                                  frame.add(p3L);
                                  frame.add(current3);
                                  frame.add(blank8);
                                  frame.add(p3TF);
                                  frame.add(prio3TF);
                                  frame.add(blank9);
                                  frame.add(p4L);
                                  frame.add(current4);
                                  frame.add(blank11);
                                  frame.add(p4TF);
                                  frame.add(prio4TF);
                                  frame.add(blank12);
                                  frame.add(blank13);
                                  frame.add(blank14);
                                  frame.add(okB);
                                  frame.add(clearB);
                                  frame.add(awtL);
                                  frame.add(awtLA);
                                  frame.setSize(800,200);
                                  frame.setVisible(true);
                                  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public static void main (String [] args)
              CPUSched O = new CPUSched();
    }

  • Please Help Me, Delete Method(any suggestions!!)

    Can anyone spare the time to look at the below three classes and suggest a method that goes into the customerList class and deletes a record from the Oracle DB they are sitting on top of.
    For example when the deleteCust button is pressed on the form (customerForm) I would like it to delete the current customer (currentCustomer) that is displayed on the form at the time of the button click.
    Can anyone please HELP me, it would be very much appreciated :-)
    customer class
    import java.util.*;
    import java.sql.*;
    public class Customer{
    private int customer_id;
    private String customer_name;
    private String address1;
    private String address2;
    private String town;
    private String county;
    private String post_code;
    private String country;
    private String fax;
    private String telephone;
    private String contact_name;
    private String email;
    private boolean newCustomer;
    //private JobList jobList;
    public Customer(int c){
    customer_id = c;
    newCustomer = true;
    public Customer(int inCustomer_id,String inCustomer_name,String inAddress1, String inAddress2, String inTown, String inCounty,String inPost_code,String inCountry,String inFax,String inTelephone,String inContact_name,String inEmail){
    customer_id=inCustomer_id;
    customer_name=inCustomer_name;
    address1=inAddress1;
    address2=inAddress2;
    town=inTown;
    county=inCounty;
    post_code=inPost_code;
    country=inCountry;
    fax=inFax;
    telephone=inTelephone;
    contact_name=inContact_name;
    email=inEmail;
    newCustomer = false;
    public String getAddress1(){
    if (address1 == null)
    return ("");
    else
    return address1;
    public String getAddress2(){
    if (address2 == null)
    return ("");
    else
    return address2;
    public String getCounty(){
    if (county == null)
    return ("");
    else
    return county;
    public String getFax(){
    if (fax == null)
    return ("");
    else
    return fax;
    public int getCustomer_id(){
    if (customer_id == 0)
    return (0);
    else
    return customer_id;
    public String getCustomer_name(){
    if (customer_name == null)
    return ("");
    else
    return customer_name;
    public String getTelephone(){
    if (telephone == null)
    return ("");
    else
    return telephone;
    public String getPost_code(){
    if (post_code == null)
    return ("");
    else
    return post_code;
    public String getTown(){
    if (town == null)
    return ("");
    else
    return town;
    public String getCountry(){
    if (country == null)
    return ("");
    else
    return country;
    public String getContact_name(){
    if (contact_name == null)
    return ("");
    else
    return contact_name;
    public String getEmail(){
    if (email == null)
    return ("");
    else
    return email;
    /*public JobList getJobList() throws SQLException {
    // if the joblist object exists return it otherwise create it
    if (jobList != null){
    return jobList;
    else{
    return new JobList(this);
    public boolean isNewCustomer(){
    return newCustomer;
    public void setAddress1(String inAddress1){
    address1=inAddress1;
    public void setAddress2(String inAddress2){
    address2=inAddress2;
    public void setCounty(String inCounty){
    county=inCounty;
    public void setFax(String inFax){
    fax=inFax;
    public void setCustomer_id(int inCustomer_id){
    customer_id = inCustomer_id;
    public void setCustomer_name(String inCustomer_name){
    customer_name=inCustomer_name;
    public void setTelephone(String inTelephone){
    telephone=inTelephone;
    public void setPost_code(String inPost_code){
    post_code=inPost_code;
    public void setTown(String inTown){
    town=inTown;
    public void setCountry(String inCountry){
    country=inCountry;
    public void setContact_name(String inContact_name){
    contact_name=inContact_name;
    public void setEmail(String inEmail){
    email=inEmail;
    customerList class
    import java.sql.*;
    import java.util.*;
    public class CustomerList{
    private ResultSet rs ;
    private Connection con;
    private Statement stmt;
    public CustomerList () {
    ConnectionManager man = ConnectionManager.getInstance();
    con = man.getConnection();
    public Customer getFirstCustomer()throws SQLException {
    Customer firstCustomer;
    stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
    rs = stmt.executeQuery("select customer_id,customer_name,address1,address2,town,county,post_code,country,fax,telephone,contact_name,email from customer");
    rs.next();
    firstCustomer = loadCustomer();
    return firstCustomer;
    public Customer getLastCustomer() throws SQLException{
    Customer lastCustomer;
    rs.last();
    lastCustomer = loadCustomer();
    return lastCustomer;
    public Customer getNextCustomer()throws SQLException{
    Customer nextCustomer ;
    if (rs.next()){
    nextCustomer = loadCustomer();
    else{
    nextCustomer = null;
    return nextCustomer;
    public Customer getPreviousCustomer()throws SQLException{
    Customer previousCustomer;
    if (rs.previous()){
    previousCustomer = loadCustomer();
    else
    previousCustomer = null;
    return previousCustomer;
    public Customer findCustomer(int inCustNum) throws SQLException{
    Customer foundCust;
    if (inCustNum==0){
    foundCust = getFirstCustomer();
    else{
    stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
    rs = stmt.executeQuery("select customer_id,customer_name,address1,address2,town,county,post_code,country,fax,telephone,contact_name,email from customer where customer_id = "+inCustNum);
    if (rs.next()){
    foundCust = loadCustomer();
    else
    foundCust = null;
    return foundCust;
    public Customer addCust()throws SQLException{
    Statement stmt2 = con.createStatement();
    ResultSet rsadd = stmt2.executeQuery("select custid.nextval from dual");
    rsadd.next();
    int id = rsadd.getInt("nextval");
    rsadd.close();
    stmt2.close();
    Customer newCust = new Customer(id);
    return newCust;
    public Customer saveCustomer(Customer inSaveCust)throws SQLException{
    Statement stmt3 = con.createStatement();
    int rowNum;
    //int incid = inSaveCust.getCid();
    if (inSaveCust.isNewCustomer()){
    stmt3.executeUpdate("insert into customer values ("
    +inSaveCust.getCustomer_id()
    +",'"+inSaveCust.getCustomer_name()
    +"','"+inSaveCust.getAddress1()
    +"','"+inSaveCust.getAddress2()
    +"','"+ inSaveCust.getTown()
    +"','"+ inSaveCust.getCounty()
    +"','"+inSaveCust.getPost_code()
    +"','"+inSaveCust.getCountry()
    +"','"+inSaveCust.getFax()
    +"','"+ inSaveCust.getTelephone()
    +"','"+inSaveCust.getContact_name()
    +"','"+inSaveCust.getEmail()+"')");
    inSaveCust = getFirstCustomer();//refreshes list after insert
    inSaveCust = getLastCustomer();// goes to the inserted record ie last one
    else {
    rowNum = rs.getRow();//traps the record number so can be returned to
    stmt3.executeUpdate("update customer set customer_name = '"+inSaveCust.getCustomer_name()
    + "', address1 = '"+inSaveCust.getAddress1()
    + "', address2 = '"+inSaveCust.getAddress2()
    + "', town = '"+ inSaveCust.getTown()
    + "', county = '"+ inSaveCust.getCounty()
    + "', post_code = '"+inSaveCust.getPost_code()
    + "', telephone = '"+inSaveCust.getCountry()
    + "', fax = '"+inSaveCust.getFax()
    + "', country = '"+inSaveCust.getTelephone()
    + "', contact_name = '"+inSaveCust.getContact_name()
    + "', email = '"+inSaveCust.getEmail()
    +"' where customer_id = "+inSaveCust.getCustomer_id());
    inSaveCust = getFirstCustomer();
    rs.absolute(rowNum); // points back to same record number as updated
    inSaveCust = loadCustomer();
    con.commit();
    return inSaveCust;
    //Trying to add in the delete method here(as u can see it is not working)
    /*public Customer deleteCustomer() throws SQL Exception {
    stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
    rs = stmt4.executeQuery("delete from customer where customer_id = "Integer.parseInt(textCustomer_id.getText()));
    rs.next();
    firstCustomer = loadCustomer();
    return firstCustomer;
    public boolean isFirst() throws SQLException{
    return rs.isFirst();
    public boolean isLast() throws SQLException{
    return rs.isLast();
    public Customer loadCustomer ()throws SQLException{
    Customer cust = new Customer(rs.getInt("customer_id"),rs.getString("customer_name"),rs.getString("address1"),
    rs.getString("address2"),rs.getString("town"),rs.getString("county"),
    rs.getString("post_code"),rs.getString("country"),rs.getString("fax"),
    rs.getString("telephone"),rs.getString("contact_name"),rs.getString("email"));
    return cust;
    customerForm class
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.util.*;
    public class CustomerForm extends JFrame implements ActionListener {
    private Customer currentCustomer;
    private CustomerList inCustomerList;
    private JPanel panel;
    private JTextField textCustomer_id,textCustomer_name,textAddress1,textAddress2,textTown,
    textCounty,textPost_code,textCountry,textTelephone,textFax,textContact_name,textEmail,textFind;
    private JButton nextCust, prevCust,firstCust,lastCust,newCust,
    findCust,add,save,delete,jobs,close,deleteCust;
    public CustomerForm(CustomerList inC)throws SQLException{
    inCustomerList = inC;
    currentCustomer = inCustomerList.getFirstCustomer();
    displayForm();
    displayFields();
    setTextFields();
    displayButtons();
    getContentPane().add(panel);
    setVisible(true);
    public void displayForm() throws SQLException{
    setTitle("Customer Form");
    setSize(700,500);
    // Center the frame
    Dimension dim = getToolkit().getScreenSize();
    setLocation(dim.width/2-getWidth()/2, dim.height/2-getHeight()/2);
    getContentPane().setLayout(new BorderLayout());
    Border etched = BorderFactory.createEtchedBorder();
    panel = new JPanel();
    panel.setLayout( null );
    Border paneltitled = BorderFactory.createTitledBorder(etched,"");
    panel.setBorder(paneltitled);
    panel.setBackground(new Color(224,224,255));
    public void displayFields() throws SQLException{
    int x = 10;
    int y = 50;
    int textheight = 20;
    int textwidth = 150;
    int labelwidth = 110;
    int ydist = textheight + 10;
    int xdist = textwidth*2;
    JLabel labelCustomer_id = new JLabel("Customer Number:");
    labelCustomer_id.setBounds( x, y, labelwidth, textheight);
    panel.add(labelCustomer_id);
    JLabel labelCustomer_name = new JLabel("Customer Name:");
    labelCustomer_name.setBounds(xdist, y, labelwidth, textheight);
    panel.add(labelCustomer_name);
    JLabel labelAddress1 = new JLabel("Address 1:");
    labelAddress1.setBounds( x, y+ydist, labelwidth, textheight);
    panel.add(labelAddress1);
    JLabel labelAddress2 = new JLabel("Address 2:");
    labelAddress2.setBounds( xdist, y+ydist, labelwidth, textheight);
    panel.add(labelAddress2);
    JLabel labelTown = new JLabel("Town:");
    labelTown.setBounds(x, y+ydist*2, labelwidth, textheight);
    panel.add(labelTown);
    JLabel labelCounty = new JLabel("County:");
    labelCounty.setBounds(xdist, y+ydist*2, labelwidth, textheight);
    panel.add(labelCounty);
    JLabel labelPost_code = new JLabel("Post Code:");
    labelPost_code.setBounds(x, y+ydist*3, labelwidth, textheight);
    panel.add(labelPost_code);
    JLabel labelCountry = new JLabel("Country:");
    labelCountry.setBounds(xdist, y+ydist*3, labelwidth, textheight);
    panel.add(labelCountry);
    JLabel labelTelephone = new JLabel("Phone:");
    labelTelephone.setBounds(x, y+ydist*4, labelwidth, textheight);
    panel.add(labelTelephone);
    JLabel labelFax = new JLabel("Fax:");
    labelFax.setBounds(xdist, y+ydist*4, labelwidth, textheight);
    panel.add(labelFax);
    JLabel labelContact_name = new JLabel("Contact Name:");
    labelContact_name.setBounds(x, y+ydist*5, labelwidth, textheight);
    panel.add(labelContact_name);
    JLabel labelEmail = new JLabel("E-mail address:");
    labelEmail.setBounds(xdist, y+ydist*5, labelwidth, textheight);
    panel.add(labelEmail);
    JLabel labelFind = new JLabel("Customer Number Search:");
    labelFind.setBounds( 40, 360, 200, textheight);
    panel.add(labelFind);
    textAddress1 = new JTextField();
    textAddress1.setBounds(x+labelwidth, y+ydist, textwidth, textheight);
    panel.add(textAddress1);
    textAddress2 = new JTextField();
    textAddress2.setBounds(xdist+labelwidth, y+ydist, textwidth, textheight);
    panel.add(textAddress2);
    textTown = new JTextField();
    textTown.setBounds(x+labelwidth, y+ydist*2, textwidth, textheight);
    panel.add(textTown);
    textCounty = new JTextField();
    textCounty.setBounds(xdist+labelwidth, y+ydist*2, textwidth, textheight);
    panel.add(textCounty);
    textPost_code = new JTextField();
    textPost_code.setBounds(x+labelwidth, y+ydist*3, textwidth, textheight);
    panel.add(textPost_code);
    textCountry = new JTextField();
    textCountry.setBounds(xdist+labelwidth, y+ydist*3, textwidth, textheight);
    panel.add(textCountry);
    textTelephone = new JTextField();
    textTelephone.setBounds(x+labelwidth, y+ydist*4, textwidth, textheight);
    panel.add(textTelephone);
    textFax = new JTextField();
    textFax.setBounds(xdist+labelwidth, y+ydist*4, textwidth, textheight);
    panel.add(textFax);
    textContact_name = new JTextField();
    textContact_name.setBounds(x+labelwidth, y+ydist*5, textwidth, textheight);
    panel.add(textContact_name);
    textEmail = new JTextField();
    textEmail.setBounds(xdist+labelwidth, y+ydist*5, textwidth+50, textheight);
    panel.add(textEmail);
    textFind = new JTextField();
    textFind.setBounds(200, 360, 80, textheight);
    panel.add(textFind);
    textCustomer_id = new JTextField();
    textCustomer_id.setBounds(x+labelwidth, y, textwidth, textheight);
    panel.add(textCustomer_id);
    textCustomer_name = new JTextField();
    textCustomer_name.setBounds(xdist+labelwidth, y, textwidth+50, textheight);
    panel.add(textCustomer_name);
    public boolean delete() {
    textCustomer_id.setText("");
    textCustomer_name.setText("");
    textAddress1.setText("");
    textAddress2.setText("");
    textTown.setText("");
    textCounty.setText("");
    textPost_code.setText("");
    textCountry.setText("");
    textTelephone.setText("");
    textFax.setText("");
    textContact_name.setText("");
    textEmail.setText("");
    textFind.setText("");
    return true;
    public void displayButtons(){
    firstCust= new JButton("FIRST");
    firstCust.addActionListener(this);
    firstCust.setBounds(50, 430, 100, 20 );
    panel.add( firstCust );
    nextCust = new JButton("NEXT");
    nextCust.addActionListener(this);
    nextCust.setBounds(150, 430, 100, 20 );
    panel.add( nextCust );
    prevCust = new JButton("PREVIOUS");
    prevCust.addActionListener(this);
    prevCust.setBounds(250, 430, 100, 20 );
    panel.add( prevCust );
    lastCust= new JButton("LAST");
    lastCust.addActionListener(this);
    lastCust.setBounds(350, 430, 100, 20 );
    panel.add( lastCust );
    findCust= new JButton("FIND");
    findCust.addActionListener(this);
    findCust.setBounds(350, 360, 100, 20 );
    panel.add( findCust );
    add = new JButton("ADD");
    add.addActionListener(this);
    add.setBounds(150, 400, 100, 20 );
    panel.add( add );
    save = new JButton("SAVE");
    save.addActionListener(this);
    save.setBounds(250, 400, 100, 20 );
    panel.add( save );
    jobs = new JButton("JOBS");
    jobs.addActionListener(this);
    jobs.setBounds(550, 360, 100, 20 );
    panel.add( jobs );
    close = new JButton("CLOSE");
    close.addActionListener(this);
    close.setBounds(550, 430, 100, 20 );
    panel.add( close );
    delete = new JButton("DELETE");
    delete.addActionListener(this);
    delete.setBounds(350, 400, 100, 20 );
    panel.add( delete );
    deleteCust = new JButton("DELETECUST");
    deleteCust.addActionListener(this);
    deleteCust.setBounds(450, 400, 100, 20);
    panel.add( deleteCust );
    public void getTextFields(){
    currentCustomer.setCustomer_id(Integer.parseInt(textCustomer_id.getText()));
    currentCustomer.setCustomer_name(textCustomer_name.getText());
    currentCustomer.setAddress1(textAddress1.getText());
    currentCustomer.setAddress2(textAddress2.getText());
    currentCustomer.setTown(textTown.getText());
    currentCustomer.setCounty(textCounty.getText());
    currentCustomer.setPost_code(textPost_code.getText());
    currentCustomer.setCountry(textCountry.getText());
    currentCustomer.setFax(textFax.getText());
    currentCustomer.setTelephone(textTelephone.getText());
    currentCustomer.setContact_name(textContact_name.getText());
    currentCustomer.setEmail(textEmail.getText());
    public void setTextFields() throws SQLException{
    textCustomer_id.setText(String.valueOf(currentCustomer.getCustomer_id()));
    textCustomer_id.setEditable(false);
    textCustomer_name.setText(currentCustomer.getCustomer_name());
    textAddress1.setText(currentCustomer.getAddress1());
    textAddress2.setText(currentCustomer.getAddress2());
    textTown.setText(currentCustomer.getTown());
    textCounty.setText(currentCustomer.getCounty());
    textPost_code.setText(currentCustomer.getPost_code());
    textCountry.setText(currentCustomer.getCountry());
    textFax.setText(currentCustomer.getFax());
    textTelephone.setText(currentCustomer.getTelephone());
    textContact_name.setText(currentCustomer.getContact_name());
    textEmail.setText(currentCustomer.getEmail());
    public void actionPerformed(ActionEvent e) {
    Object source = e.getSource();
    try {
    if (source == nextCust)
    currentCustomer = inCustomerList.getNextCustomer();
    else if (source == prevCust)
    currentCustomer = inCustomerList.getPreviousCustomer();
    else if (source == findCust) {
    try {
    currentCustomer =
    inCustomerList.findCustomer(Integer.parseInt(textFind.getText()));
    catch (NumberFormatException ex) {
    JOptionPane.showMessageDialog(
    null, "Invalid Customer number", "ERROR",
    JOptionPane.ERROR_MESSAGE);
    if (currentCustomer == null) {
    JOptionPane.showMessageDialog(null, "Customer not found");
    currentCustomer = inCustomerList.getFirstCustomer();
    textFind.setText(null);
    else if (source == firstCust)
    currentCustomer = inCustomerList.getFirstCustomer();
    else if (source == lastCust)
    currentCustomer = inCustomerList.getLastCustomer();
    else if (source == add) {
    currentCustomer = inCustomerList.addCust();
    add.setEnabled(false);
    else if (source == delete) {
    delete();
    else if (source == save) {
    add.setEnabled(true);
    getTextFields();
    currentCustomer = inCustomerList.saveCustomer(currentCustomer);
    //else if (source == jobs) {
    // JFrame newJobForm = new JobForm(currentCustomer.getJobList());
    //else if (source == deleteCust) {
    //........... //currentCustomer = inCustomerList.deleteCustomer(currentCustomer);
    else if (source == close) {
    dispose();
    setTextFields();
    nextCust.setEnabled(!inCustomerList.isLast());
    prevCust.setEnabled(!inCustomerList.isFirst());
    firstCust.setEnabled(!inCustomerList.isFirst());
    lastCust.setEnabled(!inCustomerList.isLast());
    catch (SQLException ex) {
    System.out.println("Failed");
    System.out.println(ex.getMessage());
    ex.printStackTrace();
    System.exit(-1);
    PLEASE HELP ME!!!

    http://www.ss64.demon.co.uk/orasyntax/

  • Please Help/ GUI Calculator

    I'm trying to create a GUI Calculator but cannot get my program to compile. Please could someone assistm, thanks.
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class CalculatorFrame extends JFrame
         private Container contentPane;
         //The componenets used in the calculator
         private JTextField display;
         private JButton addition;
         private JButton subtract;
         private JButton multiply;
         private JButton divide;
         private JButton mod;
         private JButton enter;
         private JButton [] digits;
         //End of components
         //Integer representations for the arithmetic operations needed
         private final static int ADD = 1;
         private final static int SUB = 2;
         private final static int MUL = 3;
         private final static int DIV = 4;
         private final static int MOD = 5;
         //ENd of arithmethic operations
         //Integer holding the operator that the user requested
         private int op;
         //Boolean variable to help perform the calculations
         private boolean firstFilled;
         private boolean clearScreen;
         //Constructor for the class
         public CalculatorFrame()
         contentPane=new Container();
         this.setSize(400,300); //sets the size of the frame
         this.setTitle("MIS 222 Calculator"); //sets the title of the frame
         //allows the "X" box in the upper right hand corner to close the entire application
         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         contentPane=this.getContentPane(); //gets the content pane
         //Methods
         addDisplay();
         addDigits();
         addDigitActionListeners();
         addOperation();
    private void addDisplay()
         JLabel displayLab = new JLabel("Answer");
         JPanel north = new JPanel();
         north.add(displayLab);
         contentPane.add(north, "North");
    //diplay was already declared above the constructor
         display = new JTextField(25);
    //adding the components to the panel
         north.add(displayLab);
         north.add(display);
    //adding the panel to frame's content pane
         contentPane.add(north, "North");
    //Declaring the global digits array
    private void addDigits()
         //Add 1 large panel to hold the 3 inner panels
         JPanel digPanel = new JPanel();
         //Set the panel's preferred size so that it will keep everything in line
         digPanel.setPreferredSize(new Dimension(200, 275));
         //Initialize the top 3 digits' JPanel and set its preferrd size
         JPanel topDigits = new JPanel();
         topDigits.setPreferredSize(new Dimension(200,60));
         //Initialize the middle 2 digits' JPanel and set its preferred size
         JPanel midDigits = new JPanel();
         midDigits.setPreferredSize(new Dimension(200,60));
         //Initialize the bottom digits' JPanel and set its preferred size
         JPanel botDigits = new JPanel();
         botDigits.setPreferredSize(new Dimension(200, 75));
         //Initialize the JButton array
         digits = new JButton[11];
         //Initialize each of the top Panel's digit buttons, and add it to the top panel
         for(int i=1; i<4; i++)
              String lab=(new Integer(i)).toString();
              digits=new JButton(lab);
              topDigits.add(digits[i]);
              //Adding the top Digit Panel to the overall digit panel
              digPanel.add(topDigits, BorderLayout.CENTER);
              //Adding the middle Digit Panel to the overall digit panel
              digPanel.add(midDigits, BorderLayout.CENTER);
              //Adding the bottom Digit Panel to the overall digit panel
              digPanel.add(botDigits, BorderLayout.CENTER);
              //Add the overall digit Panel to the Frame's contentpane
              contentPane.add(digPanel, BorderLayout.CENTER);
              //Method created to add the DigitAction Listeners
              addDigitActionListeners();
    //Method created to add all of the DigitActionListeners
    private void addDigitActionListeners()
              for(int i=0; i<10; i++)
                   digits[i].addActionListener(new DigitActionListener(i));
              digits[10].addActionListener(new DigitActionListener("."));
    //DigitActionListener class
    public class DigitActionListener implements ActionListener
         private String myNum;
         public DigitActionListener(int num)
              myNum=""+num;
         public DigitActionListener(String num)
              myNum=num;
         public void actionPerformed(ActionEvent e)
              if(display.getText().equals("Please enter a valid number")|| clearScreen)
                   clearScreen=false;
                   display.setText("");
    //OperatorActionListener class
    public void OpActionListener implements ActionListener
         private int myOpNum;
         public OpActionListener(int op)
              myOpNum=op;
         public void actionPerformed(ActionEvent e)
         {  //Checks to see if the user has already enterd a number
              if(!firstFilled)
              try{
                   //Parse the number entered
                   String number=display.getText();
                   dNum1=Double.parseDouble(number);
                   //Sets the flag for the firstFilled to true
                   firstFilled=true
                   //Sets the op variable so when the "Enter" button is pressed, it will know which operation to perform
                   op=myOpNum;
                   //Clears the textbox
                   display.setText("");
                   catch(Exception er)
                        display.setText("Please enter a valid number");
         //This is the second number being entered
              else{
                   try{
                        String number=display.getText();
                        String result;
                        dNum2=Double.parseDouble(number);
                        firstFilled=true;
                        op=myOpNum;
                        display.setText("");
                   catch(Exception er)
                        display.setText("Please enter a valid number");
    private void addOperation()
         JPanel opPanel=new JPanel();
         opPanel.setPreferredSize(new Dimension(75,200));
         JButton clear = new JButton("C");
         JButton addition = new JButton("+");
         JButton subtraction = new JButton("-");
         JButton multiply = new JButton("*");
         JButton divide = new JButton("/");
         JButton mod = new JButton("%");
         JButton enter = new JButton("Enter");
         addition.addActionListener(new OpActionListener(ADD));
         subtraction.addActionListener(new OpActionListener(SUB));
         multiply.addActionListener(new OpActionListener(MUL));
         divide.addActionListener(new OpActionListener(DIV));
         mod.addActionListener(new OpActionListener(MOD));
         clear.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                   display.setText("");
                   firstFilled=false;
         enter.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                   double result;
                   String answer="";
                   String number = display.getText();
                   dNum2 = Double.parseDouble(number);
                   dNum1=Double.parseDouble(number);
                   switch(op)
                        case ADD:
                             result = dNum1 + dNum2;
                             break;
                        case SUB:
                             result = dNum1 - dNum2;
                             break;
                        case MUL:
                             result = dNum1 * dNum2;
                             break;
                        case DIV:
                             result = dNum1 / dNum2;
                             break;
                        default:
                             result= -1.0;
                             break;
                        if(result==(int)result)
                             answer=(new Integer((int)result)).toString();
                        else
                             answer=(new Double(result)).toString();
                        display.setText(answer);
                        clearScreen=true;
                        firstFilled=false;
                        dNum1=0;
                        dNum2=0;
              opPanel.add(clear);
              opPanel.add(addition);
              opPanel.add(subtraction);
              opPanel.add(multiply);
              opPanel.add(divide);
              opPanel.add(mod);
              opPanel.add(enter);
              contentPane.add(opPanel, "East");
         //Creating the frame object
         public class CalculatorMain
              public void main(String[] args)
                   CalculatorFrame cf=new CalculatorFrame();
                   cf.show();
    ERRORS THAT I HAVE!!:
    javac calculatorframe.javacalculatorframe.java:150: '(' expected
    public void OpActionListener implements ActionListener
    ^
    calculatorframe.java:7: class CalculatorFrame is public, should be declared in a file named CalculatorFrame.java
    public class CalculatorFrame extends JFrame
    ^
    calculatorframe.java:54: cannot resolve symbol
    symbol : method addOperation ()
    location: class CalculatorFrame
    addOperation();
    ^
    3 errors
    >

    Hi, actually it's all written there:
    >
    ERRORS THAT I HAVE!!:
    javac calculatorframe.javacalculatorframe.java:150: '(' expected
    public void OpActionListener implements
    ActionListenerpublic void ... is part of a possible method signature. That's probably why the compiler expects '(' as this is need for a method.
    To define a class use:
    public class ... (or better: private class ..., if the class is not used outside of this file.
    ^
    calculatorframe.java:7: class CalculatorFrame is
    public, should be declared in a file named
    CalculatorFrame.java
    public class CalculatorFrame extends JFrame
    ^As it says, you defined a class CalculatorFrame in a file calculatorframe.java. But the file name should be the same as the class name (case sensitive). Java classes should start with capital letters, so rename the file to:
    CalculatorFrame.java
    calculatorframe.java:54: cannot resolve symbol
    symbol : method addOperation ()
    location: class CalculatorFrame
    addOperation();
    ^
    3 errors
    >You didn't declare the method 'addOperation' (-> cannot resolve symbol; which simbol: method addOperation (); where: location: class CalculatorFrame; you see it's all there)
    Note there is a method called 'addOperation' in the class OpActionListener, but not in CalculatorFrame.
    Note I didn't read the code, just the error messages. I hope this helps.
    -Puce

  • PrintStream Problem, please help!

    My goal is to create and print to a file. The program will create the file but won't print to it. I can't find anything wrong, please take look and help if you can.
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    public class ScribbleAndSave extends JApplet implements ActionListener
    // Declaring a JTextField object
    public static JTextField jtxField;
    // Create an instance of the applet
    public static ScribbleAndSave applet = new ScribbleAndSave();
    // Declare an instance of JFrame
    private static JFrame frame;
    private JButton jbt = new JButton("Save");
    // This main method enables the applet to run as an application
    public static void main(String[] args)
    // Create a frame object
    frame = new JFrame("Scribbling Demo");
    // Add the applet instance to the frame object
    frame.getContentPane().add(applet, BorderLayout.CENTER);
    // Add the JTextField instance to the frame object
    jtxField = new JTextField();
    // Invoke int() and start() to start the applet
    applet.init();
    applet.start();
    // Display the frame
    frame.setSize(300, 300);
    frame.setVisible(true);
    // Initialize the applet
    public void init()
    // Create a paint panel and add it to the applet
    getContentPane().add(new ScribblePanel(), BorderLayout.CENTER);
    getContentPane().add(jtxField, BorderLayout.SOUTH);
    getContentPane().add(jbt, BorderLayout.NORTH);
    jbt.addActionListener(this);
    public void actionPerformed(ActionEvent e)
    String actionCommand = e.getActionCommand();
    if (e.getSource() instanceof JButton)
    if ("Save".equals(actionCommand))
    try
    pw = new PrintWriter(new FileOutputStream(myFile));
    for (int i=0; i<ScribblePanel.mainVector.size(); i++)
    tempPointsVector = (Vector)ScribblePanel.mainVector.elementAt(i);
    for (int j = 1; j<tempPointsVector.size(); j++)
    tempLineStart = (Point)tempPointsVector.elementAt(j-1);
    tempLineDraw = (Point)tempPointsVector.elementAt(j);
    pw.print(tempLineStart.x + " " + tempLineStart.y + " " tempLineDraw.x " " + tempLineDraw + " ");
    catch (IOException ex)
    System.out.print(" Place holder ");
    else if ("Open".equals(actionCommand))
    open();
    Point tempLineStart = new Point(0, 0);
    Point tempLineDraw = new Point(0, 0);
    Vector tempPointsVector = new Vector();
    PrintWriter pw = null;
    File myFile = new File("myfile.dat");
    private void open()
    public void start(){
    // ScribblePanel class for scribbling using the mouse
    class ScribblePanel extends JPanel implements MouseListener, MouseMotionListener{
    // Circle diameter used for erasing
    final int CIRCLESIZE = 20;
    // Declaring and creating Point objects
    private Point lineStart = new Point(0, 0);
    private Point lineDraw = new Point(0, 0);
    // Create a Graphics object for drawing
    private Graphics g;
    // Declaring and creating vectors to hold points
    public static Vector pointsVector;
    public static Vector mainVector = new Vector();
    // Default constructor
    public ScribblePanel()
    // Register listeners for the mouse event
    addMouseListener(this);
    addMouseMotionListener(this);
    public void mouseClicked(MouseEvent e){
    public void mouseEntered(MouseEvent e){
    public void mouseExited(MouseEvent e){
    public void mouseReleased(MouseEvent e){
    // Add vectors to main vector
    mainVector.addElement(pointsVector);
    public void mousePressed(MouseEvent e){
    // Create pointsVector vector
    pointsVector = new Vector();
    // Show first point in JTextField object
    ScribbleAndSave.jtxField.setText("("+e.getX() + ", " + e.getY()+ ")");
    // Move first point to lineStart object
    lineStart.move(e.getX(), e.getY());
    public void mouseDragged(MouseEvent e){
    // Get graphics context
    g = getGraphics();
    // Detect right button pressed
    if (e.isMetaDown()){
    // Erase the drawing using an oval
    g.setColor(getBackground());
    g.fillOval(e.getX() - (CIRCLESIZE/2), e.getY() - (CIRCLESIZE/2), CIRCLESIZE, CIRCLESIZE);
    else {
    // Do scribbling
    g.setColor(Color.black);
    g.drawLine(lineStart.x, lineStart.y, e.getX(), e.getY());
    // Save successive points in vector objects
    pointsVector.addElement(new Point(lineStart.x, lineStart.y));
    pointsVector.addElement(new Point(e.getX(), e.getY()));
    // Show successive points in JTextField object
    ScribbleAndSave.jtxField.setText("("+e.getX()+", " + e.getY()+")");
    // Dispose this graphics context
    g.dispose();
    // Move successive points to lineStart object to be used as starting points
    lineStart.move(e.getX(), e.getY());
    public void paintComponent(Graphics g){
    // Reproduce scribbling
    g.setColor(Color.blue);
    for (int i=0; i<mainVector.size(); i++){
    pointsVector =(Vector)mainVector.elementAt(i);
    for (int j = 1; j<pointsVector.size(); j++){
    lineStart = (Point)pointsVector.elementAt(j-1);
    lineDraw = (Point)pointsVector.elementAt(j);
    g.drawLine(lineStart.x, lineStart.y, lineDraw.x, lineDraw.y);
    // Dispose the graphics context
    g.dispose();
    public void mouseMoved(MouseEvent e){
    }

    Check ScribblePanel.mainVector.size() it is always
    zeroJust by curiosity I double checked, but that was not so, SciribblePanel.mainVector.size() was not always. Should you attempt to run the program do a system.out.print() check and would realize that. Also understand the goal of the program is to create a file and collect in it the coordinates scribbled on the panel. The program accomplishes all steps except printing in the file. Please help!!

  • Please help understand this error...

    I am developing a small Hash Calculator that calculates MD5/ SHA Hash.
    It has 2 modes,
    1. Text mode in which i have a JTextField - userText where i can enter the text and then when i click on calculate the corresponding hash of the text is evaluated.
    2. File mode in which then the JTextField gets disabled (locked or non editable) and i have button that gets visible through which i can then select a file (through JFileChooser) and when i select a file, i put it's absolute path in the JTextField - userText. and then when i click on calculate this code is run...
    FileInputStream in=new FileInputStream(userText.getText());
                             int length=0;
                             while((length=in.read(buffer))!=-1)
                                  md5.update(buffer,0,length);
                             digest=md5.digest();
                             hex="";
                             for (int i = 0; i < digest.length; i++)
                                  int b = digest[i] & 0xff;
                                  if (Integer.toHexString(b).length() == 1) hex = hex + "0";
                                  hex  = hex + Integer.toHexString(b);                                                  
                             hash.setText(algorithm.getSelectedItem().toString()+" Hash: "+hex);
                             copyString(hex);
                             status.setText(algorithm.getSelectedItem().toString()+" Hash copied to ClipBoard",Color.RED);
                             in.close();Now what i am getting is that in case i calculate a hash of a text (default starting mode is text mode) and then change the mode to File then it is working absolutely fine, but if right in the beginning, at the starting i go and select the File Mode, then when i click on calculate i get a strange error.
    I have the stack trace of it :
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
         at java.io.FileInputStream.read(Unknown Source)
         at MD5HashCalculator.calculate(MD5HashCalculator.java:371)
         at MD5HashCalculator.access$3(MD5HashCalculator.java:338)
         at MD5HashCalculator$12.actionPerformed(MD5HashCalculator.java:280)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)This weird thing is happening only the first time and it is happening in the line of the while loop basically
    while((length=in.read(buffer))!=-1)I am unable to understand the error, please help.
    What exactly is happening , and more specifically , why is it happening only if i did the mode change right in the beginning for the first time...??

    this buffer since it had a null value was giving the
    error. I replaced the thing by
    byte buffer[]="".getBytes();
    I'm not sure that's the best thing to do.
    I was reluctant at first to initialise the buffer
    with some bytes as i thought it might effect the md5
    value if it had some value in the beginning, You're supposed to create an empty byte array, e.g. like so:
    byte[] buffer = new byte[1024];In this case, the read method will read at most 1024 bytes into the buffer. The number of bytes it actually reads is returned to you. If it returns 12, say, you should only use the 12 first bytes in the array since those are the bytes that were actually read in. Whatever was in those 12 slots in the array before you called read is overwritten. Then you call read again to see if there are more bytes available, until it returns -1 to signal that there is nothing more to read.
    but i
    have re-checked it accurately, the code is now
    working fine and the MD5 has is coming perfectly.
    This seems strange, as
    "".getBytes();returns a byte array of zero length, which to me suggests you would end up in an infinite loop. But if you say so...

  • Client server code with errors could some one please help me!!!

    I am using a random access file to design the two interfaces for my client and my server is this the right thing to do? Oh could some one give me some example code of client server interfaces.
    I got an error in the code for the interfaces and I don't know what it is could some one please help me!!
    Heres the error in the code: This is for RegisterCustomer
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    class RegisterCustomer extends JPanel implements ActionListener
    // Button for registering a customer
    private JButton jbtRegister;
    // Customer information panel
    private CustomerPanel customerPanel; (The error is on this line and it says Field type customer panel is missing)
    // Random access file
    private RandomAccessFile raf;
    Second error: Its in the ViewCustomer:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    // View customer panel
    class ViewCustomer extends JPanel implements ActionListener
    // Buttons for viewing customer information
    private JButton jbtFirst, jbtNext, jbtPrevious, jbtLast;
    // Random access file
    private RandomAccessFile raf = null;
    // Current customer record
    private Customer customer = new Customer();
    // Create a customer panel
    private CustomerPanel customerPanel = new customerPanel(); (its on this line and it says field type CustomerPanel is missing)
    // File pointer in the random access file
    private long lastPos;
    private long currentPos;
    Heres the code for the customerPanel:
    // Customer Panel.java: Panel for displaying Customer information
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    public class customerPanel extends JPanel
         JTextField jtfRegistrationnumber = new JTextField(30);
         JTextField jtfSeatingcapacity = new JTextField(20);
    JTextField jtfStartdateofhire = new JTextField(20);
    JTextField jtfDurationofhire = new JTextField(10);
    JTextField jtfManufacture = new JTextField(20);
    JTextField jtfModel = new JTextField(15);
         JTextField jtfEnginesize = new JTextField(15);
    JTextField jtfCharge = new JTextField(20);
    JTextField jtfMileage = new JTextField(10);
    // Constuct a customer panel
    public customerPanel()
    // Set the panel with line border
    setBorder(new BevelBorder(BevelBorder.RAISED));
    // Panel p1 for holding all the labels
    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(3, 1));
    p1.add(new JLabel("Registration number"));
    p1.add(new JLabel("Seating capacity"));
    p1.add(new JLabel("Start date of hire"));
    p1.add(new JLabel("Duration of hire"));
    p1.add(new JLabel("Manufacture"));
    p1.add(new JLabel("Model"));
    p1.add(new JLabel("Engine size"));
    p1.add(new JLabel("Charge"));
    p1.add(new JLabel("Mileage"));
    // Panel jpRegistration number for registration number
    JPanel jpRegistrationnumber = new JPanel();
    jpRegistrationnumber.setLayout(new BorderLayout());
    jpRegistrationnumber.add(new JLabel("Registration number"), BorderLayout.WEST);
    jpRegistrationnumber.add(jtfRegistrationnumber, BorderLayout.CENTER);
    // Panel jpSeating capacity for holding Seating capacity
    JPanel jpSeatingcapacity = new JPanel();
    jpSeatingcapacity.setLayout(new BorderLayout());
    jpSeatingcapacity.add(new JLabel("Seating capacity"), BorderLayout.WEST);
    jpSeatingcapacity.add(jtfSeatingcapacity, BorderLayout.CENTER);
         // Panel jpStart date of hire for holding start date of hire
    JPanel jpStartdateofhire = new JPanel();
    jpStartdateofhire.setLayout(new BorderLayout());
    jpStartdateofhire.add(new JLabel("Start date of hire"), BorderLayout.WEST);
    jpStartdateofhire.add(jtfStartdateofhire, BorderLayout.CENTER);
    // Panel jpDuration of hire for holding Duration of hire
    JPanel jpDurationofhire = new JPanel();
    jpDurationofhire.setLayout(new BorderLayout());
    jpDurationofhire.add(new JLabel("Duration of hire"), BorderLayout.WEST);
    jpDurationofhire.add(jtfDurationofhire, BorderLayout.CENTER);
    // Panel p2 for holding jpRegistration number and jpSeating capacity and start date of hire and duration of hire
    JPanel p2 = new JPanel();
    p2.setLayout(new BorderLayout());
    p2.add(jpRegistrationnumber, BorderLayout.WEST);
    p2.add(jpSeatingcapacity, BorderLayout.CENTER);
    p2.add(jpStartdateofhire, BorderLayout.CENTER);
    p2.add(jpDurationofhire, BorderLayout.CENTER);
    // Panel p3 for holding jtfManufacture and p2
    JPanel p3 = new JPanel();
    p3.setLayout(new BorderLayout());
    p3.add(jtfManufacture, BorderLayout.CENTER);
    p3.add(p2, BorderLayout.EAST);
    // Panel p4 for holding jtfModel, jtfEngine size, charge and mileage and p3
    JPanel p4 = new JPanel();
    p4.setLayout(new GridLayout(3, 1));
    p4.add(jtfModel);
    p4.add(jtfEnginesize);
    p4.add(jtfCharge);
    p4.add(jtfMileage);
    p4.add(p3);
    // Place p1 and p4 into customerPanel
    setLayout(new BorderLayout());
    add(p1, BorderLayout.WEST);
    add(p4, BorderLayout.CENTER);
    // Get customer information from the text fields
    public Customer getCustomer()
    return new Customer(jtfRegistrationnumber.getText().trim(),
                             jtfSeatingcapacity.getText().trim(),
                                  jtfStartdateofhire.getText().trim(),
                             jtfDurationofhire.getText().trim(),
                             jtfManufacture.getText().trim(),
                             jtfModel.getText().trim(),
                                  jtfEnginesize.getText().trim(),
                             jtfCharge.getText().trim(),
                             jtfMileage.getText().trim());
    // Set customer information on the text fields
    public void setCustomer(Customer s)
    jtfRegistrationnumber.setText(s.getRegistrationnumber());
    jtfSeatingcapacity.setText(s.getSeatingcapacity());
    jtfStartdateofhire.setText(s.getStartdateofhire());
    jtfDurationofhire.setText(s.getDurationofhire());
    jtfManufacture.setText(s.getManufacture());
    jtfModel.setText(s.getModel());
    jtfEnginesize.setText(s.getEnginesize());
    jtfCharge.setText(s.getCharge());
    jtfMileage.setText(s.getMileage());
    Could someone please help me and tell me what these two errors mean and how I could get rid of them

    Can some one take a look at this code and tell me how to get all my jlabels to line up alone side their jtf.
    Because it looks like this the picture in the attached file and this is the code for it:
    public customerPanel()
    // Set the panel with line border
    setBorder(new BevelBorder(BevelBorder.RAISED));
    // Panel p1 for holding labels Name, Street, and City
    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(5, 1));
    p1.add(new JLabel("Registration Number:"));
    p1.add(new JLabel("Seating Capacity:"));
    p1.add(new JLabel("Engine Size:"));
    p1.add(new JLabel("Start date of hire"));
    p1.add(new JLabel("Duration of hire"));
    JPanel p2 = new JPanel();
    p2.setLayout(new GridLayout(5, 1));
    p2.add(jtfRegistrationnumber);
    p2.add(jtfSeatingcapacity);
    p2.add(jtfEnginesize);
    p2.add(jtfStartdateofhire);
    p2.add(jtfDurationofhire);
    //JPanel p3 = new JPanel();
    //p3.add(p1, BorderLayout.WEST);
    //p3.add(p2, BorderLayout.NORTH);
    JPanel p4 = new JPanel();
    p4.setLayout(new GridLayout(4, 1));
    p4.add(new JLabel("Manufacture:"));
    p4.add(new JLabel("Model:"));
    p4.add(new JLabel("Mileage:"));
    p4.add(new JLabel("Charge:"));
    JPanel p5 = new JPanel();
    p5.setLayout(new GridLayout(4, 1));
    p5.add(jtfManufacture);
    p5.add(jtfModel);
    p5.add(jtfMileage);
    p5.add(jtfCharge);
    // JPanel p6 = new JPanel();
    // p6.setLayout(new BorderLayout());
    // p6.add(p4, BorderLayout.SOUTH);
    // p6.add(p5, BorderLayout.EAST);
    // Place p1 and p4 into CustomerPanel
    setLayout(new BorderLayout());
    add(p1, BorderLayout.WEST);
    add(p2, BorderLayout.NORTH);
    add(p4, BorderLayout.SOUTH);
    add(p5, BorderLayout.EAST);
    So could someone please help me and correct my code so that each text lable is lined up next to its jtf java text field.

Maybe you are looking for

  • Can I create a network object from CIDR format or do I need to use IP - netmask?

    Have a cisco ASA running ASA V 8.3 Wondering what the correct syntax is or even if it is possible to create a network object from a list of IP's in CIDR format?  Typically just do this: Create network-object object-group network name network-object 1

  • Create a new space in webcenter space, no document option

    when I create a new space according to User Guide for WebCenter Space Step 1: Create a Space ■ Step 2: Add the Logo to the El Piju Space ■ Step 3: Make the Documents Page Available ■ Step 4: Upload the Banner Image ■ Step 5: Create Subspaces ■ Step 6

  • Webclip automatic refresh in Dashboard

    Hi everyone, I am looking for a way to automatically update webclips in dashboard. In fact, I display my google reader unread articles and it would really help if webclips refresh automatically even if dashboard is hidden. Does anyone have a solution

  • How do you add a device in MAX after getting Error 200220

    Hello, I am receiving the following error when I launch my datalogging software When I open MAX, I noticed that the NI device I am using (USB-TC01) is not listed. Would anyone out there be able to let me know how do I add the the TC01 device? I know

  • How to generate a waveform (with changeable update rate and sample) with USB 6008

    Apologize about my awful English. In Tradition DAQ I can set different update rate with "AO Start" vi. Transform into USB-6008 device things turn into quite different. I don't know which vi I can setup update rate. Is there any example for this. THX