Implementing KeyEvents in a JFrame.

Hello.
I need implement the use of the Tunction Keys (F1, F2, F.....) in my application, I do this adding a KeyLinstener to my JFrame, but when other compoment in the window gains the focus my Frame lost it and no more works the funcion keys.
What can I do?
Thanks.

You need to do something like what is in this article.
http://www.javaworld.com/javaworld/javatips/jw-javatip72.html
or
http://www.javaworld.com/javaworld/javatips/jw-javatip69.html
First one (tip 72) tells you to override rootPane for JDialog but you can also do this for JFrame.
You then regsiter the listeners on the Root Pane for the functions keys and they should work whatever the focus.
The second (tip 69) tells you an old way that adds listeners to every component of the frame/dialog and so detects any key press. This has the advantage of allowing the code to determine for which component of the dialog/frame the key was pressed. If this matters to you then use this way to detect the keystrokes.

Similar Messages

  • Java System Clipboard error implementing inhereted lostOwnership procedure

    I am trying to get a string from the system clipboard manipulate it then put the manipulated string back on the system clipboard. I'm fairly certain i have the accessing the clipboard correct, but i can't figure out an error i'm getting with part of it.
    Error Message:
    Syntax error on token "}", delete this token
    It refers to the "}" that closes the scope of the lostOwnership procedure, which has to be implemented by the class because it is inherited from the "implements ClipboardOwner", but is not implemented by it.
    Code:
    public class Programming12 implements ClipboardOwner{
         private static JFrame frame  = new JFrame("HTS Programming 12");
         private static JTextArea ta;
         private static JButton start = new JButton("START");
         private ClipboardOwner co = this;//must do this because need to use "this" as the ClipboardOwner inside a static
                                                            //function
         public void lostOwnership(Clipboard clipboard, Transferable contents){}/*procedure*/Any help would be appreciated, even if you can possibly point me in the right direction.
    Edited by: Bherms on Dec 13, 2009 10:41 PM

    It works just fine for me (no syntax errors):
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import javax.swing.*;
    public class ClipBoardTest implements ClipboardOwner
         private static JFrame frame  = new JFrame("HTS Programming 12");
         private static JTextArea ta;
         private static JButton start = new JButton("START");
         private ClipboardOwner co = this;//must do this because need to use "this" as the ClipboardOwner inside a static
                                                            //function
         public void lostOwnership(Clipboard clipboard, Transferable contents){}/*procedure*/
    }

  • JComboBox Visibility on JFrame

    Hi All,
    I am developing an Applet application. The application requires a new window to be displayed on button click, so I used JFrame in developing the new window which is popped up. In the new window I need a JComboBox. I added the JComboBox along with the other components to the frame. All the other components added are visible but the JComboBox is not visible. Then I added a border for the ComboBox then the border is visble but the box is not visible. When I click on the area represented by the Border I am able to view the list of the elements that are added to the Combobox. When I select one of the components from the list the selected component is not displayed on the box. I tried using setBackground(Color.white) but I am not able to see the ComboBox and only a white rectagular box is visible. I am not able to see atleast the arrow mark on the ComboBox which is used to display the list of items added to the ComboBox.
    Any help is greatly appreciated,
    Regards,
    Ranjith.

    First of all thanks for your reply
    The code is
    public class PacketConfigurationPanel extends JPanel implements ActionListener{
    //Defining variables
    JFrame frame;
    JComboBox patternComboBox;
    MyTextField typeField;
    Font commonFont;
    int positionX, positionY, frameWidth, frameHeight;
    int dlWidth, dlHeight, prWidth, prHeight;
    //Constructor
    public PacketConfigurationPanel() {
    //Initialization
    frame = new JFrame("Packet Configuration Dialog");
    frameWidth = 500;
    frameHeight = 500;
    frame.setSize(frameWidth, frameHeight);
    Container contentPane = frame.getContentPane();
    contentPane.setLayout(null);
    frame.setVisible(true);
    commonFont = new Font("Dialog", Font.PLAIN, 12);
    positionX = 15;
    positionY = 15;
    positionY += 17;
    String[] element = {"Blah Blah", "Blah Blah"};
    patternComboBox = new JComboBox(element);
    patternComboBox.setFont(commonFont);
    patternComboBox.setVisible(true);
    patternComboBox.setEditable(true);
    //patternComboBox.setForeground(Color.black);
    //patternComboBox.setSelectedIndex(0);
    patternComboBox.setBounds(positionX, positionY, 100, 20);
    //patternComboBox.setOpaque(true);
    contentPane.add(patternComboBox);
    //contentPane.setBackground(Color.blue);
    I removed the code which is used to add other components to the frame and included the code which is used to add the ComboBox. This class is called by another class which is used to develop the applet.
    Waiting for your reply,
    Ranjith.

  • Mimicking Transparency on a JFrame

    Hi I've created the following code to update a JFrame with the background image of the desktop
    import java.awt.MouseInfo;
    import java.awt.Point;
    import java.awt.PointerInfo;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.image.BufferedImage;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.Timer;
    public class MovementListener implements MouseListener, ActionListener{
         private JFrame f;
         private Point start,end,start1,end1;
         private Timer t,t2;
         private float fps = 30.0f;
         private BackgroundImage jp;
         private BufferedImage screenImg;
         public  MovementListener(JFrame frame, BackgroundImage jp){
              this.f = frame;
              this.jp = jp;
              t = new Timer(Math.round(1000.0f/(fps)), this);
              t.stop();
              t2 = new Timer(Math.round(1000.0f/(fps)), this);
              t2.start();
         public void mouseClicked(MouseEvent arg0) {}
         public void mousePressed(MouseEvent arg0) {
              if(arg0.getButton() == MouseEvent.BUTTON1 && inVisibleBounds(arg0.getPoint())){
                   if(t.isRunning())
                        t.restart();
                   else t.start();
                   start = arg0.getPoint();
                   end = start;
         private boolean inVisibleBounds(Point p){
              return jp.contains(p);
         public void mouseReleased(MouseEvent arg0) {
              if(arg0.getButton() == MouseEvent.BUTTON1 && start != null){
                   end = arg0.getPoint();
                   if(!checkEquality(start, end)){
                        moveFrame(start,end);
                   t.stop();
                   start1 = null;
                   end1 = null;
                   start = null;
                   end = null;
         public void mouseEntered(MouseEvent arg0){}
         public void mouseExited(MouseEvent arg0) {}
         private boolean checkEquality(Point a, Point b){
              return a.x == b.x && a.y == b.y;
         private void moveFrame(Point start, Point end){
              Point p = f.getLocation();
              //move horizontally
              p.x += end.x - start.x;
              //move vertically
              p.y += end.y - start.y;
              //f.setVisible(false);
              resetUnderImg(p); //get new Image
              jp.setImage(new ImageIcon(screenImg)); //change background
              //f.setVisible(true);
              f.setLocation(p); //move frame
         public void actionPerformed(ActionEvent arg0) {
              PointerInfo pi = MouseInfo.getPointerInfo();
              resetUnderImg(pi.getLocation());
              //t2 just updates image
              if(arg0.getSource().equals(t2))return;
              if(start1 == null){
                   start1 = pi.getLocation();
                   return;
              }else if(end1 == null){
                   end1 = pi.getLocation();
              if(!checkEquality(start1, end1)){ //check if moved
                   moveFrame(start1,end1);
                   start1 = end1;
                   end1 = null;
         public void resetUnderImg(Point p) {
               int x = p.x;
               int y = p.y;
               int w = f.getWidth();
               int h = f.getHeight();
               screenImg = BackgroundImage.getBackgroundImage();
               if(x + w > screenImg.getWidth())
                    w = screenImg.getWidth() - x;
               if(y + h > screenImg.getHeight())
                    h = screenImg.getHeight() - y;
               screenImg = screenImg.getSubimage(x,y,w,h);
    }As the JFrame is Undecorated this code actually manages Dragging and updating the background my problem is not tin the dragging part of the code it's actually in the repainting part i.e. in the code
    private void moveFrame(Point start, Point end){
              Point p = f.getLocation();
              //move horizontally
              p.x += end.x - start.x;
              //move vertically
              p.y += end.y - start.y;
              //f.setVisible(false);
              resetUnderImg(p); //get new Image
              jp.setImage(new ImageIcon(screenImg)); //change background
              //f.setVisible(true);
              f.setLocation(p); //move frame
         }if I uncomment setVisible(..) I get a flicker�if I don't I get an image that looks like the frames per second on a movie is too slow.... if you know what I mean
    Any help would be appreciated

    Melissa,
    You are not clearly descrbing the situation.
    How many different ink colors
    will be printed?
    Will you use the same
    number of inks regardless of shirt color?
    If you are printing one ink, regardless of the color of the shirt, then you can:
    1. Make the block in your design one SPOT color.
    2. Position the process white lines on top of the block. (No transparency, no overprint.)
    3. Print the spot color SEPARATION.
    The result is a print of a black block with lines "knocked out of it."
    The resulting screen positive can now be used on any color shirt. The printer can simpy use a different colored ink to print it on a black shirt.
    You can also:
    1. Make the block in your design process black.
    2. Position the process white lines on top of the block. (No transparency, no overprint.)
    3. Print a composite.
    The result is the same: A print of a black block with lines "knocked out of it."
    I think what you're misunderstanding is: When working with spot colors,
    it really doesn't matter what color value is applied to the spot color Swatch, but you must print as separations. Regardless of what color the spot color is, the separation print is simply a black image. It can be used to make a printing plate for any color someone choses to load the press (or silkscreen) with.
    JET

  • Problem when to get JFrame components

    I want to get all components from a JFrame. The problem is, when first time i want to get JFrame components...it will print like below...
    nullHi i am button
    Hi i am label
    Hi i am text field
    Hi i am button that you clicked
    but for second time and others, i get true result like below
    Hi i am button
    Hi i am label
    Hi i am text field
    Hi i am button that you clicked
    Can someone show me some light, what mean of null that i get every first time i want to get JFrame components.
    Below is my source code :
    import javax.swing.JFrame;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.GridLayout;
    import java.awt.Component;
    import java.awt.BorderLayout;
    import java.awt.Container;
    public class GetAllComponentInJFrame implements ActionListener
         String storeAllComponentName;
         JFrame frame=new JFrame("Get all component in a JFrame");
         JButton button=new JButton("Button");
         JLabel label=new JLabel("Label");
         JTextField textField=new JTextField("Text field");
         JButton buttonToClick=new JButton("Click here to get all component in JFrame");
         GridLayout gl=new GridLayout(4,1);
         public GetAllComponentInJFrame()
              frame.setLayout(gl);
              buttonToClick.addActionListener(this);
              frame.setName("I am JFrame");
              button.setName("Hi i am button");
              label.setName("Hi i am label");
              textField.setName("Hi i am text field");
              buttonToClick.setName("Hi i am button that you clicked");
              frame.getContentPane().add(button);
              frame.getContentPane().add(label);
              frame.getContentPane().add(textField);
              frame.getContentPane().add(buttonToClick);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(400,400);
              frame.setVisible(true);
         public void actionPerformed(ActionEvent event)
              if(event.getSource()==buttonToClick)
                   Component[]arrayToStoreComponent=frame.getContentPane().getComponents();
                   for(int i=0; i<arrayToStoreComponent.length; i++)
                        Component temp=arrayToStoreComponent;
                        storeAllComponentName=storeAllComponentName+temp.getName()+"\n";
                   System.out.println(storeAllComponentName);
                   storeAllComponentName=new String("");
         public static void main(String[]args)
              GetAllComponentInJFrame gacijf=new GetAllComponentInJFrame();

    So, why i just get it only on first..not on second or third when i click button :
    JButton buttonToClick=new JButton("Click here to get all component in JFrame");I hope you can show me the right way to get all components in JFrame? Thanks for spend a time on my problem.

  • JFrame titleBar resize ???

    hi,i got 2 file :
    satu.java
    import java.awt.BorderLayout;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    public class satu {
    * @param args
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    JFrame.setDefaultLookAndFeelDecorated(true);
    final JFrame appp = new JFrame("TEST ");
    appp.setSize(150,180);
    appp.setResizable(false);
    dua m = new dua(appp);
            m.init();
    appp.add(m,BorderLayout.CENTER);   
        appp.setVisible(true);
        //appp.setLocationRelativeTo(null);
    appp.addWindowListener(new WindowAdapter() {
       public void windowClosing(WindowEvent evt) {
                appp.setVisible(false);
                appp.dispose();
    }dua.java
    import java.applet.Applet;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    public class dua extends Applet implements ActionListener {
    * @param args
    JFrame myframe;
    public dua(JFrame sat){
    myframe = sat;
    public void init(){
    JButton x = new JButton("Big");
    x.addActionListener(this);
    add(x);
    public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
    int newx = myframe.getWidth()+10;
    int newy = myframe.getHeight()+10;
    myframe.setTitle("X = "+newx+" Y = "+newy);
    myframe.setSize(newx,newy);
    the problem is when i clicked the button,the titlebar doesnt resize...what should i add to resize the title bar too ?
    thanks.

    BACK !!! You have to validate parent frame. This works fine:
    import java.awt.BorderLayout;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.applet.Applet;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    public class satu {
        public static void main(String[] args) {
            JFrame.setDefaultLookAndFeelDecorated(true);
            final JFrame appp = new JFrame("TEST ");
            appp.setSize(150,180);
            appp.setResizable(false);
            dua m = new dua(appp);
            m.init();
            appp.add(m,BorderLayout.CENTER);
            appp.setVisible(true);
            appp.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    class dua extends Applet implements ActionListener {
        JFrame myframe;
        public dua(JFrame sat){
            myframe = sat;
        public void init(){
            JButton x = new JButton("Big");
            x.addActionListener(this);
            add(x);
        public void actionPerformed(ActionEvent arg0) {
            int newx = myframe.getWidth()+10;
            int newy = myframe.getHeight()+10;
            myframe.setTitle("X = "+newx+" Y = "+newy);
            myframe.setSize(newx,newy);
            myframe.validate();
    }

  • What the heck am I doing wrong???

    The error message I'm getting is the following: "week4_herbie must be defined in its own file" The problem that I'm running into is that the programs are supposed to work together. One (week4_herbie) handles the mortgage calculation itself (and set up the GUI) and send the information to the amoritizeFrame program, which is designed to display the amoritization table. The numericTextFrame is to make sure that the variable input is acceptable. Here is the coding:
    week4_herbie
    The Amortization Schedule was constructed with my own class called AmortFrame
    that extends JFrame and a JTextArea that was added to a JScrollPane.
    // Imports needed libraries
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    // Event handling:implements listener interface for receiving action events.
    public class week4_herbie implements ActionListener
         // GUI Components
         JFrame calculatorFrame;
         JPanel calculatorPanel;
         AmortizeFrame amortFrame;   //local class for amortization schedule
         //  user input fields
         //  Loan amount entered as user text input from keyboard
         //  Term (in years) selected from a combo box
         //  Rate (%) selected from a combo box
         numericTextField loan;
         JComboBox rate;
         JComboBox term;
         // set up arrays for the selectable term and rate
        int[] loanTerm = new int[3];
        String[] loanTermString = new String[3];
        double[] loanRate = new double[3];
        String[] loanRateString = new String[3];
        // static variables, belong to class on not an instance
         static String sWindowTitle = "Brian's Week 3 - Mortgage Calculator";
         static String scolHeader = "Payment#\tPayment\tInterest\tCumInterest\tPrincipal\tBalance\n";
         static String slineOut = "________\t_______\t________\t___________\t_________\t_______\n";
         static String sfinalInstructions1 = "\nYou can leave windows open and enter new value or close either window to exit\n";
         JLabel loanLabel,termLabel, rateLabel, pmtLabel;
         JButton calculate;
        public week4_herbie()
              // Before progressing, read in the data
              if(readData())
                   //Create and set up the window.
                   calculatorFrame = new JFrame(sWindowTitle);
                   calculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   // Set size of user input frame;
                   calculatorFrame.setBounds(0,0,100,100);
                   //Create and set up the panel with 4 rows and 4 columns.
                   calculatorPanel = new JPanel(new GridLayout(4, 4));
                   //Add the widgets.
                   addWidgets();
                   //Set the default button.
                   calculatorFrame.getRootPane().setDefaultButton(calculate);
                   //Add the panel to the window.
                   calculatorFrame.getContentPane().add(calculatorPanel, BorderLayout.
                   CENTER);
                   //Display the window.
                   calculatorFrame.pack();
                   calculatorFrame.setVisible(true);
              }// good data read
        }// end constructor
        private boolean readData()
              boolean isValid = true;
            loanRateString[0] = "5.35%";
            loanRateString[1] = "5.5%";
            loanRateString[2] = "5.75%";
            loanTermString[0] = "7 Years";
            loanTermString[1] = "15 Years";
            loanTermString[2] = "30 Years";
            loanRate[0] = 5.35;
            loanRate[1] = 5.5;
            loanRate[2] = 5.75;
            loanTerm[0] = 7;
            loanTerm[1] = 15;
            loanTerm[2] = 30;
            return isValid;
         }// end readData
        // Creates and adds the widgets to the user input frame.
        private void addWidgets()
            // numericTextField is a JTextField with some error checking for
            // non  numeric values.
            loan = new numericTextField();
            rate = new JComboBox(loanRateString);
              term = new JComboBox(loanTermString);
            loanLabel = new JLabel("Loan Amount", SwingConstants.LEFT);
            termLabel = new JLabel(" Term ", SwingConstants.LEFT);
            rateLabel = new JLabel("  Interest Rate ", SwingConstants.LEFT);
            calculate = new JButton("Calculate");
            pmtLabel  = new JLabel("Monthly Payment", SwingConstants.LEFT);
            //Listen to events from the Calculate button.
            calculate.addActionListener(this);
            //Add the widgets to the container.
            calculatorPanel.add(loan);
            calculatorPanel.add(loanLabel);
            calculatorPanel.add(term);
            calculatorPanel.add(termLabel);
            calculatorPanel.add(rate);
            calculatorPanel.add(rateLabel);
            calculatorPanel.add(calculate);
            calculatorPanel.add(pmtLabel);
            //set label border size
            loanLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
            pmtLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
        } // end addWidgets
        // Event handling method invoked when an action occurs.
        // Processes each of the fields and includes error checking
        // to make sure each field has data in it and then calculates
        // actual payment.
        public void actionPerformed(ActionEvent event)
            double tamount = 0; //provides floating point for total amount of the loan
            int term1      = 0; //provides int for the term
            double rate1   = 0; //provides floating point for the percentage rate.
            // get string to test that user entered
                String testit = loan.getText();          // get user entered loan amount
                // if string is present
                if(testit.length() != 0)
                   tamount = (double)(Double.parseDouble(testit)); // convert to double
                   // first value valid - check second one, term value
                   // get the index of the item the user selected
                   // then get the actual value of the selection from the
                   // loanTerm array
                   int boxIndex = term.getSelectedIndex();
                   if(boxIndex != -1)
                        term1 = loanTerm[boxIndex];
                        // second value valid - check third one, interest rate
                        // get the index of the item the user selected
                       // then get the actual value of the selection from the
                       // loanRate array
                       boxIndex = rate.getSelectedIndex();
                       // if something is selected in rate combo box
                        if(boxIndex != -1)
                            rate1 = loanRate[boxIndex];
                             // all three values were good so calculate the payment
                        double payment = ((tamount * (rate1/1200)) /
                                              (1 - Math.pow(1 + rate1/1200, -term1*12)));
                        // format string using a mask
                        java.text.DecimalFormat dec = new java.text.DecimalFormat(",###.00");
                        String pmt = dec.format(payment);
                        // change foreground color of font for this label
                        pmtLabel.setForeground(Color.green); //
                        // set formatted payment
                             pmtLabel.setText(pmt);
                             // generate the amortization schedule
                             amortize(tamount, rate1*.01, term1*12, payment);
                        else  //third value was bad
                             Toolkit.getDefaultToolkit().beep(); // invokes audible beep
                             pmtLabel.setForeground(Color.red);  // sets font color
                             pmtLabel.setText("Missing Field or bad value");  // Error Message
                        }// end validate third value
                   else  // second value was bad
                        Toolkit.getDefaultToolkit().beep();
                        pmtLabel.setForeground(Color.red);
                        pmtLabel.setText("Missing Field or bad value");
                   }// end validate second value
              else  // first value was bad
                   Toolkit.getDefaultToolkit().beep();
                   pmtLabel.setForeground(Color.red);
                 pmtLabel.setText("Missing Field or bad value");
              }// end validate first value
        }// end actionPerformed
         // calculate the loan balance and interest paid for each payment over the
         // term of the loan and list it in a separate window - one line per payment.
         public void amortize(double principal, double APR, int term,
                              double monthlyPayment)
              double monthlyInterestRate = APR / 12;
              //double totalPayment = monthlyPayment * term;
              int payment = 1;
              double balance = principal;
              int num = 0;
              double monthlyInterest;
              double cumInterest = 0;
            // if the frame for the amortization schedule has not been created
            // yet, create it.
              if(amortFrame == null)
                 amortFrame = new AmortizeFrame();
              // obtain a reference to our text area in our frame
              // and update this as we go through
              JTextArea amortText = amortFrame.getAmortText();
              // formatting mask
              java.text.DecimalFormat df= new java.text.DecimalFormat(",###.00");
              // set column header
              amortText.setText(scolHeader);
              amortText.append(slineOut);
              // loop through our amortization table and add to
              // JTextArea
              while(num < term)
                   monthlyInterest = monthlyInterestRate * balance;
                   cumInterest += monthlyInterest;
                   principal = monthlyPayment - monthlyInterest;
                   balance -= principal;
                   //Show Amortization Schedule
                   amortText.append(String.valueOf(payment));
                   amortText.append("\t ");
                   amortText.append(df.format(monthlyPayment));
                   amortText.append("\t ");
                   amortText.append(df.format(monthlyInterest));
                   amortText.append("\t ");
                   amortText.append(df.format(cumInterest));
                   amortText.append("\t ");
                   amortText.append(df.format(principal));
                   amortText.append("\t ");
                   amortText.append(df.format(balance));
                   amortText.append("\n");
                   payment++;
                   num++;
              // print the headers one more time at the bottom
              amortText.append(slineOut);
              amortText.append(scolHeader);
              amortText.append(sfinalInstructions1);
         }// end amortize
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI()
            //Make sure we have nice window decorations.
             //Note this next line only works with JDK 1.4 and higher
            JFrame.setDefaultLookAndFeelDecorated(true);
            week4_herbie calculator = new week4_herbie();
        // main method
        public static void main(String[] args)
             // allow user to set a different file from
             // command line
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    }// end classAmoritizeFrame
    import java.awt.*;
    import javax.swing.*;
    // this class provides the frame and the scrolling text area for the
    // amortization schedule
    class AmortizeFrame extends JFrame
         private JTextArea amortText;
         private JScrollPane amortScroll;
         private String sTitle = "Brian's";
         final String sTitle2 = " Amortization Schedule";
         // default constructor
         public AmortizeFrame()
              initWindow();
         // constructor that takes parameter (such as week number)
         // to add extra info to title on frame of window
         public AmortizeFrame(String week)
              sTitle = sTitle + " " + week;
              initWindow();
         }// end constructor
         // helper method that initialized GUI
         private void initWindow()
              setTitle(sTitle + sTitle2);
              setBounds(200,200,550,400);
              Container contentPane=getContentPane();
              amortText = new JTextArea(7,100);
              amortScroll= new JScrollPane(amortText);
              contentPane.add(amortScroll,BorderLayout.CENTER);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
         // method to get the text area for users of
         // this frame.  They can then add whatever text they want from the outside
         public JTextArea getAmortText()
              return amortText;
    }// end amortizeFramenumericTextFrame
    * This is a control that subclasses the
    * JTextField class and through a keyboard
    * listener only allows numeric input, decimal point
    * and backspace into the text field.
    * Known Problems!!!:
    * 1) It will not catch if the user
    *    enters two decimal points
    import java.awt.Toolkit;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import javax.swing.JTextField;
       A JTextField subclass component that
       only allowing numeric input.  
    class numericTextField extends JTextField
        private void setUpListener()
            addKeyListener(new KeyAdapter() {
                public void keyTyped(KeyEvent e)
                            char c = e.getKeyChar();
                    if(!Character.isDigit(c) && c != '.' && c != '\b' && c != '\n' && c != '\177')
                        Toolkit.getDefaultToolkit().beep();
                        e.consume();
        numericTextField(int i)
             super(i);
               setUpListener();
        public numericTextField()
              setUpListener();
    }Thanks for the assist

    Top-level classes (that is, classes not inside other classes) must be defined as public or package-private (the default access level if you do not provide one).
    A public top-level class Foo must be contained in Foo.java.
    A non-public top-level class Foo can be contained in any .java file.

  • Problem with painting/threads/ProgressMonitor

    Hello,
    I'll try to be clear, ask me anything if it isn't. I have two threads, one that downloads some selected webpages, and the other that reads them. In the thread that reads, there is a ProgressMonitor object, which indicate how many webpages have been read.
    I created a JUnit test which works as expected. One thread downloads, the other reads and a nice little progress monitor appears and everything works.
    I transfered the code (the part of the code starting the thread that reads, which starts the thread that downloads) into the main application. The threads are working and the ProgressMonitor appears, but it does not draw the components (there is no label, progress bar, button etc...). I can't seem to find the problem. I think it is caused by the threads or synchronized methods, I am not sure as I am no expert with threads. Once the threads have finished running, the components of the ProgressMonitor appears. So I guess that the threads are blocking the (re)painting of the application, but I can't figure why. Im using Thread.yield() quite often. Priorities problem ? Here some parts of the code :
    JUnit Test code :
         public synchronized void testHarvest() {
              JFrame frame = new JFrame("Super");
              frame.setVisible(true);
              Harvester harvester = new Harvester(
                        frame,
                        new Rule());
              Thread harvest = new Thread(harvester);
              harvest.start();
              try {
                   harvest.join();
              } catch (InterruptedException ie) {}
    ...Main application :
    Code:
    public class Gui extends JFrame implements ComponentListener {
       private static JFrame mMotherFrame = null;
        public Gui() {
            mMotherFrame = this;
        private class GuiActionRealize {
              public synchronized void getFromWeb() {
                   Harvester harvester = new Harvester(
                             mMotherFrame,
                             new Rule());
                   Thread harvest = new Thread(harvester);
                   harvest.start();               
                   try {                    
                        harvest.join();
                   } catch (InterruptedException ie) {}
    }Harvester :
    Code:
    public class Harvester implements Runnable {
      private JFrame mMotherFrame;
      private ProgressMonitor mMonitor;
    public Harvester(JFrame owner, IRule subjectRule) {
       mMotherFrame = owner;
        public void find() {
        mMonitor = new ProgressMonitor(mMotherFrame, "Downloading from the Internet.", "", 1, mAcceptedURLs.size());
         mMonitor.setMillisToDecideToPopup(0);
         mMonitor.setMillisToPopup(0);
    public void run() {
      find();
      mHarvested = harvest();
      mFinished = true;
      Thread.yield();
    public List harvest() {
      download = new DownloadThread(this, mAcceptedURLs);
      Thread downthread = new Thread(download);
      downthread.start(); int i = 0;
      while (!mMonitor.isCanceled()) {
          while (download.getDownloadedDocuments().isEmpty()) {
               try {
                       Thread.yield();
                       Thread.sleep(300);
                } catch (InterruptedException ie) {}
           mMonitor.setNote("Downloading decision " + i);
           mMonitor.setProgress(mMonitor.getMinimum()+ ++i);
           } // end while(!cancel)
           download.kill();
           return mHarvested;
    }I'm very puzzled by the fact that it worked in the JUnit Case and not in the application.
    I can see that the thread that is responsible for drawing components is not doing his job, since that the mother frame (Gui class) is not being repainted while the harvest/download threads are working. That's not the case in the JUnit case, where the frame is being repainted and everything is fine. This is the only place in the application that I'm using threads/runnable objects.
    I also tried making the Gui class a thread by implementing the Runnable interface, and creating the run method with only a repaint() statement.
    And I tried setting the priority of the harvest thread to the minimum. No luck.
    If you need more info/code, let me know, Ill try to give as much info as I can.
    Thank you

    Why are you painting the values yourself? Why don't you just add the selected values to a JList, or create a container with a GridLayout and add a JLabel with the new text to the container.
    Every time you call the paintComponent() method the painting gets done from scratch so you would need to keep a List of selected items and repaint each item every time. Maybe this [url http://forum.java.sun.com/thread.jsp?forum=57&thread=304939]example will give you ideas.

  • How can transfer data from a dialog to another panel?

    Will anyone help me?Thanks.
    In our project,When the user need to fill some data into the textfield in a panel,he can simplify this action by click a button,when the button is clicked,then a dialog which contains a table of all the imformation of all customers will show,then the user can select one customer's information from the table,after click a button such as "OK",the selected information will show in corresponding textfiled in another panel.Because the dialog and the panel are two
    different object,so how can I transfer the data selected from the dialog to the panel and show the updated information timely??

    try this program. it exchanges some data between s adialog and a frame.
    akz
    * @version 1.20 01 Sep 1998
    * @author Cay Horstmann
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class DataExchangeTest extends JFrame
    implements ActionListener
    {  public DataExchangeTest()
    {  setTitle("DataExchangeTest");
    setSize(300, 300);
    JMenuBar mbar = new JMenuBar();
    setJMenuBar(mbar);
    JMenu fileMenu = new JMenu("File");
    mbar.add(fileMenu);
    connectItem = new JMenuItem("Connect");
    connectItem.addActionListener(this);
    fileMenu.add(connectItem);
    exitItem = new JMenuItem("Exit");
    exitItem.addActionListener(this);
    fileMenu.add(exitItem);
    public void actionPerformed(ActionEvent evt)
    {  Object source = evt.getSource();
    if (source == connectItem)
    {  ConnectInfo transfer= new ConnectInfo("yourname", "pw");
    if (dialog == null)
    dialog = new ConnectDialog(this);
    if (dialog.showDialog(transfer))
    {  String uname = transfer.username;
    String pwd = transfer.password;
    Container contentPane = getContentPane();
    contentPane.add(new JLabel("username=" + uname + ", password=" + pwd),"South");
    validate();
    else if(source == exitItem)
    System.exit(0);
    public static void main(String[] args)
    {  JFrame f = new DataExchangeTest();
    f.show();
    private ConnectDialog dialog = null;
    private JMenuItem connectItem;
    private JMenuItem exitItem;
    class ConnectInfo
    {  public String username;
    public String password;
    public ConnectInfo(String u, String p)
    { username = u; password = p; }
    class ConnectDialog extends JDialog implements ActionListener
    {  public ConnectDialog(JFrame parent)
    {  super(parent, "Connect", true);
    Container contentPane = getContentPane();
    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(2, 2));
    p1.add(new JLabel("User name:"));
    p1.add(username = new JTextField(""));
    p1.add(new JLabel("Password:"));
    p1.add(password = new JPasswordField(""));
    contentPane.add("Center", p1);
    Panel p2 = new Panel();
    okButton = addButton(p2, "Ok");
    cancelButton = addButton(p2, "Cancel");
    contentPane.add("South", p2);
    setSize(240, 120);
         //custom method to create and buttons to a container
    JButton addButton(Container c, String name)
    {  JButton button = new JButton(name);
    button.addActionListener(this);
    c.add(button);
    return button;
    public void actionPerformed(ActionEvent evt)
    {  Object source = evt.getSource();
    if(source == okButton)
    {  ok = true;
    setVisible(false);
    else if (source == cancelButton)
    setVisible(false);
    public boolean showDialog(ConnectInfo transfer)
    {  username.setText(transfer.username);
    password.setText(transfer.password);
    ok = false;
    show();
    if (ok)
    {  transfer.username = username.getText();
    transfer.password = password.getText();
    return ok;
    private JTextField username;
    private JTextField password;
    private boolean ok;
    private JButton okButton;
    private JButton cancelButton;

  • How to create a button with an attached menu?

    I don't know how these buttons are called but I'll try to explain what I want to do. I have a toolbar where I have a button that cycles through several functions on every action - I use it to cycle through display modes. Because I do not want to switch through all other posibilties I want a menu next to it where I can directly switch to the desired display mode. Clicking on the button cycles through the modes and clicking on the attached menu provides a direct selection. What I have in mind is something like the "show images / show no images / show cached images only" Button in the Opera webbrowser, see
    http://img32.imagevenue.com/img.php?loc=loc74&#8465;=a33_button_menu.jpg
    Currently I'm using a group of JToggleButtons but since I'm going to add new display modes adding new buttons would make the toolbar look too crowded.

    See if this is useful
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class SwingA implements ActionListener
    JPopupMenu pop;
    JFrame frame;
    JPanel panel;
    JButton cmdPop;
    JDialog dlgFrame;
    int times_clicked = 0;
         public static void main(String[] args)
         SwingA A=new SwingA();
         SwingA()
                    try
              UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                      frame=new JFrame("PopUp");
                      frame.setSize(600,480);
                      frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
                      pop=new JPopupMenu();
                      cmdPop=new JButton("Click");
                     cmdPop.addActionListener(this);
                   JMenuItem item = new JMenuItem("First");
                   JMenuItem item1 = new JMenuItem("Second");
                   pop.add(item);
                   pop.add(item1);
                     panel=new JPanel();
                      panel.add(cmdPop);
                      frame.getContentPane().add(panel);
                      frame.setVisible(true);
              catch(Exception E)
         public void actionPerformed(ActionEvent source)
           pop.show(cmdPop, cmdPop.getWidth(), 0);
    }

  • Adding a contact to an address book, please help!

    hi,
    I'm trying to write new infomation to my file but i cant seem to get it to work.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import java.lang.*;
    import java.text.*;
    public class AddressBook extends JFrame implements ActionListener
         FlowLayout leftLayout;
         JFrame winNew;
    JTextField txtName, txtPhone, txtMobile, txtAddress;
    JButton btnImport, btnAdd, btnNext, btnPrevious, btnSave;
    JLabel lblTitle, lblName, lblPhone, lblMobile, lblAddress;
    JPanel pTitle, pName, pPhone, pMobile, pAddress, pButtons;
         ArrayList<String> Name = new ArrayList<String>();
         ArrayList<String> Phone = new ArrayList<String>();
         ArrayList<String> Mobile = new ArrayList<String>();
         ArrayList<String> Address = new ArrayList<String>();
         ArrayList<String> temp = new ArrayList<String>();
         int index = 0;
              public static void main(String[] args)
              new AddressBook();
         public AddressBook()
              final int WIDTH = 450;
              final int HEIGHT = 400;
              JFrame win = new JFrame("Address Book");
              win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              leftLayout = new FlowLayout(FlowLayout.LEFT);
              pTitle = new JPanel();
              pTitle.setLayout(new FlowLayout(FlowLayout.CENTER));
              lblTitle = new JLabel("Address Book");
              pTitle.add(lblTitle);
              win.add(pTitle);
              win.setLayout(new GridLayout(6,1));
              win.setSize(WIDTH, HEIGHT);
              win.setBackground(Color.BLUE);
              win.setResizable(false);
              win.setLocationRelativeTo(null);
              pName = new JPanel();
              pName.setLayout(leftLayout);
              lblName = new JLabel("Name: ");
              txtName = new JTextField(20);
              win.add(pName);
              pName.add(lblName);
              pName.add(txtName);
              pPhone = new JPanel();
              pPhone.setLayout(leftLayout);
              lblPhone = new JLabel("Phone: ");
              txtPhone = new JTextField(13);
              win.add(pPhone);
              pPhone.add(lblPhone);
              pPhone.add(txtPhone);
              pMobile = new JPanel();
              pMobile.setLayout(leftLayout);
              lblMobile = new JLabel("Mobile: ");
              txtMobile = new JTextField(14);
              win.add(pMobile);
              pMobile.add(lblMobile);
              pMobile.add(txtMobile);
              pAddress = new JPanel();
              pAddress.setLayout(leftLayout);
              lblAddress = new JLabel("Address: ");
              txtAddress = new JTextField(30);
              win.add(pAddress);
              pAddress.add(lblAddress);
              pAddress.add(txtAddress);
              pButtons = new JPanel();
              btnImport = new JButton("Import");
              pButtons.add(btnImport);
              btnImport.addActionListener(this);
              btnAdd = new JButton("Add");
              pButtons.add(btnAdd);
              btnAdd.addActionListener(this);
              btnPrevious = new JButton("Previous");
              pButtons.add(btnPrevious);
              //btnPrevious.addActionListener(this);
              btnNext = new JButton("Next");
              pButtons.add(btnNext);
              //btnNext.addActionListener(this);
              btnSave = new JButton("Save");
              pButtons.add(btnSave);
              btnSave.addActionListener(this);
              win.add(pButtons);
              win.setVisible(true);
         public void actionPerformed(ActionEvent e)
              if (e.getSource() == btnImport)
                   importContacts();
              if (e.getSource() == btnAdd)
                   clearScreen();
              if (e.getSource() == btnPrevious)
                   Previous();
              if (e.getSource() == btnSave)
         writetoFile();
              else if (e.getSource() == btnNext)
                   Next();
              public void importContacts()
              try
                   BufferedReader infoReader = new BufferedReader(new FileReader("../files/example.buab"));
                   int i = 0;
                   String loadContacts;
                   while ((loadContacts = infoReader.readLine()) !=null)
                        temp.add(loadContacts);
                        i++;
                   int a = 0;
                   int b = 0;
                   for (a = 0, b = 0; a < temp.size(); a++, b++)
                   if (b == 4)
                        b = 0;
                   if (b == 0)
                        Name.add(temp.get(a));
                   if (b == 1)
                        Phone.add(temp.get(a));
                   if (b == 2)
                        Mobile.add(temp.get(a));
                   if (b == 3)
                        Address.add(temp.get(a));
              catch (IOException ioe)
              ioe.printStackTrace();
              txtName.setText(Name.get(0));
              txtPhone.setText(Phone.get(0));
              txtMobile.setText(Mobile.get(0));
              txtAddress.setText(Address.get(0));
              public void Previous()
                   if (index > 0)
                        index--;
                   importContacts();
              public void Next()
                   if(index < temp.size() - 1)
                   index++;
                   importContacts();
              public void clearScreen()
                   txtName.setText("");
                   txtPhone.setText("");
                   txtMobile.setText("");
                   txtAddress.setText("");
              public void writetoFile()
    PrintStream out = new PrintStream("../files/example.buab");
    for
    (int index = 0; index < Name.size(); index++)
    (int index = 0; index < Phone.size(); index++)
    (int index = 0; index < Mobile.size(); index++)
    (int index = 0; index < Address.size(); index++)
    out.println("");
    out.println("");
    out.println(Name.get(index));
    out.println(Phone.get(index));
    out.println(Mobile.get(index));
    out.println(Address.get(index));
    i get an ioexception, must catch or throw, i tried to add catch but it says i must have try, so i added try and it says i cant have catch without try! what am I doing wrong??
    am i doing it right also? should this be in my options? i.e if i press save button?
    also why isn't my next and previous buttons working??
    and one more thing, is there an easier way to show the contents of my file to the jtextfields? (import contacts class)
    thanks

    sorry i did try to do this but didnt see the code bit.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import java.lang.*;
    import java.text.*;
    public class AddressBook extends JFrame implements ActionListener
         FlowLayout leftLayout;
         JFrame winNew;
            JTextField txtName, txtPhone, txtMobile, txtAddress;
            JButton btnImport, btnAdd, btnNext, btnPrevious, btnSave;
            JLabel lblTitle, lblName, lblPhone, lblMobile, lblAddress;
            JPanel pTitle, pName, pPhone, pMobile, pAddress, pButtons;
             ArrayList<String> Name = new ArrayList<String>();
             ArrayList<String> Phone = new ArrayList<String>();
             ArrayList<String> Mobile = new ArrayList<String>();
             ArrayList<String> Address = new ArrayList<String>();
             ArrayList<String> temp = new ArrayList<String>();
             int index = 0;
                  public static void main(String[] args)
                      new AddressBook();
                public AddressBook()
              final int WIDTH = 450;
              final int HEIGHT = 400;
              JFrame win = new JFrame("Address Book");
              win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              leftLayout = new FlowLayout(FlowLayout.LEFT);
              pTitle = new JPanel();
              pTitle.setLayout(new FlowLayout(FlowLayout.CENTER));
              lblTitle = new JLabel("Address Book");
              pTitle.add(lblTitle);
              win.add(pTitle);
              win.setLayout(new GridLayout(6,1));
              win.setSize(WIDTH, HEIGHT);
              win.setBackground(Color.BLUE);
              win.setResizable(false);
              win.setLocationRelativeTo(null);
              pName = new JPanel();
              pName.setLayout(leftLayout);
              lblName = new JLabel("Name: ");
              txtName = new JTextField(20);
              win.add(pName);
              pName.add(lblName);
              pName.add(txtName);
              pPhone = new JPanel();
              pPhone.setLayout(leftLayout);
              lblPhone = new JLabel("Phone: ");
              txtPhone = new JTextField(13);
              win.add(pPhone);
              pPhone.add(lblPhone);
              pPhone.add(txtPhone);
              pMobile = new JPanel();
              pMobile.setLayout(leftLayout);
              lblMobile = new JLabel("Mobile: ");
              txtMobile = new JTextField(14);
              win.add(pMobile);
              pMobile.add(lblMobile);
              pMobile.add(txtMobile);
              pAddress = new JPanel();
              pAddress.setLayout(leftLayout);
              lblAddress = new JLabel("Address: ");
              txtAddress = new JTextField(30);
              win.add(pAddress);
              pAddress.add(lblAddress);
              pAddress.add(txtAddress);
              pButtons = new JPanel();
              btnImport = new JButton("Import");
              pButtons.add(btnImport);
              btnImport.addActionListener(this);
              btnAdd = new JButton("Add");
              pButtons.add(btnAdd);
              btnAdd.addActionListener(this);
              btnPrevious = new JButton("Previous");
              pButtons.add(btnPrevious);
              //btnPrevious.addActionListener(this);
              btnNext = new JButton("Next");
              pButtons.add(btnNext);
              //btnNext.addActionListener(this);
              btnSave = new JButton("Save");
              pButtons.add(btnSave);
              btnSave.addActionListener(this);
              win.add(pButtons);
              win.setVisible(true);
             public void actionPerformed(ActionEvent e)
                      if (e.getSource() == btnImport)
                           importContacts();
                      if (e.getSource() == btnAdd)
                           clearScreen();
                          if (e.getSource() == btnPrevious)
                           Previous();   
                          if (e.getSource() == btnSave)
                         writetoFile();
                         else if (e.getSource() == btnNext)
                           Next();
                  public void importContacts()
                      try
                               BufferedReader infoReader = new BufferedReader(new FileReader("../files/example.buab"));
                               int i = 0;
                               String loadContacts;
                               while ((loadContacts = infoReader.readLine()) !=null)
                                        temp.add(loadContacts);
                                        i++;
                               int a = 0;
                               int b = 0;
                               for (a = 0, b = 0; a < temp.size(); a++, b++)
                                   if (b == 4)
                                            b = 0;
                                   if (b == 0)
                                            Name.add(temp.get(a));   
                                   if (b == 1)
                                            Phone.add(temp.get(a));   
                                   if (b == 2)
                                            Mobile.add(temp.get(a));   
                                   if (b == 3)
                                            Address.add(temp.get(a));   
                          catch (IOException ioe)
                              ioe.printStackTrace();
                      txtName.setText(Name.get(0));
                      txtPhone.setText(Phone.get(0));
                      txtMobile.setText(Mobile.get(0));
                      txtAddress.setText(Address.get(0));
              public void Previous()
                   if (index > 0)
                        index--;
                   importContacts();
              public void Next()
                   if(index < temp.size() - 1)
                   index++;
                   importContacts();
              public void clearScreen()
                   txtName.setText("");
                   txtPhone.setText("");
                   txtMobile.setText("");
                   txtAddress.setText("");
              public void writetoFile()
                           PrintStream out = new PrintStream("../files/example.buab");
                            for
                            (int index = 0; index < Name.size(); index++)
                            (int index = 0; index < Phone.size(); index++)
                            (int index = 0; index < Mobile.size(); index++)
                            (int index = 0; index < Address.size(); index++)
                                   out.println("");
                                   out.println("");
                                   out.println(Name.get(index));
                                   out.println(Phone.get(index));
                                   out.println(Mobile.get(index));
                                   out.println(Address.get(index));
                            out.close();
    }

  • Plzz help me with the output of this code....

    hi all..
    plz check this code and tell me how to select one or more options from this Jlist and write the selected item into a text file....This code does that but the text file shows only one item (i tried using arry but din work) AND text file displays the item which is selected last time the code is interpreted..
    import java.awt.*;
    import java.io.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class mld extends JFrame implements ListSelectionListener, ActionListener
    {private JFrame    myframe = new JFrame("Select File");
                       private DefaultListModel listModel = new DefaultListModel();
         private JList list= new JList(listModel);
         private String selString = "select file name";
         private JButton selButton;
            public mld(){
         super("mld");
         addWindowListener(new WindowAdapter()
       {     public void windowClosing(WindowEvent ev) {dispose();     
                   System.exit(0);
              listModel.addElement("prog1");
    listModel.addElement("prog2");
         listModel.addElement("prog3");
         listModel.addElement("prog4");
         listModel.addElement("prog5");
         listModel.addElement("prog6");
         listModel.addElement("prog7");
         listModel.addElement("prog8");
         listModel.addElement("prog9");
         listModel.addElement("prog10");
         listModel.addElement("prog11");     
    listModel.addElement("prog12");
         list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    list.addListSelectionListener(this);
         JScrollPane listScrollPane = new JScrollPane(list);
         JButton selButton = new JButton(selString);
         selButton.setActionCommand(selString);
         selButton.addActionListener(this);
    //Create a panel that uses FlowLayout (the default).
         JPanel buttonPane = new JPanel();
         buttonPane.add(selButton);
         Container contentPane = getContentPane();
         contentPane.add(listScrollPane, BorderLayout.CENTER);
         contentPane.add(buttonPane, BorderLayout.SOUTH);
         pack();
         show();}
    public void valueChanged(ListSelectionEvent e) {}
    public void actionPerformed(ActionEvent e){
         String tmp = new String(list.getSelectedValue().toString());
    try{
    FileOutputStream fileOut = new FileOutputStream("temp.txt");
    fileOut.write(tmp.getBytes());
    fileOut.close();}
    catch (Exception e1)
    {                e1.printStackTrace();  }
    //*main method//
    public static void main(String s[]) {
         JFrame frame = new mld();
    try {
    Process p = Runtime.getRuntime().exec("notepad temp.txt ");
    p.waitFor();
    Process p1 = Runtime.getRuntime().exec("c:/Program Files/Microsoft Office/Office/outlook.EXE /c ipm.note /m [email protected] /a c:/temp.txt");
    catch(Exception e)
    {                e.printStackTrace();  }
    Thanx in advance
    bharthi

    replace
    FileOutputStream fs = new FileOutputStream("filename");
    with
    FileOutputStream fs = new FileOutputStream("filename",true);

  • Accessing tables from java

    I am creating an inventory system. I have used Java for front-end where i have created forms which display the vendor table, customer table, item table, order table, invoice tbl etc.
    I have created class files for each form that im displaying. i have also made connection to the oracle dbs succesfully. i can access data from the dbs.
    but my problem is,
    1)
    for instance i have created a vendor_master table in oracle with certain constraints like vendor_number can contain only 5 varchar2 characters ,
    eg.
    create table vendor_master
    (v_no varchar2(5) constraint v_no_pk primary key,
    v_name varchar2(25),
    v_add varchar2(15),
    city varchar2(15),
    st varchar2(15),
    zip number(10),
    tel number(11),
    fax number(11));
    now when i want 2 insert any row in the table i should be able 2 insert only "certain" characters of "certain" length depending on the constraints i have set. how do i do tht? coz java does not allow me 2 set the max chars like VB in the properties column
    i have my vendor Master class file here:
    code:--------------------------------------------------------------------------------
    package mainpage;
    import java.io.*;
    import java.io.Serializable;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.String.*;
    import javax.swing.*;
    import javax.swing.JPanel;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.sql.ResultSet;
    import java.util.Vector;
    import oracle.jdbc.driver.OracleDriver;
    import oracle.jdbc.OracleResultSet;
    import java.sql.PreparedStatement;
    public class VendorMaster extends JPanel implements java.io.Serializable
    JFrame venMastFrame = new JFrame("Vendor Master");
    JLabel vennolbl = new JLabel();
    JLabel venNamelbl = new JLabel();
    JLabel venAdd = new JLabel();
    JTextField venAddtxt = new JTextField();
    JTextField venNotxt = new JTextField();
    JTextField venNmtxt = new JTextField();
    JLabel venCitylbl = new JLabel();
    JTextField venCitytxt = new JTextField();
    JLabel venStlbl = new JLabel();
    JTextField venSttxt = new JTextField();
    JLabel venZiplbl = new JLabel();
    JTextField venZiptxt = new JTextField();
    JLabel venTellbl = new JLabel();
    JTextField venTeltxt = new JTextField();
    JLabel venFaxlbl = new JLabel();
    JTextField venFaxtxt = new JTextField();
    JButton vPrevbtn = new JButton();
    JButton vNxtbtn = new JButton();
    JButton vExitbtn = new JButton();
    JButton vNewbtn = new JButton();
    JButton vDelbtn = new JButton();
    JButton vUpdtbtn = new JButton();
    JButton vSavebtn = new JButton();
    int currentIndex = 0;
    int totalRecords = 0;
    private Vector vendorMasterRecords = new Vector();
    public VendorMaster()
    venMastFrame.setSize(850,760);
    venMastFrame.setVisible(true);
    //venMastFrame.show();
    try
    jbInit();
    } catch (Exception e)
    e.printStackTrace();
    } // end of constructor
    private void jbInit() throws Exception
    Connection myConnection = DataManager.createConnection();
    vendorMasterRecords = loadVendorMasterRecords(myConnection);
    VendorMasterBean vmBean = null;
    venMastFrame.getContentPane().setLayout(null);
    if(vendorMasterRecords != null)
    {                 vmBean = (VendorMasterBean)vendorMasterRecords.elementAt(0);
    totalRecords = vendorMasterRecords.size();
    currentIndex = 0;
    if(vmBean == null)
    vmBean = new VendorMasterBean();
    venNamelbl.setText("Vendor Name:");
    venNamelbl.setBounds(new Rectangle(22, 87, 89, 23));
    venNmtxt.setBounds(new Rectangle(153, 81, 224, 22));
    venNmtxt.setEnabled(false);
    venNmtxt.setText(vmBean.getVendorName());
    venAdd.setText("Address:");
    venAdd.setBounds(new Rectangle(25, 130, 113, 31));
    venAddtxt.setBounds(new Rectangle(152, 126, 201, 22));
    venAddtxt.setEnabled(false);
    venAddtxt.setText(vmBean.getAddress());
    vennolbl.setText("Vendor No:");
    vennolbl.setBounds(new Rectangle(23, 41, 73, 22));
    venNotxt.setBounds(new Rectangle(155, 38, 108, 22));
    venNotxt.setEnabled(false);
    venNotxt.setText(vmBean.getVendorNumber());
    venCitylbl.setText("City:");
    venCitylbl.setBounds(new Rectangle(25, 175, 61, 29));
    venCitytxt.setBounds(new Rectangle(153, 172, 156, 24));
    venCitytxt.setEnabled(false);
    venCitytxt.setText(vmBean.getCity());
    venStlbl.setText("State:");
    venStlbl.setBounds(new Rectangle(25, 225, 64, 32));
    venSttxt.setBounds(new Rectangle(152, 223, 158, 24));
    venSttxt.setEnabled(false);
    venSttxt.setText(vmBean.getState());
    venZiplbl.setText("Zip:");
    venZiplbl.setBounds(new Rectangle(24, 275, 58, 24));
    venZiptxt.setBounds(new Rectangle(150, 272, 108, 24));
    venZiptxt.setEnabled(false);
    venZiptxt.setText(vmBean.getZipcode());
    venTellbl.setText("Telephone No:");
    venTellbl.setBounds(new Rectangle(25, 323, 106, 26));
    venTeltxt.setBounds(new Rectangle(149, 326, 108, 26));
    venTeltxt.setEnabled(false);
    venTeltxt.setText(vmBean.getTelephone());
    venFaxlbl.setText("Fax No:");
    venFaxlbl.setBounds(new Rectangle(27, 375, 97, 26));
    venFaxtxt.setBounds(new Rectangle(149, 375, 107, 26));
    venFaxtxt.setEnabled(false);
    venFaxtxt.setText(vmBean.getFax());
    /* code for buttons */
    vExitbtn.setBounds(new Rectangle(681, 457, 111, 29));
    vExitbtn.setText("EXIT");
    vExitbtn.addKeyListener(new VendorMaster_vExitbtn_keyAdapter(this));
    vExitbtn.addActionListener(new VendorMaster_vExitbtn_actionAdapter(this));
    vPrevbtn.setText("PREVIOUS");
    vPrevbtn.addKeyListener(new VendorMaster_vPrevbtn_keyAdapter(this));
    vPrevbtn.addActionListener(new VendorMaster_vPrevbtn_actionAdapter(this));
    vPrevbtn.setBounds(new Rectangle(14, 457, 110, 29));
    vPrevbtn.setEnabled(false);
    vNxtbtn.setText("NEXT");
    vNxtbtn.addKeyListener(new VendorMaster_vNxtbtn_keyAdapter(this));
    vNxtbtn.addActionListener(new VendorMaster_vNxtbtn_actionAdapter(this));
    vNxtbtn.setBounds(new Rectangle(124, 457, 111, 29));
    vNewbtn.setText("NEW");
    vNewbtn.setBounds(new Rectangle(235, 457, 111, 29));
    vNewbtn.setActionCommand("NEW");
    vNewbtn.addActionListener(new VendorMaster_vNewbtn_actionAdapter(this));
    vNewbtn.addKeyListener(new VendorMaster_vNewbtn_keyAdapter(this));
    vDelbtn.setText("DELETE");
    vDelbtn.setBounds(new Rectangle(346, 457, 111, 29));
    vDelbtn.setHorizontalAlignment(SwingConstants.CENTER);
    vDelbtn.addActionListener(new VendorMaster_vDelbtn_actionAdapter(this));
    vDelbtn.addKeyListener(new VendorMaster_vDelbtn_keyAdapter(this));
    vUpdtbtn.setText("UPDATE");
    vUpdtbtn.addActionListener(new VendorMaster_vUpdtbtn_actionAdapter(this));
    vUpdtbtn.setBounds(new Rectangle(457, 457, 113, 29));
    vUpdtbtn.setMaximumSize(new Dimension(71, 25));
    vUpdtbtn.setMinimumSize(new Dimension(71, 25));
    vUpdtbtn.setPreferredSize(new Dimension(71, 25));
    /* Add all the txtboxes, lbls and buttons to the frame */
    vSavebtn.setBounds(new Rectangle(570, 457, 111, 29));
    vSavebtn.setText("SAVE");
    vSavebtn.addActionListener(new VendorMaster_vSavebtn_actionAdapter(this));
    venMastFrame.getContentPane().add(vennolbl, null);
    venMastFrame.getContentPane().add(venNotxt, null);
    venMastFrame.getContentPane().add(venNamelbl, null);
    venMastFrame.getContentPane().add(venNmtxt, null);
    venMastFrame.getContentPane().add(venAdd, null);
    venMastFrame.getContentPane().add(venAddtxt, null);
    venMastFrame.getContentPane().add(venCitylbl, null);
    venMastFrame.getContentPane().add(venCitytxt, null);
    venMastFrame.getContentPane().add(venStlbl, null);
    venMastFrame.getContentPane().add(venSttxt, null);
    venMastFrame.getContentPane().add(venZiplbl, null);
    venMastFrame.getContentPane().add(venZiptxt, null);
    venMastFrame.getContentPane().add(venTellbl, null);
    venMastFrame.getContentPane().add(venTeltxt, null);
    venMastFrame.getContentPane().add(venFaxlbl, null);
    venMastFrame.getContentPane().add(venFaxtxt, null);
    venMastFrame.getContentPane().add(vPrevbtn, null);
    venMastFrame.getContentPane().add(vNxtbtn, null);
    venMastFrame.getContentPane().add(vNewbtn, null);
    venMastFrame.getContentPane().add(vDelbtn, null);
    venMastFrame.getContentPane().add(vUpdtbtn, null);
    venMastFrame.getContentPane().add(vSavebtn, null);
    venMastFrame.getContentPane().add(vExitbtn, null);
    } // end of jbinit
    public static void main(String[] args)
    VendorMaster vendorMaster1 = new VendorMaster();
    } //end of main
    /* this is where the data will be retrieved from the dbs */
    protected Vector loadVendorMasterRecords(Connection connection)
    //Connection connection = null;
    Vector masterRecords = new Vector();
    // From database getting values
    try
    //connection = connectionManager.getConnection();
    Statement stmt = connection.createStatement();
    String queryall = "Select * from vendor_master order by v_no";
    ResultSet rs = stmt.executeQuery(queryall);
    while (rs.next())
    String vendorNumber = rs.getString("v_no");
    String vendorName = rs.getString("v_name");
    String address = rs.getString("v_add");
    String city = rs.getString("city");
    String state = rs.getString("st");
    String zipCode = rs.getString("zip");
    String telephone = rs.getString("tel");
    String fax = rs.getString("fax");
    VendorMasterBean vendorMasterBean = new VendorMasterBean(vendorNumber,
    vendorName,
    address,
    city,
    state,
    zipCode,
    telephone,
    fax);
    /* data retrieved from the vendormasterbean is then inserted in vector*/
    masterRecords.addElement(vendorMasterBean);
    } // end of while
    } catch (Exception e) // end of try & start of catch
    e.printStackTrace();
    } // end of catch
    finally
    if(connection != null)
    DataManager.freeConnection(connection);
    return masterRecords; /* the data stored in
    masterRecords is passed 2 vendormasterRecords*/
    } // finally ends here
    } // end of loadvendorMasterrecords
    /*example- when previous button is pressed then an event is triggered
    captured by the key listener and then actionPerformed method is called
    which in turn calls the getPreviousRecord*/
    /* to insert records */
    protected void addVendorMasterRecord(VendorMasterBean vmBean )
    Connection connection = null;
    Vector masterRecords = new Vector();
    // first check whether all the textboxes are empty
    // also check whether there is already a record
    //existing with the same v_no
    // From database getting values
    try
    connection = DataManager.createConnection();
    PreparedStatement newRecord = connection.prepareStatement("insert into vendor_master values(?,?,?,?,?,?,?,?)");
    newRecord.setString(1,vmBean.getVendorNumber());
    newRecord.setString(2, vmBean.getVendorName());
    newRecord.setString(3, vmBean.getAddress());
    newRecord.setString(4, vmBean.getCity());
    newRecord.setString(5, vmBean.getState());
    newRecord.setString(6, vmBean.getZipcode());
    newRecord.setString(7, vmBean.getTelephone());
    newRecord.setString(8, vmBean.getFax());
    newRecord.executeUpdate();
    // Insert statement
    // PreparedStatement pStmt = ....;
    // The assign each value in the vmBean to the pStmt
    // and finally execute the pStmt
    } catch (Exception e) // end of try and begin of catch
    e.printStackTrace();
    } // end of catch
    finally
    if(connection != null)
    DataManager.freeConnection(connection);
    }// end of if
    } // end of finally
    } // end of addVendorMasterRecord
    void vNewbtn_actionPerformed(ActionEvent e)
    /* First empty all the textboxes */
    venNotxt.setText(" ");
    venNmtxt.setText(" ");
    venAddtxt.setText(" ");
    venCitytxt.setText(" ");
    venSttxt.setText(" ");
    venZiptxt.setText(" ");
    venTeltxt.setText(" ");
    venFaxtxt.setText(" ");
    venNotxt.setEnabled(true);
    venNmtxt.setEnabled(true);
    venAddtxt.setEnabled(true);
    venCitytxt.setEnabled(true);
    venSttxt.setEnabled(true);
    venZiptxt.setEnabled(true);
    venTeltxt.setEnabled(true);
    venFaxtxt.setEnabled(true);
    vPrevbtn.setEnabled(false);
    vNxtbtn.setEnabled(false);
    void vNewbtn_keyPressed(KeyEvent e)
    /* to delete records */
    protected void removeVendorMasterRecord(VendorMasterBean vmBean )
    Connection connection = null;
    Vector masterRecords = new Vector();
    // From database getting values
    try
    connection = DataManager.createConnection();
    PreparedStatement deleteRecord = connection.prepareStatement("delete from vendor_master where v_no = ?");
    deleteRecord.setString(1, vmBean.getVendorNumber());
    deleteRecord.executeUpdate();
    // Delete statement for where condition pass the vendor number as parameter
    //"delete from vendor_master where v_no = ?"
    //PreparedStatement pStmt = ....;
    // The assign v_no in the vmBean to the pStmt
    // and finally execute the pStmt
    } catch (Exception e)
    e.printStackTrace();
    finally
    // After executing this new record should be removed from the Vector of results.
    // uncomment this
    if(connection != null){
    DataManager.freeConnection(connection);
    } // end of finally
    } // end of removeVendorMasterRecord
    void vDelbtn_actionPerformed(ActionEvent e)
    String vendorNumber = venNotxt.getText();
    String vendorName = venNmtxt.getText();
    String address = venAddtxt.getText();
    String city = venCitytxt.getText();
    String state = venSttxt.getText();
    String zipCode = venZiptxt.getText();
    String telephone = venTeltxt.getText();
    String fax = venFaxtxt.getText();
    VendorMasterBean vmBean = new VendorMasterBean(vendorNumber,vendorName, address, city, state, zipCode, telephone, fax);
    removeVendorMasterRecord(vmBean);
    void vDelbtn_keyPressed(KeyEvent e)
    /* To get next record */
    protected VendorMasterBean getNextRecord()
    VendorMasterBean vmBean = new VendorMasterBean();
    if(currentIndex < totalRecords)
    vmBean =(VendorMasterBean)vendorMasterRecords.elementAt(++currentIndex);
    if(currentIndex == (totalRecords-1) )
    // reached last, so disable the Next button
    vNxtbtn.setEnabled(false);
    // enable the Previous
    vPrevbtn.setEnabled(true);
    } // end of if stmt
    } // end of outer if stmt
    return vmBean;
    } // end of getnextrecord
    void vNxtbtn_keyPressed(KeyEvent e)
    void vNxtbtn_actionPerformed(ActionEvent e)
    VendorMasterBean vmBean = getNextRecord();
    venNotxt.setText(vmBean.getVendorNumber());
    venNmtxt.setText(vmBean.getVendorName());
    venAddtxt.setText(vmBean.getAddress());
    venCitytxt.setText(vmBean.getCity());
    venSttxt.setText(vmBean.getState());
    venZiptxt.setText(vmBean.getZipcode());
    venTeltxt.setText(vmBean.getTelephone());
    venFaxtxt.setText(vmBean.getFax());
    /* to get previous record */
    protected VendorMasterBean getPreviousRecord()
    VendorMasterBean vmBean = new VendorMasterBean();
    if(currentIndex > 0)
    vmBean =(VendorMasterBean)vendorMasterRecords.elementAt(--currentIndex);
    if(currentIndex == 0)
    // reached first so disable the Previous button
    vPrevbtn.setEnabled(false);
    // enable the Next
    vNxtbtn.setEnabled(true);
    } // end of inner if stmt
    } // end of outer if stmt
    return vmBean;
    } // end of previousrecord
    void vPrevbtn_actionPerformed(ActionEvent e)
    VendorMasterBean vmBean = getPreviousRecord();
    venNmtxt.setText(vmBean.getVendorName());
    venAddtxt.setText(vmBean.getAddress());
    venNotxt.setText(vmBean.getVendorNumber());
    venCitytxt.setText(vmBean.getCity());
    venSttxt.setText(vmBean.getState());
    venZiptxt.setText(vmBean.getZipcode());
    venTeltxt.setText(vmBean.getTelephone());
    venFaxtxt.setText(vmBean.getFax());
    void vPrevbtn_keyPressed(KeyEvent e)
    void vUpdtbtn_actionPerformed(ActionEvent e)
    /* when the update button is pressed , only the v_no is disabled
    vPrevbtn.setEnabled(false);
    vNxtbtn.setEnabled(false);
    venNmtxt.setEnabled(true);
    venAddtxt.setEnabled(true);
    venCitytxt.setEnabled(true);
    venSttxt.setEnabled(true);
    venZiptxt.setEnabled(true);
    venTeltxt.setEnabled(true);
    venFaxtxt.setEnabled(true);
    //then the user should press the save button
    void vExitbtn_actionPerformed(ActionEvent e)
    venMastFrame.setDefaultCloseOperation(venMastFrame.EXIT_ON_CLOSE);
    void vExitbtn_keyPressed(KeyEvent e)
    void vSavebtn_actionPerformed(ActionEvent e)
    String vendorNumber = venNotxt.getText();
    String vendorName = venNmtxt.getText();
    String address = venAddtxt.getText();
    String city = venCitytxt.getText();
    String state = venSttxt.getText();
    String zipCode = venZiptxt.getText();
    String telephone = venTeltxt.getText();
    String fax = venFaxtxt.getText();
    VendorMasterBean vmBean = new VendorMasterBean(vendorNumber, vendorName,address, city, state, zipCode, telephone, fax);
    addVendorMasterRecord(vmBean);
    } // end of vSavebtn_actionPerformed
    } // end of class vendormaster
    //Adapter classes
    class VendorMaster_vNxtbtn_actionAdapter implements java.awt.event.ActionListener
    VendorMaster adaptee;
    VendorMaster_vNxtbtn_actionAdapter(VendorMaster adaptee)
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e)
    adaptee.vNxtbtn_actionPerformed(e);
    class VendorMaster_vNxtbtn_keyAdapter extends java.awt.event.KeyAdapter
    VendorMaster adaptee;
    VendorMaster_vNxtbtn_keyAdapter(VendorMaster adaptee)
    this.adaptee = adaptee;
    public void keyPressed(KeyEvent e)
    adaptee.vNxtbtn_keyPressed(e);
    class VendorMaster_vPrevbtn_actionAdapter implements java.awt.event.ActionListener
    VendorMaster adaptee;
    VendorMaster_vPrevbtn_actionAdapter(VendorMaster adaptee)
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e)
    adaptee.vPrevbtn_actionPerformed(e);
    class VendorMaster_vPrevbtn_keyAdapter extends java.awt.event.KeyAdapter
    VendorMaster adaptee;
    VendorMaster_vPrevbtn_keyAdapter(VendorMaster adaptee)
    this.adaptee = adaptee;
    public void keyPressed(KeyEvent e)
    adaptee.vPrevbtn_keyPressed(e);
    class VendorMaster_vExitbtn_actionAdapter implements java.awt.event.ActionListener
    VendorMaster adaptee;
    VendorMaster_vExitbtn_actionAdapter(VendorMaster adaptee)
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e)
    adaptee.vExitbtn_actionPerformed(e);
    class VendorMaster_vExitbtn_keyAdapter extends java.awt.event.KeyAdapter
    VendorMaster adaptee;
    VendorMaster_vExitbtn_keyAdapter(VendorMaster adaptee)
    this.adaptee = adaptee;
    public void keyPressed(KeyEvent e)
    adaptee.vExitbtn_keyPressed(e);
    class VendorMaster_vNewbtn_actionAdapter implements java.awt.event.ActionListener
    VendorMaster adaptee;
    VendorMaster_vNewbtn_actionAdapter(VendorMaster adaptee)
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e)
    adaptee.vNewbtn_actionPerformed(e);
    class VendorMaster_vNewbtn_keyAdapter extends java.awt.event.KeyAdapter
    VendorMaster adaptee;
    VendorMaster_vNewbtn_keyAdapter(VendorMaster adaptee)
    this.adaptee = adaptee;
    public void keyPressed(KeyEvent e)
    adaptee.vNewbtn_keyPressed(e);
    class VendorMaster_vDelbtn_actionAdapter implements java.awt.event.ActionListener
    VendorMaster adaptee;
    VendorMaster_vDelbtn_actionAdapter(VendorMaster adaptee)
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e)
    adaptee.vDelbtn_actionPerformed(e);
    class VendorMaster_vDelbtn_keyAdapter extends java.awt.event.KeyAdapter
    VendorMaster adaptee;
    VendorMaster_vDelbtn_keyAdapter(VendorMaster adaptee)
    this.adaptee = adaptee;
    public void keyPressed(KeyEvent e)
    adaptee.vDelbtn_keyPressed(e);
    class VendorMaster_vUpdtbtn_actionAdapter implements java.awt.event.ActionListener {
    VendorMaster adaptee;
    VendorMaster_vUpdtbtn_actionAdapter(VendorMaster adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.vUpdtbtn_actionPerformed(e);
    class VendorMaster_vSavebtn_actionAdapter implements java.awt.event.ActionListener {
    VendorMaster adaptee;
    VendorMaster_vSavebtn_actionAdapter(VendorMaster adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.vSavebtn_actionPerformed(e);
    the following code is the vendorMasterBean class file- this file helps 2 assign data to the various textboxes.
    code:--------------------------------------------------------------------------------
    package mainpage;
    public class VendorMasterBean
    private String vendorNumber;
    private String vendorName;
    private String address;
    private String city;
    private String state;
    private String zipcode;
    private String telephone;
    private String fax;
    public int Mandatory_Value;
    public VendorMasterBean()
    } // end of constructor
    public VendorMasterBean(String vendorNumber,String vendorName,String address,String city,String state,String zipcode,String telephone,String fax)
    setVendorNumber(vendorNumber);
    setVendorName(vendorName);
    setAddress(address);
    setCity(city);
    setState(state);
    setZipcode(zipcode);
    setTelephone(telephone);
    setFax(fax);
    /* Set Method */
    public void setVendorNumber(String vendorNumber)
    try
    if ( (vendorNumber == null) || (vendorNumber.length() <= 0) || (vendorNumber.length() > 5))
    throw new ValidateException(ValidateException.MANDATORY_VALUE,
    "Vendor Number");
    } // end of if stmt
    else {
    this.vendorNumber = vendorNumber;
    } // end of else
    catch(Exception e)
    e.printStackTrace();
    } // end of setVendorNumber
    public void setVendorName(String vendorName)
    try
    if((vendorName == null) || (vendorName.length() <=0 && vendorName.length() > 25))
    throw new ValidateException(ValidateException.MANDATORY_VALUE,
    "Vendor Name");
    }// end of if
    else
    this.vendorName = vendorName;
    } // end of else
    } // end of try
    catch(Exception e)
    e.printStackTrace();
    }// end of set method
    public void setAddress(String address)
    try
    if((address == null) ||(address.length() <=0 && address.length()>15))
    throw new ValidateException(ValidateException.MANDATORY_VALUE,
    "Address");
    else
    this.address = address;
    catch(Exception e)
    e.printStackTrace();
    public void setCity(String city)
    try
    if((city == null) ||(city.length()<=0 && city.length() > 15))
    throw new ValidateException(ValidateException.MANDATORY_VALUE,
    "City");
    else
    this.city = city;
    catch(Exception e)
    e.printStackTrace();
    public void setState(String state)
    try
    if((state == null) || (state.length()<=0 && state.length() >15))
    throw new ValidateException(ValidateException.MANDATORY_VALUE,
    "State");
    else
    this.state = state;
    catch(Exception e)
    e.printStackTrace();
    public void setZipcode(String zipcode)
    try
    if((zipcode==null) ||(zipcode.length()<=0 && zipcode.length() > 10))
    throw new ValidateException(ValidateException.MANDATORY_VALUE,
    "Zipcode");
    else
    this.zipcode = zipcode;
    catch(Exception e)
    e.printStackTrace();
    public void setTelephone(String telephone)
    try
    if((telephone==null) || (telephone.length() <= 0 && telephone.length()> 7))
    throw new ValidateException(ValidateException.MANDATORY_VALUE,
    "Telephone");
    else
    this.telephone = telephone;
    catch(Exception e)
    e.printStackTrace();
    public void setFax(String fax)
    try
    if((fax == null) ||(fax.length()<=0 && fax.length() > 7))
    throw new ValidateException(ValidateException.MANDATORY_VALUE,
    "Fax");
    else
    this.fax = fax;
    catch(Exception e)
    e.printStackTrace();
    /* Get method */
    public String getVendorNumber()
    return vendorNumber;
    public String getVendorName()
    return vendorName;
    public String getAddress()
    return address;
    public String getCity()
    return city;
    public String getState()
    return state;
    public String getZipcode()
    return zipcode;
    public String getTelephone()
    return telephone;
    public String getFax()
    return fax;
    /* end of get method*/
    } // end of class
    2) the 2nd error is in the save button method , everytme i try 2 save the inserted record it gives me an error.
    in case u need my mainpage.java, here it is
    code:--------------------------------------------------------------------------------
    package mainpage;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JPanel;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    //import java.sql.Statement;
    //import java.sql.ResultSet;
    import oracle.jdbc.driver.OracleDriver;
    import oracle.jdbc.OracleResultSet;
    public class MainPage extends JFrame implements ActionListener
    public static String title = "Warehouse Management System";
    JFrame frame = new JFrame();
    JMenuBar menuBar = new JMenuBar();
    JMenu viewMenu = new JMenu("VIEW");
    JMenuItem vendorItem = new JMenuItem("Vendor Master");
    JMenuItem custItem= new JMenuItem("Customer Master");
    JMenuItem salesrepItem= new JMenuItem("Sales Rep Master");
    JMenuItem itemmastItem= new JMenuItem("Item Master");
    JMenuItem orderItem= new JMenuItem("Order Master");
    JMenuItem invoiceItem = new JMenuItem("Invoice Master");
    JMenuItem payItem= new JMenuItem("Payment Master");
    JMenu transactionMenu = new JMenu("EDIT");
    JMenuItem veneditItem = new JMenuItem("Vendor");
    JMenuItem custeditItem = new JMenuItem("Customer");
    JMenuItem saleItem = new JMenuItem("Rep Information");
    JMenuItem itmeditItem= new JMenuItem("Item");
    JMenuItem ordeditItem= new JMenuItem("Order");
    JMenuItem inveditItem = new JMenuItem("Invoice");
    JMenuItem payeditItem = new JMenuItem("Payment");
    JMenu exitMenu = new JMenu("EXIT

    2 parts to this
    Limit characters in jtextfield using a custom document
    http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#customdocument
    Specify a custom editor (jtextfield) for jtable (or column)
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#validtext

  • How to change the length of a JTextField?

    Hello,
    I am trying to shorten the length of a JTextField with the following code :
    // up to this point, getColumns() returns a value of 35.
    jTextField1.setColumns(20);
    (jTextField1.getParent()).invalidate();
    (jTextField1.getParent()).validate();
    When I ran this code, it does not change the length of the text field at all.
    I wonder if I am writing my code correctly or is there a better/more correct
    way to do this?
    Thank you for your help.
    Akino.

    Packing a frame works:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ShortText implements ActionListener {
        JTextField txtF;
        JFrame frame;
        public ShortText() {
         frame = new JFrame();
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         txtF = new JTextField(30);
         JButton btn = new JButton("Shorten");
         btn.addActionListener(this);
         frame.add(txtF, BorderLayout.NORTH);
         frame.add(btn, BorderLayout.SOUTH);
         frame.pack();
         frame.setVisible(true);
        public static void main(String[] args) {
         new ShortText();
        public void actionPerformed(ActionEvent e) {
         System.out.println("Old Columns: " + txtF.getColumns());
         txtF.setColumns(20);
         frame.pack();
         System.out.println("New Columns: " + txtF.getColumns());
    }

  • Can any one tell what is the problem in this code?

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.geom.*;
    import java.util.*;
    public class AppletTest2 extends JApplet implements ActionListener,MouseMotionListener,WindowListener{
    JFrame fr = new JFrame("Visual Tool -- Work Flow Editor");
         JPanel panel1 = new JPanel();
         JPanel panel2 = new JPanel();
         JButton sButton = new JButton("Source");
         JButton rButton = new JButton("Redirection");
         JButton dButton = new JButton("Destination");
         JButton connect = new JButton("Connect");
         BasicStroke stroke = new BasicStroke(2.0f);
         int flag = 1 ;
         Vector lines = new Vector();
         JButton sBut,rBut,dBut;
    int x1 = 0 ;
         int y1 = 0 ;
         int x2 = 0 ;
         int y2 = 0;
         int x3 = 0;
         int y3 = 0;
         int i=0;
         int j=0;
         int k=0;
         int l = 100;
    int b = 50;
    public void init(){
              /*********Frame ******************/
    fr.getContentPane().setLayout(new BorderLayout());
         fr.setSize(700,500);
              fr.getContentPane().add(panel1,BorderLayout.CENTER);
              fr.getContentPane().add(panel2,BorderLayout.SOUTH);
              fr.addWindowListener(this);
              /*****************PANEL 1*********************/
              panel1.setLayout(null);
    panel1.setBounds(new Rectangle(0,0,400,400));
              panel1.setBackground(new Color(105,105,205));
    /************************PANEL 2 *************/
              panel2.setLayout(new FlowLayout());
              panel2.setBackground(new Color(105,205,159));
              panel2.add(sButton);
              panel2.add(rButton);
              panel2.add(dButton);
              panel2.add(connect);
              connect.setToolTipText("Use this button after selecting From and To position to connect");
              /***************************LISTENER********************/
    sButton.addActionListener(this);
              rButton.addActionListener(this);
              dButton.addActionListener(this);
              connect.addActionListener(this);
              fr.setVisible(true);     
              fr.setResizable(false);
         } // init clse
    /************************** START METHOD **********************************************/
              public void start(){                                 
                   System.out.println("inside start");
                   paint(panel1.getGraphics());
    /*******************************APPLET METHODS **************************************************/
              public void stop(){}
              public void destroy(){}
    /******************************MOUSE MOTION LISTENERS METHOD*************************************/
              public void mouseMoved(MouseEvent e){System.out.println("moved");}
              public void mouseDragged(MouseEvent e){System.out.println("dragged");}
    /***************************************ACTION EVENT IMPLEMENTAION *******************************/
         public void actionPerformed(ActionEvent e){
              if (e.getSource().equals(sButton)){          
              sourceObject("Source Object");          
              else if (e.getSource().equals(rButton)){          
              redirectionObject("Redirection");
              i = i+1;
              else if (e.getSource().equals(dButton)){
              destinationObject("Destination");
                   j= j+1;
              else if (e.getSource().equals(connect)){
                   System.out.println("am inside connect");                
                   paint(panel1.getGraphics());               
    else if(e.getSource().equals(sBut)){
                   System.out.println("am s button");                
                   x1 = sBut.getX() + l;
                   y1 = sBut.getY() + (b/2);
              else if(e.getSource().equals(rBut)){
                   System.out.println("am r button");               
                   x2 = rBut.getX() ;
                   y2 = rBut.getY()+ b/2;
                   System.out.println("x2 : " + x2 + "y2 :" +y2 );
              else if(e.getSource().equals(dBut)){
                   System.out.println("am d button");                
                   x3 = dBut.getX();
    y3 = dBut.getY()+ b/2;
    } // action close
    /**********************Main **********************************/     
         public static void main(String args[]){
         JApplet at = new AppletTest2();
              at.init();
              at.start();
    /********************my methods starts here *******************/
         public void sourceObject(String name){     
    sBut = new JButton(name);
         panel1.add(sBut);
         sBut.setBounds(new Rectangle(20,208,l,b));     
         sBut.addActionListener(this);
    System.out.println("am inside the source object") ;
         public void redirectionObject(String name){     
         rBut = new JButton(name);
         panel1.add(rBut);
         rBut.setBounds(new Rectangle(290,208,l,b));     
    rBut.addActionListener(this);
    System.out.println("am inside the redirection :" + j) ;
    public void destinationObject(String name){     
         dBut = new JButton(name);
         panel1.add(dBut);     
    System.out.println("am inside the destination object") ;
    if (j == 0)
                   dBut.setBounds(new Rectangle(566,60,l,b));                    
                   System.out.println("am inside the destination:" + j) ;
                   } else if (j == 2)
                        dBut.setBounds(new Rectangle(566,208,l,b));     
                        System.out.println("am inside the destination :" + j) ;
                   } else if (j == 1)
    dBut.setBounds(new Rectangle(566,350,l,b));     
                        System.out.println("am inside the destination :" + j) ;
    dBut.addActionListener(this);
    /* public void connectObject(Object obj1,Object obj2){
    System.out.println("nothing");
    /************************************* PAINT **************************/
    public void paint(Graphics g){
         System.out.println("inside paint");
         Graphics2D g2 = (Graphics2D) g;
         g2.setStroke(stroke);
    if(flag == 1){
    System.out.println("inside flag");
    int np = lines.size();
                        System.out.println(np);
                             for (int I=0; I < np; I++) {                       
         Rectangle p = (Rectangle)lines.elementAt(I);
                             System.out.println("width" + p.width);
                             g2.setColor(Color.red);
                             g2.drawLine(p.x,p.y,p.width,p.height);
                             System.out.println(p.x +"" +""+ p.y + ""+ ""+ p.width+ "" + ""+ p.height);
    flag = -1;
    }else if(flag == -1){
         if(x1 != 0 && y1 != 0 && x2 != 0 && y2 != 0 ){
    // Graphics2D g2 = (Graphics2D) g;
         // g2.setStroke(stroke);
    g2.setColor(Color.red);
         g2.drawLine(x1,y1,x2,y2);
         lines.addElement(new Rectangle(x1,y1,x2,y2));     
         x1 = 0 ;y1 = 0 ;
         x2 = 0 ;y2 = 0 ;
    //     g2.drawLine(100,100,200,200);
    else if (x2 != 0 && y2 != 0 && x3 != 0 && y3 != 0 )
              // Graphics2D g2 = (Graphics2D) g;
                   // g2.setStroke(stroke);
              g2.setColor(Color.green);
                        g2.drawLine(x2,y2,x3,y3);
                        lines.addElement(new Rectangle(x2,y2,x3,y3));
                        x2 = 0; y2 = 0 ;
                        x3 = 0 ; y3 = 0 ;                    
    else if (x1 != 0 && y1 != 0 && x3 != 0 && y3 != 0)
                   //     Graphics2D g2 = (Graphics2D) g;
                   // g2.setStroke(stroke);
                   g2.setColor(Color.red);
                   g2.drawLine(x1,y1,x3,y3);
                        lines.addElement(new Rectangle(x1,y1,x3,y3));                              
                        x1 = 0; y1 = 0 ;
                        x3 = 0 ; y3 = 0 ;                    
    // repaint();
    /********************************WINDOW LISTENER IMPLEMENTATION *****************************/
    public void windowActivated(WindowEvent we) { 
              flag = 1;
              paint(panel1.getGraphics());
    System.out.println("windowActivated -- event 1");
         //start();               
         public void windowClosed(WindowEvent we) {
                                                                System.out.println("windowClosed -- 2");
         public void windowClosing(WindowEvent we){
                                                                System.out.println("windowClosing -- 3");
    public void windowDeactivated(WindowEvent we) {
                                                                     System.out.println("windowDeactivated -- 4");
    public void windowDeiconified(WindowEvent we) {
                                                                     flag = 1;
                                                                     System.out.println("windowDeiconified -- 5");          
                                                                     paint(panel1.getGraphics());           
    public void windowIconified(WindowEvent we) {           
                                                           System.out.println("windowIconified -- 6");
                                                           //paint(panel1.getGraphics());
    public void windowOpened(WindowEvent we) {             
                                                      //     flag = 1;
                                                      //     paint(panel1.getGraphics());
                                                           System.out.println("windowopened -- 7");     
    The problem am facing here is that when i minimize the frame and maximize , my old lines are getting disappared.
    For avoiding that i am storing the old coordinates and
    try to redraw , when maximize.
    but the lines are coming for flash of second and disappearing once again ?
    can any one help?
    thanks all

    Very interestingly the same code is repainting in
    Linux SUSE,jdk1.3.
    but not in WINNT , jdk 1.3
    Any reason ?
    Is the swing 100 % platform independenet ?????
    Does swing also uses native thread ???

Maybe you are looking for

  • What is different between asp and jsp, which is better and why

    hi, i would like to know which script language is better (ASP or JSP). if you can give me a detail comparison. Thank in advance zhe

  • My Mac suddenly stopped playing through my external speakers which are fine and working well with other devices.

    My Mac suddenly stopped playing through my external speakers which are fine and working well with other devices.

  • Solaris 8 0 FTP

    A windows applications does a FTP get from a folder on a Sun box with Solaris 8. It works fine. Upon installing the 8 patches (approx 150), the FTP connections now keeps dropping. On restarting the NT application,a new FTP connection is established,b

  • Auto code generate

    hi,        i am using following query for auto code generation group wise declare @temp as char(20) IF $[OITM.ItmsGrpCod] = 101 BEGIN set @temp=(select isnull(max(right(ItemCode,6)),0) + 1 from OITM where (ItmsGrpCod= 101) and (len(ItemCode)=7)) set

  • Parsing Exception

    Hi all: I am trying to store binary data in UUencoded format in an XML document. I have defined this data element (filecontent) as #CDATA in the dtd file, since defining it as #PCDATA creates a whole bunch of exceptions during parsing of the UUencode