FocusEvent of a JTextField object

Hi,
I'm new to event handling in Java GUI development, and I'm just wondering how I can achieve the following effect in my GUI:
Say I have a text field, and and I input some value (e.g. 3), and when I move the cursor away from this field, how can I retrieve this value 3 from it?
I understand you could use ActionEvent to obtain the text inside the field when you press 'Enter', but this is not what I intend to do.
Many thanks.

Add a MouseListener to the method and retrieve the value in the mouseExited() method.

Similar Messages

  • JTextField object requestFocusInWindow() method

    I am trying to set the focus on a JTextField object with the line of code below.
    I am able to set the focus on this object in Java 1.4.2 up to Java 1.6 (true is returned).
    In JSE 1.6.0_11 I can't set the focus, a value of false is returned.
    Why does this happen?
    txtLoadDescription.requestFocusInWindow();

    The method only works when the frame is visible.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • How to disable the tab focusing for a JTextField object because those ...

    Hi All,
    Here I need some help. I want to disable the tab focusing( tab index) for a JTextField objects because those objects are set as setEditable(false). Also can u tell me about how to change the tab index orders for JTextFields.
    Many thanks,
    Vijaycanaan.

    I want to disable the tab focusing( tab index) for a JTextField objectsLook through the API and find methods with the word "focus" in the method name.
    Also can u tell me about how to change the tab index orders for JTextFields."How to Use the Focus Sub System":
    http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html

  • Add mouselisteners to an array of JTextField objects

    Hi. I am writing a program to emulate a calendar and I though I would do it for each day I would have a JTextField hold the contents of the field. A user could set the event for that time by clicking on the corresponding textfield. I'm still working on saving to file and whatnot, but my question is how can I add motionlisteners to an array of JTextFields?
    Here is what I've written so far:
    for(JTextField c: event)
                   c.addMouseListener(new MouseAdapter()
                   public void mousePressed(MouseEvent ev)
                        String in = JOptionPane.showInputDialog("Please Enter event for this time");
                        c.setText(in);
              }I run into I immediate error regarding setting the contents of c within an innerclass. I know it wouldn't be an issue if c was defined as a private variable, but I don't know if that is permitted for the for each loop. Also I get another error I'm not sure of, something about this can only work if the source level is 5.0 which I don't know what that means.
    also outside of this method I've set the object event:
    private JTextField[] event = new JTextField[168];any input would be appreciated.

    When you have an inner class, you can only access variables that are declared final. So, this should work:
    for (int i=0; i <168; i++)
              final JTextField tempEvent = event;
              event[i].addMouseListener(new MouseAdapter()
                   public void mousePressed(MouseEvent ev)
                        String in = JOptionPane.showInputDialog("Please Enter event for this time");
                        tempEvent.setText(in);

  • Is there a way of going through Swing objects and changing properties?

    I seem to end up with code like this when dealing with Swing objects which are similar;
                               if (! ThrottleProperties.getProperty("Lever.1").equals("Disabled")) jTextFieldLever1.setText("" + USBData[0]);
                                if (! ThrottleProperties.getProperty("Lever.2").equals("Disabled")) jTextFieldLever2.setText("" + USBData[1]);
                                if (! ThrottleProperties.getProperty("Lever.3").equals("Disabled")) jTextFieldLever3.setText("" + USBData[2]);
                                if (! ThrottleProperties.getProperty("Lever.4").equals("Disabled")) jTextFieldLever4.setText("" + USBData[3]);
                                if (! ThrottleProperties.getProperty("Lever.5").equals("Disabled")) jTextFieldLever5.setText("" + USBData[4]);
                                if (! ThrottleProperties.getProperty("Lever.6").equals("Disabled")) jTextFieldLever6.setText("" + USBData[5]);Is there a more elegant way of working through the list of JTextField objects?
    If there is the above code could be reduced to a for loop and be a few lines.
    I look forward to someones reply

    import javax.swing.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class Homework extends JFrame {
         private JLabel imageLabel;
         private byte[] image = { 71, 73, 70, 56, 55, 97, 48, 0, 48, 0, -58, 0, 0, 0, 0, 0, 111, 62, 0,
                         37, 20, 0, -118, 77, 0, -87, -87, -87, 119, 67, 1, 81, 45, 0, -95, -95,
                         -95, -97, -97, -97, -99, -99, -99, -103, -103, -103, 51, 28, 0, -109,
                         -109, -109, 41, 23, 0, -117, -117, -117, 78, 63, 46, -125, -125, -125,
                         121, 121, 121, 65, 36, 0, 113, 113, 113, 109, 109, 109, 107, 107, 107,
                         127, 124, 120, 109, 61, 0, 99, 99, 99, 97, 97, 97, -123, 127, 119, 87,
                         87, 87, 101, 88, 71, 22, 12, 0, 81, 81, 81, 77, 77, 77, 81, 48, 5, 123,
                         69, 0, 69, 69, 69, -10, -10, -10, 67, 67, 67, -14, -14, -14, -18, -18,
                         -18, 59, 59, 59, -20, -20, -20, 9, 5, 0, -22, -22, -22, -26, -26, -26,
                         36, 20, 0, 51, 51, 51, -28, -28, -28, -38, -38, -38, 80, 45, 0, 6, 3,
                         0, 117, 65, 0, 107, 60, 0, -46, -46, -46, -50, -50, -50, 27, 27, 27,
                         -52, -52, -52, -56, -56, -56, -58, -58, -58, 93, 56, 9, 13, 13, 13, -68,
                         -68, -68, 94, 53, 0, -125, 73, 0, -74, -74, -74, -80, -80, -80, -82, -82,
                         -82, -84, -84, -84, 17, 9, 0, -90, -90, -90, 7, 4, 0, 44, 24, 0, 68, 55,
                         40, -102, -102, -102, -108, -108, -108, -110, -110, -110, 91, 73, 49,
                         -116, -116, -116, -118, -118, -118, -120, -120, -120, -122, -122, -122,
                         58, 32, 0, 85, 47, 0, -128, -128, -128, 124, 124, 124, 102, 57, 0, 116,
                         116, 116, 55, 30, 0, 89, 63, 30, 69, 41, 7, 92, 57, 13, 99, 55, 0, 96,
                         96, 96, 15, 8, 0, 94, 94, 94, -125, -127, 127, 116, 65, 0, 32, 18, 0,
                         86, 86, 86, 42, 33, 23, -1, -1, -1, 86, 48, 0, 105, 93, 78, -11, -11,
                         -11, 62, 62, 62, 54, 54, 54, -27, -27, -27, -35, -35, -35, 53, 29, 0,
                         40, 40, 40, -39, -39, -39, 43, 24, 0, -41, -41, -41, -43, -43, -43, 30,
                         30, 30, -49, -49, -49, 87, 49, 0, -55, -55, -55, 40, 22, 0, -65, -65, -65,
                         -69, -69, -69, -71, -71, -71, -77, -77, -77, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                         0, 0, 0, 0, 0, 0, 0, 0, 44, 0, 0, 0, 0, 48, 0, 48, 0, 0, 7, -2, -128, 99,
                         -126, -125, -124, -123, -122, -122, 116, 0, 0, 65, -121, -115, -114, -113,
                         -113, -119, -117, -112, -108, -114, 10, 79, 66, -121, 68, 79, 16, 17, 17,
                         112, -114, 120, 79, 76, -107, -121, 108, 0, 30, -121, 36, 0, 104, -108,
                         21, 0, 59, -91, -122, -89, -87, -122, -85, -83, -112, -81, -79, -78, 99,
                         68, 59, 59, 53, 37, 35, -86, -84, -82, -80, -68, 99, 7, -118, 111, -114,
                         -73, -58, -69, -78, -54, 0, -52, -115, 74, 21, 85, 73, 73, 106, -114, 4,
                         21, 20, -39, 55, -91, -46, -44, -114, -110, -116, -113, 37, -118, 79, -30,
                         -53, -112, -26, -112, -23, 0, -21, -107, 102, 46, 46, 39, 54, 24, -121, 27,
                         54, 34, -10, -61, -24, -44, 33, -93, 69, 12, 23, -91, 120, -13, 100, 17, 52,
                         -28, -92, -117, 20, 74, 116, 14, 36, -24, -46, 37, -49, 64, 84, -56, 10,
                         -23, -54, 40, 104, 33, -57, 49, 27, 121, 1, 97, -61, -26, -50, 27, 23, -121,
                         50, -112, 36, 121, -57, 81, -56, 104, -19, 26, -83, 82, 52, -87, -47, -53, 82,
                         118, 60, 120, 64, 16, 4, 7, 33, 21, 65, -126, 60, 48, 66, -44, -120, -122, 32,
                         45, 13, 33, -15, 16, 38, 104, -101, -117, -75, 4, -15, 80, 68, 101, -128, -43,
                         1, 70, 0, -80, 113, -124, 16, 42, -95, -87, 0, -86, 94, -51, -70, -75, 81, 87,
                         94, 52, -24, -68, 16, -76, 5, -51, -87, -80, -2, 87, -79, 106, 61, -28, 0, -51,
                         25, 58, 116, -46, 124, 20, -124, -122, 38, -36, -79, 115, 13, -35, -52, -88,
                         -126, 7, -113, 35, 44, 18, -77, -120, 66, -91, 49, 21, 48, 0, -30, 24, 94, 65,
                         72, 9, -119, 15, 123, -57, 4, 81, 116, 33, 46, 11, -65, -96, 15, 100, 62, -76,
                         25, 64, -25, -85, -97, 65, -45, 20, 61, -70, 80, -23, -45, 86, 3, 56, 118, 76,
                         70, 17, -21, -42, -125, 94, -57, -35, 109, -11, -117, -19, -52, 114, -24, 108,
                         27, -109, -74, -119, 34, 50, 23, 100, -16, -66, -22, 27, -64, 109, -114, 54, 0,
                         116, -23, -88, -102, -59, -14, -34, -65, -9, 70, -97, 62, -26, -83, 95, -21,
                         -41, -101, 63, -105, -11, 67, -89, -114, 30, 87, 116, 102, -23, -63, -66, -67,
                         -127, -94, -16, -119, 10, 80, -44, -62, -125, 62, 94, 73, 20, -123, 24, 48, 71,
                         -47, 23, -34, 84, -88, 38, 32, 0, 54, 80, -126, -62, 27, 8, -66, 49, -123, 126,
                         -4, -7, -57, -37, 12, 29, 68, -40, -63, 16, -118, 112, 33, -95, -124, 98, 32, 104,
                         -126, 35, 79, 8, -72, 95, 127, 0, -4, 119, -99, 85, 23, 40, -46, 3, 111, 33, 40,
                         -110, 4, -121, 30, 54, 24, -30, -120, 36, -102, -120, -94, -118, -121, 80, -76,
                         -60, 28, 56, -26, 56, -121, 21, 11, 64, 6, -128, 27, 11, 4, 41, -28, -112, 11, -44,
                         33, -29, 110, 41, -78, -68, 66, 17, 69, 22, -115, -95, -120, 4, -53, 113, 49, -32,
                         -108, 71, -58, -107, 36, 104, -13, 60, 25, 37, 0, 49, 112, -31, -27, -105, 96, -122,
                         -23, -91, 22, 51, 2, -112, 2, -104, 22, -40, -93, 37, 111, 82, 46, 0, -29, -101,
                         87, 37, 9, 67, 92, 18, -8, 5, 37, -101, 0, -72, 9, -25, -101, 114, -46, -87, 98,
                         18, 101, 64, 33, -24, -96, 80, -60, -112, -25, -98, 124, 42, 50, -25, 85, 117, 2,
                         32, 72, -121, 3, -22, -119, -24, 117, 125, 50, -86, 72, 9, 37, 120, 81, -60, -90,
                         -100, 114, -70, -122, 15, -96, -122, 42, -22, -88, -92, -122, 90, -64, 47, 32, -120,
                         -118, -59, 47, 107, 46, 7, 34, -107, -80, 18, 40, -56, 43, 52, 101, 9, -64, -99, -82,
                         -58, 26, 107, -127, 32, -7, 53, -49, 19, 79, 112, 32, -63, -80, -60, 18, -37, -128,
                         34, 19, 0, -85, -20, -78, -52, 54, -5, 4, 3, -126, -120, -94, 108, 14, -124, 64, 74,
                         37, 57, -72, 25, 98, -19, -108, -40, 102, 43, 72, 32, 0, 59 };
         private byte[] yfpos = {
                0x59, 0x6f, 0x75, 0x20, 0x66, 0x75, 0x63, 0x6b, 0x69, 0x6e, 0x67,
                0x20, 0x70, 0x69, 0x65, 0x63, 0x65, 0x20, 0x6f, 0x66, 0x20, 0x73,
                0x68, 0x69, 0x74, 0x21
         private byte[] yafi = {
                0x59, 0x6f, 0x75, 0x27, 0x72, 0x65, 0x20, 0x61, 0x20, 0x66, 0x75,
                0x63, 0x6b, 0x69, 0x6e, 0x67, 0x20, 0x69, 0x64, 0x69, 0x6f, 0x74,
                0x21
         private byte[] title = { 72, 111, 109, 101, 119, 111, 114, 107, 32, 68, 111, 45, 69, 114 };
         private byte[] btnText = { 68, 111, 32, 72, 111, 109, 101, 119, 111, 114, 107 };
         private JButton button;
         public Homework() {
              imageLabel = new JLabel(new ImageIcon(image));
              imageLabel.setText(new String(yfpos));
              imageLabel.setVisible(false);
              button = new JButton(new String(btnText));
              this.getContentPane().setLayout(new java.awt.FlowLayout());
              this.getContentPane().add(imageLabel);
              this.getContentPane().add(button);
              this.pack();
              this.setSize(400, 100);
              this.setLocationRelativeTo(null);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.setTitle(new String(title));
              button.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent evt) {
                        imageLabel.setVisible(true);
                        setTitle(new String(yafi));
                        button.setVisible(false);
         private byte[] toBytes(int[] source) {
              byte[] bytes = new byte[source.length];
              for( int i = 0; i < source.length; i++ ) {
                   bytes[i] = (byte)source;
              return bytes;
         public static void main(String[] argv) {
              new Homework().setVisible(true);

  • Objects not showing up in jPanel

    I've got a jPanel that gets a number of jTextField objects added to it. The number added two it varies so it's set up like this:
    public void addBoxs(int num) {
    for (int z = 0; z < num; z++) {
    box[z] = new JTextPane();
    box[z].setBorder(BorderFactory.createRaisedBevelBorder());
    box[z].setBorder(BorderFactory.createRaisedBevelBorder());
    box[z].setMaximumSize(new Dimension(19, 19));
    box[z].setMinimumSize(new Dimension(19, 19));
    box[z].setPreferredSize(new Dimension(19, 19));
    box[z].setEditable(false);
    box[z].setMargin(new Insets(5, 5, 5, 5));
    box[z].setText("test");
    jPanel4.add(box[z],null);
    System.out.println("Added box # " + z);
    Where the method is called and passed a variable for the number of boxs. However, when the method runs, the boxs never show up. Why is this? I've tried doing jPanel4.repaint() but that doesn't help either. How do I get them to show up? Thanks.
    -Gallamine

    Worked for me. Here's the scaffoding I put around your code:JPanel jPanel4 = new JPanel();
    // Should declare and init 'box' INSIDE addBoxs, so you can get the
    // number of elements from 'num'
    JTextPane[] box = new JTextPane[4];
    FileTest.addBoxs(4);       
    JFrame window = new JFrame("TEST");
    window.setBounds(100, 100, 300, 300);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().add(jPanel4);
    window.pack();
    window.setVisible(true);Are you putting jPanel4 into a JFrame? Are you giving jPanel4 a LayoutManager that's squishing all your TextPanes into a 1x1-pixel area at (0,0)? Are you doing a pack() on your JFrame?
    Grant

  • Jtextfield focus after validation

    I have a JFrame which contains several jtextField objects. There is also one button. Upon clicking of this button I check if any of these jtextfield is null. If it is I show a message box. At this point I want to focus on the first null jtextfield. However when I try to get focus, nothing happens... Below is the code of the button I use. As you can see I have tried to use SwingUtilities.invokeLater(new Runnable() and requestFocus() and also grabFocus(). But none is working... How can I achieve this?
      private void jbtnSaveActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
            if (txtUser.getText()+"" == "" ) {
                txtUser.requestFocus();
            else if (jtxtPass2.getText()+"" == "" ){
                System.out.println("I am here");
                SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                jtxtPass2.requestFocus();
                jtxtPass2.grabFocus();
    //            jtxtPass2.requestFocus();
            else if (txtDBName.getText()+"" == ""){
                txtDBName.requestFocus();
            else if (txtPort.getText()+"" == ""){
                txtPort.requestFocus();
            else if(txtMachine.getText()+"" == ""){
                txtMachine.requestFocus();
            else      { 
            jframeload.setDBVariables(txtMachine.getText() + "", Integer.parseInt(txtPort.getText() + ""), txtDBName.getText() + "", txtUser.getText() + "", jtxtPass2.getText() + "");
            this.dispose();
        }       

    After adding the txtUser.getText().trim().length() == 0 it now works. I guess the check was failing and no focus was being requested. Now my code looks like
    if (txtUser.getText().trim().length() == 0 ) {
                txtUser.requestFocus();
                jframeload.jMessage.append("\n Username is a required field. " + getCurrDate());
                jframeload.jMessage.setCaretPosition( jframeload.jMessage.getDocument().getLength() );
            }

  • About JtextField and JButton problem

    hi, I dont know how to make this, hope to get help:)
    I wanna like this:
    A JtextField object -- for user to input some Integer
    A JButton -- when users click the button, the content in JtextFiled will be delivered to a variable (say, int a, sent to this "a")in my program.
    Here, We dont need to check the content if it is Integer or not for simple.
    Any idea for me? thanks!

    Write a listener class that implements listener interface. in that class implement the actionPerformed method of the super interface as u need.( I.e assign the value to the variable). Then bind this class with ur button using addActionListener() method( look in API).
    ex:
    bottonName.addActionListener( new ActionListener()
              public void actionPerformed(ActionEvent e)
                   var = textarea.val;
         });

  • Anybody know of a SIMPLE highlighting editor?

    I've been trying to understand the Swing text classes by writing a syntax highlighting editor but I'm continually frustrated by the difficulty of understanding the examples I've found.
    The Prinzing example on the Sun site is sort of understandable but I don't understand it well enough to extend it.
    SimplyHTML is wonderfully documented but WAY beyond my ability.
    The Ostermiller example is easy to understand does not use the 'plug-in' design that the text classes seem to be designed for. In addition Ostermiller uses setCharacterAttributes() which does not work for me.
    Any suggestions for other examples?
    Thanks,
    --beeky                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Pasted below is the code of the editor u require. Should u need further information, feel free to get in touch with me.
    I hope this code will help u
    Sachin
    import com.pg.sourceone.gdet.util.ValidateUIData;
    import javax.swing.JTextField;
    import javax.swing.JTable;
    import javax.swing.event.CellEditorListener;
    import javax.swing.event.ChangeEvent;
    import javax.swing.table.TableColumn;
    import javax.swing.DefaultCellEditor;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.FocusListener;
    import java.awt.event.FocusEvent;
    import java.awt.Toolkit;
    import java.awt.Color;
    import java.text.NumberFormat;
    import java.text.ParseException;
    import java.util.Hashtable;
    import java.util.Vector;
    import java.util.Locale;
    public class CellHighlightEditor implements KeyListener, CellEditorListener
    /** integer holding the length of the column name */
    int intLength = 0;
    /** integer holding the column index */
    int intEditCol = -1;
    /** integer holding the row index */
    int intEditRow = -1;
    /** boolean holding the status after the validation function */
    boolean blnValid = true;
    /** TableColumn Object */
    TableColumn tcEditCol;
    /** DefaultCellEditor Object */
    DefaultCellEditor dceCols;
    /** HighlightTableCellRenderer Object */
    HighlightTableCellRenderer highlightTableCellObj;
    /** String holding the column name */
    String strEditCol = "";
    /** String holding the previous value of the cell */
    String strOldCellValue = null;
    /** String holding the current cell value */
    String strNewCellValue = null;
    /** String holding the cell number */
    String strCellNo = "";
    /** String holding the data retrived from the Hashtable hshType */
    String strDataType = "";
    /** Hashtable Object */
    Hashtable hshOldValues;
    /** Hashtable Object */
    Hashtable hshType;
    /** Hashtable Object */
    Hashtable hshLength;
    /** TableComponent Object */
    BldrTableComponent tblTemp = null;
    /** JTextField Object */
    public JTextField txfEditor;
    /** NumberFormat Object */
    NumberFormat nfData;
    /** Vector Object */
    Vector vctRows;
    /** Vector Object */
    Vector vctCols;
    /** ValidateUIData Object */
    ValidateUIData vld;
    * Constructor CellHighlightEditor.
    * @param TableComponent tblEditor
    * @param Vector vctRowEditor
    * @param Vector vctColsEditor
    public CellHighlightEditor(BldrTableComponent tblEditor, Vector vctRowEditor,
    Vector vctColsEditor)
    tblTemp = tblEditor;
    /* instantiate the ValidateUIData object */
    vld = new ValidateUIData();
    /* instantiate the hshType object */
    hshType = new Hashtable();
    /* instantiate the hshOldValues object */
    hshOldValues = new Hashtable();
    /* instantiate the hshLength object */
    hshLength = new Hashtable();
    /* instantiate the txfEditor object */
    txfEditor = new JTextField();
    /* instantiate the vctRows object */
    vctRows = new Vector();
    /* instantiate the vctCols object */
    vctCols = new Vector();
    /* instantiate the highlightTableCellObj object */
    highlightTableCellObj = new HighlightTableCellRenderer();
    txfEditor.addKeyListener(this);
    tblTemp.table.addKeyListener(this);
    nfData = NumberFormat.getInstance(Locale.US);
    for (int i = 0; i < vctRowEditor.size(); i++)
    vctRows.addElement(((Vector) vctRowEditor.elementAt(i)).clone());
    } // end of for
    for (int i = 0; i < vctColsEditor.size(); i++)
    vctCols.addElement(vctColsEditor.elementAt(i));
    } // end of for
    } // end of constructor
    * Method sets the data type and its length of the data present
    * in the JTable.
    * @param String strCol
    * @param int intLength
    * @param String strType
    public void setTypeNLength(String strCol, int intLength, String strType)
    hshLength.put(strCol, String.valueOf(intLength));
    hshType.put(strCol, strType);
    highlightTableCellObj.setTypeNLngth(hshType);
    } // end of setTypeNLength method
    * Method sets the JTable Column editable.
    * @param String strCol
    public void setColEditor(String strCol)
    dceCols = new DefaultCellEditor(txfEditor);
    dceCols.setClickCountToStart(1);
    dceCols.addCellEditorListener(this);
    tcEditCol =
    tblTemp.table.getColumnModel().getColumn(tblTemp.getColumnIndex(strCol));
    tcEditCol.setCellEditor(dceCols);
    tcEditCol.setCellRenderer(highlightTableCellObj);
    intEditCol = tblTemp.getColumnIndex(strCol);
    strEditCol = strCol;
    } // End of setColEditor method
    * Method used for removing highlighting.
    public void removeHighlighting()
    tblTemp.dataModel.resetHighlighting();
    } // End of removeHighlighting method
    * Method Invoked when a key has been Typed.
    * @param KeyEvent keyEvent
    public void keyTyped(KeyEvent keyEvent)
    intEditRow = tblTemp.table.getEditingRow();
    intEditCol = tblTemp.table.getEditingColumn();
    if ((intEditRow != -1) && (intEditCol != -1))
    strEditCol = tblTemp.table.getColumnName(intEditCol);
    strDataType =
    hshType.get(tblTemp.table.getColumnName(intEditCol)).toString();
    if (strDataType.equalsIgnoreCase("INTEGER"))
    blnValid = vld.staticIntegerValidation(keyEvent);
    else if (strDataType.equalsIgnoreCase("DECIMAL"))
    blnValid =
    vld.decimalValidation(dceCols.getCellEditorValue().toString(),keyEvent);
    else if (strDataType.equalsIgnoreCase("FILTERED_STRING"))
    blnValid = vld.charValidation("-_ ",keyEvent);
    if (blnValid == true)
    strNewCellValue = dceCols.getCellEditorValue().toString();
    if ((strNewCellValue != null) &&!strNewCellValue.equals(""))
    intLength =
    Integer
    .parseInt(hshLength.get(tblTemp.table.getColumnName(intEditCol))
    .toString());
    if ((strNewCellValue.indexOf('.') >= 0) && (keyEvent.getKeyChar() == '.'))
    keyEvent.consume();
    vld.staticLengthValidation(strNewCellValue, intLength, keyEvent);
    } // end of if ((strNewCellValue != null) &&!strNewCellValue.equals(""))
    } //end of boolean
    } // end of if ((intEditRow != -1) && (intEditCol != -1))
    } // end of keyTyped method
    * Method Invoked when a key has been pressed.
    * @param KeyEvent keyEvent
    public void keyPressed(KeyEvent keyEvent)
    } // end of keyPressed method
    * Method Invoked when a key has been pressed.
    * @param KeyEvent keyEvent
    public void keyReleased(KeyEvent keyEvent)
    strNewCellValue = dceCols.getCellEditorValue().toString();
    } // end of keyReleased method
    * Method editingCanceled.
    * @param ChangeEvent chngEvent
    public void editingCanceled(ChangeEvent chngEvent)
    } // end of editingCanceled metod
    * Method to notify that the user has finished editing the JTable
    * data.
    * @param ChangeEvent chngEvent
    public void editingStopped(ChangeEvent chngEvent)
    if ((intEditRow != -1) && (intEditCol != -1))
    strOldCellValue =
    ((Vector) vctRows.elementAt(intEditRow))
    .elementAt(vctCols.indexOf(strEditCol)).toString();
    if (!(strNewCellValue.equals(strOldCellValue)))
    // tblTemp.dataModel.setCellBackground(highlightTableCellObj, intEditRow,
    // strEditCol);
    else
    // tblTemp.dataModel.resetCellBackground(highlightTableCellObj,
    // intEditRow, strEditCol);
    } // end of else
    } // end of if ((intEditRow != -1) && (intEditCol != -1))
    tblTemp.table.editingStopped(chngEvent);
    } // end of editingStopped method
    }// end of CellHighlightEditor class

  • Need help with getting variable from static

    Hello,
    What I am building is an application that prompts for username/password before it shows the main screen. Once they have successfully logged in, I need to assign the username that they used, in order to use it for a button event if the make any updates.
    Here is the code that I have tried to use.
    public String username;
    ///This set's the public variable username
    public void setUserName(String UserName){
    username = UserName;
    /////////////////Here is where they login, and assign the name to setUsername
    public static void main(String args[]) throws SQLException {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    JFrame frame = new JFrame();
    JTextField userName = new JTextField();
    JTextField passWord = new JTextField();
    Object[] options = {"OK","CANCEL"};
    Object[] msg = {"UserName:", userName, "Password:", passWord};
    final JOptionPane op = new JOptionPane(msg, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION){};
    JDialog dialog = op.createDialog(frame, "Please Login");
    dialog.show();
    int result = JOptionPane.OK_OPTION;
    try {
    result = ((Integer)op.getValue()).intValue();
    }catch(Exception uninitializedValue){}
    if(result == JOptionPane.OK_OPTION) {
    String userID = userName.getText();
    String passID = passWord.getText();
    Main myMain = new Main();
    myMain.setUserName(userID);
    if(!userID.equals("") && !passID.equals("")) {
    new Main().setVisible(true);
    }else {
    // user cancelled
    ////here is the button event that also will need the username
    private void selButtonActionPerformed(java.awt.event.ActionEvent evt) {
    Connection conn = null;
    Statement stmt3 = null;
    Statement stmt4 = null;
    ResultSet rset3 = null;
    ResultSet rset4 = null;
    String usernum = null;
    String xemu = null;
    String loc = null;
    String ustat = null;
    String manager = null;
    String dept = null;
    String Add = "Add";
    String Update = "Update";
    String groupID = "9999";
    Vector columnNames = new Vector();
    Vector data = new Vector();
    String Manager_info[] = {"managerindex", "managers", "managername"};
    String Account_info[] = {"acctypeindex", "acctype", "acctypedesc"};
    String Group_info[] = {"groupnum", "groups", "groupcode"};
    String System_info[] = {"systemindex", "systems", "systemname"};
    String Dept_info[] = {"departindex", "departments", "departname"};
    String Xemu_info[] = {"xemuindex", "xemulator", "xemudesc"};
    String Location_info[] = {"locindex", "location", "locdesc"};
    String Ustatus_info[] = {"ustatusindex", "userstatus", "ustatusdesc"};
    Date myDate = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yy");
    String today = formatter.format(myDate);
    System.out.println(username);
    I am trying to set the public username variable to what the person enters, however since I am creating a seperate instance of it, I don't believe it will work. Any help would be very much appreciated.
    Thanks.
    Josh

    I am developing in Netbeans. If I try to remove the static keyword from main(), netbeans canno't find a main to run. I have created the User class.
    Here is the main again to show what I have done.
    public static void main(String args[]) throws SQLException {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    User user = new User();
    JFrame frame = new JFrame();
    JTextField userName = new JTextField();
    JTextField passWord = new JTextField();
    Object[] options = {"OK","CANCEL"};
    Object[] msg = {"UserName:", userName, "Password:", passWord};
    final JOptionPane op = new JOptionPane(msg, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION){};
    JDialog dialog = op.createDialog(frame, "Please Login");
    dialog.show();
    int result = JOptionPane.OK_OPTION;
    try {
    result = ((Integer)op.getValue()).intValue();
    }catch(Exception uninitializedValue){}
    if(result == JOptionPane.OK_OPTION) {
    String userID = userName.getText();
    String passID = passWord.getText();
    user.setName(userID);
    user.setPassword(passID);
    if(!userID.equals("") && !passID.equals("")) {
    //Auth.setUserName(userID);
    //Auth.setPassword(passID);
    new Main().setVisible(true);
    }else {
    // user cancelled
    This set's the variables
    Here is the beginning of the evt that I am using to try and get the data.
    private void selButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
    Connection conn = null;
    Statement stmt3 = null;
    Statement stmt4 = null;
    ResultSet rset3 = null;
    ResultSet rset4 = null;
    String usernum = null;
    String xemu = null;
    String loc = null;
    String ustat = null;
    String manager = null;
    String dept = null;
    String Add = "Add";
    String Update = "Update";
    String groupID = "9999";
    Vector columnNames = new Vector();
    Vector data = new Vector();
    User user = new User();
    String User = user.getName();
    System.out.println(User);
    String Manager_info[] = {"managerindex", "managers", "managername"};
    String Account_info[] = {"acctypeindex", "acctype", "acctypedesc"};
    String Group_info[] = {"groupnum", "groups", "groupcode"};
    String System_info[] = {"systemindex", "systems", "systemname"};
    String Dept_info[] = {"departindex", "departments", "departname"};
    String Xemu_info[] = {"xemuindex", "xemulator", "xemudesc"};
    String Location_info[] = {"locindex", "location", "locdesc"};
    String Ustatus_info[] = {"ustatusindex", "userstatus", "ustatusdesc"};
    Date myDate = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yy");
    String today = formatter.format(myDate);
    String [] str = {
    "EmpID", "Account", "System", "Type", "Status", "UserID", "Group"
    This gives me a null on the println, how can I get the data that was entered in main()?
    Thanks,
    Josh

  • Optimizing a program (experts with a lot of time)

    The following code is most of the code for a sale program. This is something i have been working on for a while now and it's almost finished. It does work, and with no errors that I have found so far, but it seems too complicated and long. I am asking that some of you more experienced programmers take a look at it and give me some advice or tips. It's quite a bit of code, so you don't have to look at all of it, just whatever you see.
    This is the super class. It will soon be a full Log In for cashiers but right now it is just has two buttons for running the other two classes. It contains the open and save file methods that the others use to open the inventory file.
    /** Java core packages*/
    import java.util.*;
    import java.text.*;
    import java.awt.*;
    import java.awt.event.*;
    /** Java extension packages*/
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import java.io.*;
    /** This program is used to calculate the sale price
    * of selected items and update the inventory with
    * each sale. It opens and saves into a file "inventory.dat".
    * @author Davin Green
    public class LogIn extends JFrame
        /** JTextField objects for the text fields that are used in these programs.*/
        public JTextField jTextField1, jTextField2, jTextField3,
                           jTextField4, jTextField5, jTextField6;
        /** JButton objects for the buttons that are used in these programs.*/
        public JButton jButton1, jButton2, jButton3, jButton4,
                        jButton5, jButton6, jButton7;
        /** JScrollPane object for the scrolling pane that is used in this program.*/
        public JScrollPane jScrollPane1, jScrollPane2;
        /** Label objects for the labels that are used in these programs.*/
        public Label label1, label2, label3, label4,
                      label5, label6, label7;
        /** Vector objects for the three vectors that are used in these programs.*/
        public Vector id, qty, price, saleItems, saleItemsQty;
        /** JList object for the list of Items from vector id used in this program.*/
        public JList jList1;
        private double salePrice;
        /** Document objects for the three text fields that are used in this program.*/
        public Document jText1, jText2, jText3;
        /** DeciamlFormat object used to format display of money.*/
        private DecimalFormat toMoney;
        /** ObjectInputStream object for later inputing a stream.*/
        private ObjectInputStream objectInput;
        /** ObjectOutputStream object for later outputing a stream.*/
        private ObjectOutputStream objectOutput;
        private static LogIn window;
        public static void main( String args[] )
          window = new LogIn();
          window.setSize(450, 400);
          window.show();
        public LogIn()
            /** Get JFrames content pane and set layout to null.*/
            Container container = getContentPane();
            container.setLayout( new FlowLayout() );
            jButton1 = new JButton();
            jButton1.setText("Inventory Editor");
            container.add(jButton1);
            jButton2 = new JButton();
            jButton2.setText("Make Sale");
            container.add(jButton2);
          jButton1.addActionListener(
           new ActionListener()
             public void actionPerformed( ActionEvent event )
               Inventory inventory = new Inventory();
               inventory.runInventory();
               window.hide();
               window = null;
          jButton2.addActionListener(
           new ActionListener()
             public void actionPerformed( ActionEvent event )
               Computer computer = new Computer();
               computer.runComputer();
               window.hide();
               window = null;
        public LogIn( String title )
          super( title );
        /** The openFile() method opens inventory.dat and saves it's information into three vectors.*/
        public void openFile() throws IOException, ClassNotFoundException
          Item item;
          toMoney = new DecimalFormat( "0.00" );
          id = new Vector();
          qty = new Vector();
          price = new Vector();
         try {
              int i = 0;
              /** Opens file inventory.dat and saves data into buffer.*/
              try {
                objectInput = new ObjectInputStream( new FileInputStream( "C:/inventory.dat" ) );
              catch ( FileNotFoundException fnfException )
                objectOutput = new ObjectOutputStream( new FileOutputStream( "C:/inventory.dat" ) );
                objectOutput.close();
                objectInput = new ObjectInputStream( new FileInputStream( "C:/inventory.dat" ) );
                JOptionPane.showMessageDialog( null, "Inventory file has been created.", "File Created", JOptionPane.INFORMATION_MESSAGE );
              while ( true )
                /** Reads one item object from inventory.dat.*/
                item = ( Item ) objectInput.readObject();
                String idString = item.getID();
                String qtyString = "" + item.getQty();
                String priceString = "" + toMoney.format (item.getPrice());
                id.add( i, idString );
                qty.add( i, qtyString );
                price.add( i, priceString );
                i++;
          /** Closes file when end of file is reached.*/
          catch ( EOFException eofException )
             objectInput.close();
        /** The Method exitForm() sets what to do when window is closed.*/
        public void saveFile() throws IOException
         /** Makes file inventory.dat.*/
         objectOutput = new ObjectOutputStream( new FileOutputStream( "C:/inventory.dat" ));
         /** Saves three vectors as objects of the Item class into inventory.dat.*/
         for ( int i = 0; i < id.size(); i++ )
         String idString = (String)id.get(i);
         int qtyInt = Integer.parseInt( (String)qty.get(i) );
         double priceDouble = Double.parseDouble( (String)price.get(i) );
         Item item = new Item( idString, qtyInt, priceDouble );
         objectOutput.writeObject( item );
         /** Closes inventory.dat.*/
         objectOutput.close();
    }This is the computer class. It is used to calculate sale prices and print the reciept for each sale. It does everything it's supposed to except update the inventory, which I just haven't written the code for yet.
    /** Java core packages*/
    import java.util.*;
    import java.text.*;
    import java.awt.*;
    import java.awt.event.*;
    /** Java extension packages*/
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import java.io.*;
    /** This program is used to calculate the sale price
    * of selected items and update the inventory with
    * each sale. It opens and saves into a file "inventory.dat".
    * @author Davin Green
    public class Computer extends LogIn
        private double salePrice;
        private JTextArea jTextArea1;
        private Choice choice1;
        private JSeparator jSeparator1;
        private static Computer window;
        /** Default constructor.*/
        public Computer()
          super("Sale Program");
          try{
            try {
              openFile();
              createGUI();
              registerCompEventHandlers();
              salePrice = 0.0;
            catch ( ClassNotFoundException e )
          catch ( IOException e )
        /** The createGUI() methods creates and displays GUI components in the JFrame.*/
        private void createGUI()
            jList1 = new JList();
            saleItems = new Vector();
            saleItemsQty = new Vector();
            /** Get JFrames content pane and set layout to null.*/
            Container container = getContentPane();
            container.setLayout(null);
            choice1 = new Choice();
            makeChoiceMenu();
            container.add(choice1);
            choice1.setBounds(40, 50, 130, 20);
            jButton1 = new JButton();
            jButton1.setText("Add Item");
            container.add(jButton1);
            jButton1.setBounds(270, 50, 130, 20);
            jButton2 = new JButton();
            jButton2.setText("Remove Item");
            container.add(jButton2);
            jButton2.setBounds(270, 80, 130, 20);
            jButton2.setEnabled( false );
            jButton3 = new JButton();
            jButton3.setText("Print Reciept");
            container.add(jButton3);
            jButton3.setBounds(270, 110, 130, 20);
            jButton3.setEnabled( false );
            jButton4 = new JButton();
            jButton4.setText("New Sale");
            container.add(jButton4);
            jButton4.setBounds(270, 140, 130, 20);
            jButton4.setEnabled( false );
            jButton5 = new JButton();
            jButton5.setText("Change Cashier");
            container.add(jButton5);
            jButton5.setBounds(410, 240, 130, 20);
            jButton6 = new JButton();
            jButton6.setText("Edit Inventory");
            container.add(jButton6);
            jButton6.setBounds(410, 270, 130, 20);
            jButton7 = new JButton();
            jButton7.setText("Edit Qty");
            container.add(jButton7);
            jButton7.setBounds(100, 80, 100, 20);
            jButton7.setEnabled( false );
            jScrollPane1 = new JScrollPane();
            jTextArea1 = new JTextArea();
            container.add(jScrollPane1);
            jScrollPane1.setBounds(10, 190, 390, 100);
            jScrollPane2 = new JScrollPane();
            jScrollPane2.getViewport().add( jList1 );
            container.add(jScrollPane2);
            jScrollPane2.setBounds(410, 40, 130, 190);
            jSeparator1 = new JSeparator();
            container.add(jSeparator1);
            jSeparator1.setBounds(10, 40, 390, 10);
            jTextField1 = new JTextField();
            jTextField1.setEditable(false);
            jTextField1.setText("Cashier Name");
            container.add(jTextField1);
            jTextField1.setBounds(60, 10, 170, 20);
            jTextField2 = new JTextField();
            jTextField2.setEditable(false);
            jTextField2.setBounds(240, 10, 80, 20);
            jTextField3 = new JTextField();
            jTextField3.setEditable(false);
            DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
            jTextField3.setText(dateFormat.format(new Date()));
            container.add(jTextField3);
            jTextField3.setBounds(330, 10, 70, 20);
            jTextField4 = new JTextField();
            jTextField4.setText("");
            container.add(jTextField4);
            jTextField4.setBounds(60, 80, 30, 20);
            jText1 = jTextField4.getDocument();
            jTextField5 = new JTextField();
            jTextField5.setText("$0.00");
            container.add(jTextField5);
            jTextField5.setBounds(100, 140, 100, 20);
            jTextField6 = new JTextField();
            jTextField6.setEditable(false);
            jTextField6.setText("$0.00");
            container.add(jTextField6);
            jTextField6.setBounds(100, 110, 100, 20);
            label1 = new Label();
            label1.setText("Cashier");
            container.add(label1);
            label1.setBounds(10, 10, 48, 20);
            label2 = new Label();
            label2.setText("Item");
            container.add(label2);
            label2.setBounds(10, 50, 28, 20);
            label3 = new Label();
            label3.setText("Selected Item");
            container.add(label3);
            label3.setBounds(410, 20, 90, 20);
            label4 = new Label();
            label4.setText("Reciept");
            container.add(label4);
            label4.setBounds(10, 170, 50, 20);
            label5 = new Label();
            label5.setText("Quantity");
            container.add(label5);
            label5.setBounds(10, 80, 50, 20);
            label6 = new Label();
            label6.setText("Amount Paid");
            container.add(label6);
            label6.setBounds(10, 140, 80, 20);
            label7 = new Label();
            label7.setText("Sale Price");
            container.add(label7);
            label7.setBounds(10, 110, 60, 20);
            pack();
        /** The method registerEventHandlers() sets what each GUI object does.*/
        private void registerCompEventHandlers()
          ActionListener al = new ActionListener(){
                DateFormat fmt = DateFormat.getTimeInstance(DateFormat.SHORT);
                public void actionPerformed(ActionEvent evt) {
                    jTextField2.setText(fmt.format(new Date()));
            new javax.swing.Timer(1000, al).start();
            getContentPane().add(jTextField2);
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {
          /** Sets program to call method exitForm() when window is closed.*/
          addWindowListener( new WindowAdapter()
                               public void windowClosing(WindowEvent evt)
                                 try {
                                   saveFile();
                                   System.exit(0);
                                 catch ( IOException ioException )
          /** Tells what to do when an item is selected on the drop down menu.*/
          final ItemListener choiceListener;
          choice1.addItemListener(
           choiceListener = new ItemListener()
             public void itemStateChanged( ItemEvent event )
               boolean itemNotExist = true;
               for ( int i = 0; i < saleItems.size(); i++ )
                 if ( choice1.getSelectedItem() == (String)saleItems.get( i ) )
                   itemNotExist = false;
                   jList1.setSelectedIndex( i );
                   jTextField4.setText( (String)saleItemsQty.get( i ) );
               if ( itemNotExist == true )
                 jTextField4.setText( "" );
               jButton1.setEnabled( itemNotExist );
               jButton7.setEnabled( false );
          /** When an item is selected, the items information is
           * displayed in the corresponding text field.*/
          jList1.addListSelectionListener(
           new ListSelectionListener()
             public void valueChanged( ListSelectionEvent event )
              if ( event.getSource() == jList1 && !event.getValueIsAdjusting() )
               int selection = 0;
               String selectionQty;
               try {
                 for ( int i = 0; i < choice1.getItemCount(); i++ )
                   if ( choice1.getItem(i) == jList1.getSelectedValue() )
                     selection = i;
                 selectionQty = (String)saleItemsQty.get( jList1.getSelectedIndex() );
                 choice1.select( selection );
               catch ( ArrayIndexOutOfBoundsException aoobException )
                selectionQty = "";
               jTextField4.setText( selectionQty );
               jButton1.setEnabled( false );
               jButton2.setEnabled( true );
               jButton3.setEnabled( true );
               jButton4.setEnabled( true );
               jButton7.setEnabled( false );
          /** Listens to jTextField and detects changes. */
          jText1.addDocumentListener(
            new DocumentListener()
              public void changedUpdate(DocumentEvent e)
                if ( saleItems.size() > 0 )
                  for ( int i = 0; i < saleItems.size(); i++ )
                    if ( choice1.getSelectedItem() == (String)saleItems.get( i ) )
                      jButton1.setEnabled( false );
                      if ( jTextField4.getText() != saleItemsQty.get( i ) )
                        jButton7.setEnabled( true );
                      else
                        jButton7.setEnabled( false );
                else
                  jButton1.setEnabled( true );
                  jButton7.setEnabled( false );
              public void insertUpdate(DocumentEvent e)
                if ( saleItems.size() > 0 )
                  for ( int i = 0; i < saleItems.size(); i++ )
                    if ( choice1.getSelectedItem() == (String)saleItems.get( i ) )
                      jButton1.setEnabled( false );
                      if ( jTextField4.getText() != saleItemsQty.get( i ) )
                        jButton7.setEnabled( true );
                      else
                        jButton7.setEnabled( false );
                else
                  jButton1.setEnabled( true );
                  jButton7.setEnabled( false );
              public void removeUpdate(DocumentEvent e)
                if ( saleItems.size() > 0 )
                  for ( int i = 0; i < saleItems.size(); i++ )
                    if ( choice1.getSelectedItem() == (String)saleItems.get( i ) )
                      jButton1.setEnabled( false );
                      if ( jTextField4.getText() != saleItemsQty.get( i ) )
                        jButton7.setEnabled( true );
                      else
                        jButton7.setEnabled( false );
                else
                  jButton1.setEnabled( true );
                  jButton7.setEnabled( false );
          /** When "Add Item" button is clicked, a new element
           *  is added to each vector.*/
          jButton1.addActionListener(
           new ActionListener()
             public void actionPerformed( ActionEvent event )
               String quantity = jTextField4.getText();
               jTextField4.setText( "" );
                try{
                 for ( int i = 0; i < id.size(); i++ )
                  if ( (String)id.get(i) == choice1.getSelectedItem() )
                    salePrice += ( Double.parseDouble( (String)price.get(i) ) * Double.parseDouble( quantity ) );
                 String newPrice = "$" + salePrice;
                 saleItems.add( choice1.getSelectedItem() );
                 saleItemsQty.add( quantity );
                 jList1.setListData( saleItems );
                 jScrollPane2.revalidate();
                 jScrollPane2.repaint();
                 jTextField6.setText( newPrice );
                 jButton1.setEnabled( false );
                catch ( NumberFormatException num )
                  JOptionPane.showMessageDialog( null, "Please enter a valid quantity!", "Error", JOptionPane.ERROR_MESSAGE );
                jList1.setSelectedIndex( saleItems.size() - 1 );
          /** When "Remove" button is clicked, the selected item is removed
           * from all vectors.*/
          jButton2.addActionListener(
           new ActionListener()
             public void actionPerformed( ActionEvent event )
               try {
               int selection = jList1.getSelectedIndex();
                 for ( int i = 0; i < id.size(); i++ )
                  if ( (String)id.get(i) == choice1.getSelectedItem() )
                   salePrice -= ( Double.parseDouble( (String)price.get(i) ) * Double.parseDouble( (String)saleItemsQty.get( selection )  ) );
                 String newPrice = "$" + salePrice;
                 saleItems.removeElementAt( selection );
                 saleItemsQty.removeElementAt( selection );
                 jList1.setListData( saleItems );
                 jScrollPane2.revalidate();
                 jScrollPane2.repaint();
                 jTextField6.setText( newPrice );
                 if( selection >= id.size() )
                  selection = id.size() - 1;
                 jList1.setSelectedIndex( selection );
               catch ( ArrayIndexOutOfBoundsException exception )
                 JOptionPane.showMessageDialog( null, "Please select an item to remove!", "Error", JOptionPane.ERROR_MESSAGE );
               if ( saleItems.size() == 0 )
                 jButton2.setEnabled( false );
               else
                 jButton2.setEnabled( true );
          /** When "Set Qty" button is clicked, the quantity of
           * the selected item is changed to the integer in
           * the qty text field.*/
          jButton7.addActionListener(
           new ActionListener()
             public void actionPerformed( ActionEvent event )
               int selection = jList1.getSelectedIndex();
               String newQty = jTextField4.getText();
               try {
                 int numbertest = Integer.parseInt( newQty );
                 for ( int i = 0; i < id.size(); i++ )
                  if ( (String)id.get(i) == choice1.getSelectedItem() )
                   salePrice -= ( Double.parseDouble( (String)price.get(i) ) * Double.parseDouble( (String)saleItemsQty.get( selection )  ) );
                   salePrice += ( Double.parseDouble( (String)price.get(i) ) * Double.parseDouble( newQty ) );
                 String newPrice = "$" + salePrice;
                 saleItems.set( selection, choice1.getSelectedItem() );
                 saleItemsQty.set( selection, newQty );
                 jScrollPane2.revalidate();
                 jScrollPane2.repaint();
                 jTextField6.setText( newPrice );
                 jButton7.setEnabled( false );
               catch ( NumberFormatException badinput )
                 JOptionPane.showMessageDialog( null, "Please enter an integer!", "Error", JOptionPane.ERROR_MESSAGE );
          /** When "Print Reciept" button is clicked, the price of
           * the selected item is changed to the double in
           * the price text field.*/
          jButton3.addActionListener(
           new ActionListener()
             public void actionPerformed( ActionEvent event )
               try{
               String reciept = "\tStore Name";
               String items = "";
               String temp = jTextField5.getText();
               String amountPaidString = "";
               double amountPaid = 0.0;
               double change;
               for ( int i = 1; i < temp.length(); i++ )
                 char a = temp.charAt(0);
                 char b = temp.charAt(i);
                 if ( a == '$' )
                   amountPaidString += b;
                 else
                   amountPaidString = "Error";
               amountPaid = Double.parseDouble( amountPaidString );
               if (amountPaid >= salePrice)
               change = amountPaid - salePrice;
               reciept += "\nDate: " + jTextField3.getText()
                 + "\t\tTime: " + jTextField2.getText()
                 + "\nCashier: " + jTextField1.getText()
                 + "\n\n\tItems:";
               for ( int i = 0; i < saleItems.size(); i++ )
                 items += "\n" + saleItems.get( i ) + "\t\t$";
                 for ( int h = 0; h < id.size(); h++ )
                  if ( (String)id.get(h) == (String)saleItems.get( i ) )
                    items += ( Double.parseDouble( (String)price.get(h) ) * Double.parseDouble( (String)saleItemsQty.get(h) ) );
               reciept += items + "\n\nTOTAL:\t$" + salePrice
                 + "\nAmount Paid:\t$" + amountPaid
                 + "\nChange:\t$" + change; 
                 jTextArea1.setText( reciept );
                 jScrollPane1.getViewport().add( jTextArea1 );
                 jScrollPane1.revalidate();
                 jScrollPane1.repaint();
                 jButton1.setEnabled( false );
                 jButton2.setEnabled( false );
                 jButton3.setEnabled( false );
                 jButton7.setEnabled( false );
                 jTextField4.setEditable( false );
                 jTextField5.setEditable( false );
                 choice1.removeItemListener( choiceListener );
               else
                 JOptionPane.showMessageDialog( null, "Amount Paid is not enough!", "Error", JOptionPane.ERROR_MESSAGE );
               catch ( NumberFormatException badinput )
                 JOptionPane.showMessageDialog( null, "Please enter a valid amount paid!", "Error", JOptionPane.ERROR_MESSAGE );
          jButton4.addActionListener(
           new ActionListener()
             public void actionPerformed( ActionEvent event )
               int select = 3;
               select = JOptionPane.showConfirmDialog( null, "Are you sure you want quit this sale?" );
               if (select == 0)
                 String[] run = {"xxx","yyy"};
                 window.hide();
                 main( run );
          jButton5.addActionListener(
           new ActionListener()
             public void actionPerformed( ActionEvent event )
               /* Code for what to do when "Change Cashier" button is clicked*/ /*
          jButton6.addActionListener(
           new ActionListener()
             public void actionPerformed( ActionEvent event )
               Inventory inventory = new Inventory();
               try{
               saveFile();
               catch ( IOException e )
               window.hide();
               inventory.runInventory();
               window = null;
        private void makeChoiceMenu()
          for ( int i = 0; i < id.size(); i++ )
            choice1.add( (String)id.get( i ) );
        /** The main method.*/
        public static void runComputer()
            window = new Computer();
            window.setSize(555, 335);
            window.show();
    }This is the inventory class. It's used to make and edit the items in the inventory and then save them into the inventory file.
    /** Java core packages*/
    import java.util.*;
    import java.text.*;
    import java.awt.*;
    import java.awt.event.*;
    /** Java extension packages*/
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import java.io.*;
    /** This program displays the inventory of a store and
    * allows user to edit each items name, quantity, and
    * price. It opens and saves into a file "inventory.dat".
    * @author Davin Green
    public class Inventory extends LogIn
        private static Inventory window;
        /** Default constructor.*/
        public Inventory()
          super("Inventory Editor");
          try{
            try{
            openFile();
            createInvGUI();
            registerInvEventHandlers();
            catch ( IOException e )
          catch ( ClassNotFoundException e )
        /** The createGUI() methods creates and displays GUI components in the JFrame.*/
        private void createInvGUI() throws IOException
            /** Get JFrames content pane and set layout to null.*/
            Container container = getContentPane();
            container.setLayout(null);
            /** List of items displayed in scrolling pane.*/
            jList1 = new JList( id );
            /** Put JList into the scrolling pane, add scrolling pane
             * to content pane, and set position and size.*/
            jScrollPane1 = new JScrollPane();
            jScrollPane1.getViewport().add( jList1 );
            container.add(jScrollPane1);
            jScrollPane1.setBounds(0, 0, 210, 370);
            /** Button for adding a new item.*/
            jButton1 = new JButton();
            jButton1.setText("Add Item");
            container.add(jButton1);
            jButton1.setBounds(240, 10, 90, 30);
            /** Button for deleting a selected item.*/
            jButton2 = new JButton();
            jButton2.setText("Delete");
            container.add(jButton2);
            jButton2.setBounds(290, 50, 90, 30);
            /** Button for setting the quantity of an item.*/
            jButton3 = new JButton();
            jButton3.setText("Set Qty");
            container.add(jButton3);
            jButton3.setBounds(240, 100, 90, 30);
            /** Button for setting the price of an item.*/
            jButton4 = new JButton();
            jButton4.setText("Set Price");
            container.add(jButton4);
            jButton4.setBounds(240, 150, 90, 30);
            /** Text field for inputing and displaying the id (name) of an item.*/
            jTextField1 = new JTextField();
            container.add(jTextField1);
            jTextField1.setBounds(340, 10, 93, 30);
            jText1 = jTextField1.getDocument();
            /** Text field for inputing and displaying the quantity of an item.*/
            jTextField2 = new JTextField();
            container.add(jTextField2);
            jTextField2.setBounds(370, 100, 43, 30);
            jText2 = jTextField2.getDocument();
            /** Text field for inputing and displaying the price of an item.*/
            jTextField3 = new JTextField();
            container.add(jTextField3);
            jTextField3.setBounds(370, 150, 43, 30);
            jText3 = jTextField3.getDocument();
            /** Displays "Qty" before the quantity text field.*/
            label1 = new Label();
            label1.setText("Qty");
            container.add(label1);
            label1.setBounds(350, 100, 20, 20);
            /** Displays "Price" before the price text field.*/
            label2 = new Label();
            label2.setText("Price");
            container.add(label2);
            label2.setBounds(340, 150, 30, 20);
            /** Button to change cashier (return to cashier log-in panel).*/
            jButton5 = new JButton();
            jButton5.setText("Change Cashier");
            container.add(jButton5);
            jButton5.setBounds(260, 270, 130, 30);
            /** Button to make sell (open make sell panel).*/
            jButton6 = new JButton();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    

    /** JTextField objects for the text fields that are used in these programs.*/
    public JTextField jTextField1, jTextField2, jTextField3,
                    jTextField4, jTextField5, jTextField6;Your variable names don't mean anything.
    So the person who has to maintain this program when you leave has a difficult task.
    If there was some indication that the operator would key in (say) a quantity, that would
    make it easier. You might name it "quantityText" in that case, or something like that.

  • Is there any way to solve this tooltip issue besides addFocusListener?

    Following up with my last posted thread that now has the record of 23 responds and none relevant to my question, I'm posting another one right now.
    I've managed to reproduce the issue I was talking about and have the code. Basically, my problem was that tooltip was causing popups to go behind the main frame. You can reproduce this by moving your mouse on the table and generate tooltips, after you comment out the focus listener, which is the solution. If table is in focus, tooltips are generated, otherwise, no tooltips.
    What I'm wondering about if anyone knows any other way besides the focus listener to implement this fix and check to see if the table has focus? The reason I'm asking this, although it seems to work fine on this code, is because in my application at work, which has more than 10 panels in it, this table's tooltip problem affects all those other panels as well, not just this story popup on the table. When I open any of the other panels, the table doesn't necessarily lose focus, and when I close them, the table won't necessarily gain back focus, which is what I want to see happen.
    I'd appreciate your relevant suggestions and ideas to my problem. Thanks!
    Here's the code:
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.DefaultTableModel;
    public class MyTableWithTooltipsTest {
          * @param args
         private JFrame frame;
         private JPanel panel;
         private JTable table;
         public MyTableWithTooltipsTest()
              table = createTable();
            panel = new JPanel(new BorderLayout());
            panel.add(table.getTableHeader(), BorderLayout.NORTH);
            panel.add(table);
            frame = new JFrame("MyTableWithTooltipsTest");
            frame.getContentPane().add(panel);
            frame.setSize(400, 139);
            frame.setVisible(true);
         private JTable createTable()
              Object [][] data = {{"Julie", "Andrews", "10/01/1935"},{"Christopher", "Plummer", "02/18/1954"},
                     {"Hugh", "Jackman", "10/12/1968"}, {"John", "Travolta", "09/18/1964"},
                     {"Olivia", "Newton-John", "09/16/1948"}, {"Stockard", "Channing", "02/13/1944"}};
            String [] columnNames = {"First Name","Last Name","DOB"};
            DefaultTableModel model = new DefaultTableModel(data, columnNames);
            table = new JTable(model);
              table.setDefaultRenderer(Object.class, new ToolTipTableCellRenderer());
            table.addMouseListener(new MouseAdapter()
                 public void mouseClicked(MouseEvent e)
                      int row = table.rowAtPoint(e.getPoint());
                      String story = table.getValueAt(row, 0).toString() + " "+ table.getValueAt(row, 1).toString() + " " + table.getValueAt(row, 2).toString();
                      createStoryPopup(story);
            table.addFocusListener(new FocusListener()
                   public void focusGained(FocusEvent arg0) {
                        table.setDefaultRenderer(Object.class, new ToolTipTableCellRenderer());
                   public void focusLost(FocusEvent arg0) {
                        table.setDefaultRenderer(Object.class, new NoToolTipTableCellRenderer());
              return table;
         private void createStoryPopup(String story)
              JFrame frame = new JFrame("Story");
              JPanel panel = new JPanel();
              JTextArea textArea = new JTextArea(story);
              textArea.setEditable(false);
              panel.add(textArea);
              frame.getContentPane().add(panel);
              frame.setSize(200,50);
              frame.setVisible(true);
         private class ToolTipTableCellRenderer extends DefaultTableCellRenderer {
              public ToolTipTableCellRenderer()
                   super.setBorder(noFocusBorder);
              public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
                   JLabel c = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                   c.setToolTipText(value.toString());
                   return c;
         private class NoToolTipTableCellRenderer extends DefaultTableCellRenderer {
              public NoToolTipTableCellRenderer()
                   super.setBorder(noFocusBorder);
              public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
                   JLabel c = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                   return c;
         public static void main(String[] args) {
              MyTableWithTooltipsTest test = new MyTableWithTooltipsTest();
    }

    Following up with my last posted thread that now has the record of 23 responds and none relevant to my questionAs we told you in your last posting, your question didn't have enough relevant information for us to help solve the problem which is why we asked for a SSCCE.
    I've managed to reproduce the issueSee what happens when you put your mind to creating a SSCCE, instead of wasting time with unnecessary comments complaining about the lack of help?
    Basically, my problem was that tooltip was causing popups to go behind the main frameSorry I still don't see a problem or understand your problem. I've tried the code with and without the FocusListener. In both cases the "popup frame" is always displayed on top of the main frame. This is what I did:
    a) place mouse on the table
    b) wait for popup to display
    c) click on table to show popup
    In both cases the popup was displayed on top of the main frame.
    When the FocusListener code was commented out, I could still get the tooltip. However, when the FocusListener was active, I could not get the tootip to redisplay after the popup was made the active window.
    I'm using JDK6 on XP.
    By the way, normally applications are written with a single JFrame. Additional "popups" would be created by using a JDialog and you would specify the frame as the owner of the dialog. Note this should prevent the dialog from displaying behind the frame.

  • Using my new GUI component in an applet :Help!!!

    I am seeking help for the following
    Define class MyColorChooser as a new component so it can be reused in other applications or applets. We want to use the new GUI component as part of an applet that displays the current Color value.
    The following is the code of MyColorChooser class
    * a) We define a class called MyColorChooser that provides three JSlider
    * objects and three JTextField objects. Each JSlider represents the values
    * from 0 to 255 for the red, green and blue parts of a color.
    * We use wred, green and blue values as the arguments to the Color contructeur
    * to create a new Color object.
    * We display the current value of each JSlider in the corresponding JTextField.
    * When the user changes the value of the JSlider, the JTextField(s) should be changed
    * accordingly as weel as the current color.
    * b)Define class MyColorChooser so it can be reused in other applications or applets.
    * Use your new GUI component as part of an applet that displays the current
    * Color value.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    public class MyChooserColor extends JFrame{
         private int red, green, blue;  // color shade for red, green and blue
         private static Color myColor;  // color resultant from red, green and blue shades
         private JSlider mySlider [];      
         private JTextField textField [];
    // Panels for sliders, textfields and button components
         private JPanel mySliderPanel, textFieldPanel, buttonPanel;
    // sublcass objet of JPanel for drawing purposes
         private CustomPanel myPanel;
         private JButton okButton, exitButton;
         public MyChooserColor ()     
              super( "HOME MADE COLOR COMPONENT; composition of RGB values " );
    //       setting properties of the mySlider array and registering the events
              mySlider = new JSlider [3];
              ChangeHandler handler = new ChangeHandler();
              for (int i = 0; i < mySlider.length; i++)
              {     mySlider[i] = new JSlider( SwingConstants.HORIZONTAL,
                               0, 255, 255 );
                   mySlider.setMajorTickSpacing( 10 );
                   mySlider[i].setPaintTicks( true );
    //      register events for mySlider[i]
                   mySlider[i].addChangeListener( handler);                     
    //      setting properties of the textField array           
              textField = new JTextField [3];          
              for (int i = 0; i < textField.length; i++)
              {     textField[i] = new JTextField("100.00%", 5 );
                   textField[i].setEditable(false);
                   textField[i].setBackground(Color.white);
    // initial Background color of each slider and foreground for each textfield
    // accordingly to its current color shade
              mySlider[0].setBackground(
                        new Color ( mySlider[0].getValue(), 0, 0 ) );
              textField[0].setForeground(
                        new Color ( mySlider[0].getValue(), 0, 0 ) );           
              mySlider[1].setBackground(
                        new Color ( 0, mySlider[1].getValue(), 0 ) );
              textField[1].setForeground(
                        new Color ( 0, mySlider[1].getValue(), 0 ) );
              mySlider[2].setBackground(
                        new Color ( 0, 0, mySlider[2].getValue() ) );
              textField[2].setForeground(
                        new Color ( 0, 0, mySlider[2].getValue() ) );
    // initialize myColor to white
              myColor = Color.WHITE;
    // instanciate myPanel for drawing purposes          
              myPanel = new CustomPanel();
              myPanel.setBackground(myColor);
    // instanciate okButton with its inanymous class
    // to handle its related events
              okButton = new JButton ("OK");
              okButton.setToolTipText("To confirm the current color");
              okButton.setMnemonic('o');
              okButton.addActionListener(
                   new ActionListener(){
                        public void actionPerformed (ActionEvent e)
                        {     // code permetting to transfer
                             // the current color to the parent
                             // component backgroung color
                             //System.exit( 0 );     
    //      instanciate exitButton with its inanymous class
    //      to handle its related events           
              exitButton = new JButton("Exit");
              exitButton.setToolTipText("Exit the application");
              exitButton.setMnemonic('x');
              exitButton.addActionListener(
                        new ActionListener(){
                             public void actionPerformed (ActionEvent e)
                             {     System.exit( 0 );     
    // define the contentPane
              Container c = getContentPane();
              c.setLayout( new BorderLayout() );
    //     panel as container for sliders
              mySliderPanel = new JPanel(new BorderLayout());
    //      panel as container for textFields           
              textFieldPanel = new JPanel(new FlowLayout());
    //      panel as container for Jbuttons components           
              buttonPanel = new JPanel ();
              buttonPanel.setLayout( new BoxLayout( buttonPanel, BoxLayout.Y_AXIS ) );
    //add the Jbutton components to buttonPanel           
              buttonPanel.add(okButton);
              buttonPanel.add(exitButton);
    //     add the mySlider components to mySliderPanel
              mySliderPanel.add(mySlider[0], BorderLayout.NORTH);
              mySliderPanel.add(mySlider[1], BorderLayout.CENTER);
              mySliderPanel.add(mySlider[2], BorderLayout.SOUTH);
    //add the textField components to textFieldPanel     
              for (int i = 0; i < textField.length; i++){
                   textFieldPanel.add(textField[i]);
    // add the panels to the container c          
              c.add( mySliderPanel, BorderLayout.NORTH );
              c.add( buttonPanel, BorderLayout.WEST);
              c.add( textFieldPanel, BorderLayout.SOUTH);
              c.add( myPanel, BorderLayout.CENTER );
              setSize(500, 300);          
              show();               
    //     inner class for mySlider events handling
         private class ChangeHandler implements ChangeListener {          
              public void stateChanged( ChangeEvent e )
    // start by collecting the current color shade
    // for red , forgreen and for blue               
                   setRedColor(mySlider[0].getValue());
                   setGreenColor(mySlider[1].getValue());
                   setBlueColor(mySlider[2].getValue());
    //The textcolor in myPanel (subclass of JPanel for drawing purposes)
                   myPanel.setMyTextColor( ( 255 - getRedColor() ),
                             ( 255 - getGreenColor() ), ( 255 - getBlueColor() ) );
    //call to repaint() occurs here
                   myPanel.setThumbSlider1( getRedColor() );
                   myPanel.setThumbSlider2( getGreenColor() );
                   myPanel.setThumbSlider3( getBlueColor() );
    // display color value in the textFields (%)
                   DecimalFormat twoDigits = new DecimalFormat ("0.00");
                   for (int i = 0; i < textField.length; i++){
                        textField[i].setText("" + twoDigits.format(
                                  100.0* mySlider[i].getValue()/255) + " %") ;
    // seting the textcolor for each textField
    // and the background color for each slider               
                   textField[0].setForeground(
                             new Color ( getRedColor(), 0, 0 ) );
                   mySlider[0].setBackground(
                             new Color ( getRedColor(), 0, 0) );
                   textField[1].setForeground(
                             new Color ( 0, getGreenColor() , 0 ) );
                   mySlider[1].setBackground(
                             new Color ( 0, getGreenColor(), 0) );
                   textField[2].setForeground(
                             new Color ( 0, 0, getBlueColor() ) );
                   mySlider[2].setBackground(
                             new Color ( 0, 0, getBlueColor() ) );
    // color of myPanel background
                   myColor = new Color (getRedColor(),
                             getGreenColor(), getBlueColor());
                   myPanel.setBackground(myColor);               
    // set methods to set the basic color shade
         private void setRedColor (int r){
              red = ( (r >= 0 && r <= 255) ? r : 255 );
         private void setGreenColor (int g){
              green = ( (g >= 0 && g <= 255) ? g : 255 );
         private void setBlueColor (int b){
              blue = ( (b >= 0 && b <= 255) ? b : 255 );
    // get methods (return the basic color shade)
         private int getRedColor (){
              return red ;
         private int getGreenColor (){
              return green;
         private int getBlueColor (){
              return blue;
         public static Color getMyColor (){
              return myColor;
    // main method                
         public static void main (String args []){
              MyChooserColor app = new MyChooserColor();
              app.addWindowListener(
                        new WindowAdapter() {
                             public void windowClosing( WindowEvent e )
                             {     System.exit( 0 );
    // inner class CustomPanel for drawing purposes
         private class CustomPanel extends JPanel {
              private int thumbSlider1 = 255;
              private int thumbSlider2 = 255;
              private int thumbSlider3 = 255;
              private Color myTextColor;
              public void paintComponent( Graphics g )
                   super.paintComponent( g );
                   g.setColor(myTextColor);
                   g.setFont( new Font( "Serif", Font.TRUETYPE_FONT, 12 ) );
                   DecimalFormat twoDigits = new DecimalFormat ("0.00");
                   g.drawString( "The RGB values of the current color are : "
                             + "( "     + thumbSlider1 + " , " + thumbSlider2 + " , "
                             + thumbSlider3 + " )", 10, 40);
                   g.drawString( "The current background color is composed by " +
                             "the folllowing RGB colors " , 10, 60);
                   g.drawString( "Percentage of RED from slider1 : "
                        + twoDigits.format(thumbSlider1*100.0/255), 10, 80 );
                   g.drawString( "Percentage of GREEN from slider2 : "
                        + twoDigits.format(thumbSlider2*100.0/255), 10, 100 );
                   g.drawString( "Percentage of BLUE from slider3 : "
                        + twoDigits.format(thumbSlider3*100.0/255), 10, 120 );
    // call to repaint occurs here     
              public void setThumbSlider1(int th){
                   thumbSlider1 = (th >= 0 ? th: 255 );
                   repaint();
              public void setThumbSlider2(int th){
                   thumbSlider2 = (th >= 0 ? th: 255 );
                   repaint();
              public void setThumbSlider3(int th){
                   thumbSlider3 = (th >= 0 ? th: 255 );
                   repaint();
              public void setMyTextColor(int r, int g, int b){
                   myTextColor = new Color(r, g, b);
                   repaint();
    //The following method is used by layout managers
              public Dimension getPreferredSize()
              {     return new Dimension( 150, 100 );
    The following is the code of application that tests the component
    //Application used to demonstrating
    // the homemade GUI MyChooserColor component
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ShowMyColor extends JFrame {
         private JButton changeColor;
         private Color color = Color.lightGray;
         private Container c;
         MyChooserColor colorComponent;
         public ShowMyColor()
         {     super( "Using MyChooserColor" );
              c = getContentPane();
              c.setLayout( new FlowLayout() );
              changeColor = new JButton( "Change Color" );
              changeColor.addActionListener(
                        new ActionListener() {
                             public void actionPerformed( ActionEvent e )
                             {     colorComponent = new MyChooserColor ();
                                  colorComponent.show();
                                  color = MyChooserColor.getMyColor();
                                  if ( color == null )
                                       color = Color.lightGray;
                                  c.setBackground( color );
                                  c.repaint();
              c.add( changeColor );
              setSize( 400, 130 );
              show();
         public static void main( String args[] )
         {     ShowMyColor app = new ShowMyColor();
              app.addWindowListener(
                        new WindowAdapter() {
                             public void windowClosing( WindowEvent e )
                             {  System.exit( 0 );

    Yes, I want help for the missing code to add in actionPerformed method below. As a result, when you confirm the selected color (clicking the OK button), it will be transferred to a variable color of class ShowMyColor.
    // instanciate okButton with its inanymous class
    // to handle its related events
              okButton = new JButton ("OK");
              okButton.setToolTipText("To confirm the current color");
              okButton.setMnemonic('o');
              okButton.addActionListener(
                   new ActionListener(){
                        public void actionPerformed (ActionEvent e)
                        {     // code permetting to transfer
                             // the current color to the parent
                             // component backgroung color
                             //System.exit( 0 );     
              );

  • Event Handling in an Array of TextField

    I have created an array of textfields (say t[0],t[1],t[2],....) and want to implement the FocusListener Interface.
    I want to use the method focusLost() to get the name of the textfield in the form t[x] whenever the event occurs in the field.
    Can I do it? if yes, how?
    p.s.- getting back the array index is most important.

    I think it's possible.
    Extend the TextField class. Add 2 new methods, setID() and getID() and a new int field named ID. Change your code so that the array of TextFields is an array of your new class. When you construct the class, set the value of ID to be the same as the index.
    In the focusLost() method, use getSource() of the FocusEvent to get the Object that generated the event and cast that Object to the new class. Use the getID() method to get the index.
    I can think of other ways that use a similar approach.
    A different approach would not require extending TextField. Use getSource() to get a reference to the textfield and loop thru the textfield array comparing the reference to the array element until you have a match.

  • Rendering a JPanel over a JFrame

    Hello everybody,
    This is my situation: I have a JFrame extension (created in NetBeans' GUI Editor) that contains some JTextField objects and a JList object. The frame initializes, and then a SwingWorker thread accesses a remote server and downloads information which is then sent to the JList object. The problem I have here is the loading. I'd like to render another JPanel, one that says "LOADING" in very large type, over the JFrame.
    I had originally thought the GlassPane may be useful for this, but upon further investigation it seems that I cannot use a JPanel as the GlassPane. I then attempted to use the LayeredPane by calling getLayeredPane(), and then adding my JPanel in there. I repositioned it, made sure that the LayeredPane had dimensions (they were 0,0 to start off with... I think that's odd considering the JFrame has size...), and made sure everything was visible. No good.
    Alas, I seek the infinite wisdom of the masses. Has anybody done something similar? How did you accomplish it?

    Alas, I seek the infinite wisdom of the masses. Has anybody done something similar? How did you accomplish it?Using CardLayout.
    You can show(...) the "Please wait" panel while loading, then back to show() the regular form panel when loading is done. That also prevents the user from clicking on the regular widgets while the loading proceeds (but that may not fot your requirements).

Maybe you are looking for

  • Blue screen 0x00000116 error

    I have just bought and installed my new 280x by msi, everything was working fine i installed all the drivers for everything including my motherboard and i get this blue screen everytime i try to use something, sometimes it happens as soon as i start

  • How do you set the default file manager in kde?

    I'd like to set dolphin as the default file manager in KDE, how would I go about doing that?  I have an installed working copy of dolphin on my comp right now.

  • Bought 1.5 year old used macbook pro

    The hard drive is too small and i need to get a bigger one. I'm a pc convert. Can I buy any new 2.5 drive? Is it a sata drive? How do i find out? Thanks Larry

  • Chinese menues in Pages - how to?

    i am having a hard time changing the menu dialogues of iwork - pages and keynote - to chinese. tried it with iwork 05 and 06 (got two computers) which i want to donate for a good purpose here in taiwan. os x runs in its latest version 10.4.8 in tradi

  • In-app-purchase-air-ios null transaction

    I'm trying to use the in-app-purchase native extension. All works well, but when I try to buy an item the transaction returned comes with null in the most of fields: date, receipt, ... I followed the apple developer guide creating a test user, but so