JTextfield and JButton

Hi all
My problem is that i have a JTextfield that is connected to a Oracle database that allow the user to enter data in the database. I want to have a button that will allow the user to test to see whether the data entered in the textfield is valid.
I'm not sure if i need to use sqlj or not. Any help would be gladly received.
Thanks
null

Hmmm... lots and lots of ways to handle this, depending on your particular need for the particular type of 'validation'. ( More info? )
"JTextField" is not connected to a database in the same way that the infoswing "TextFieldControl" is.. .therefore one could trap the event ActionPerformed off the JTextField and do the checks ( or use the jbutton like you suggest..but it would seem like you'd always want it checked and corrected before continuing towards the inevitable commit attempt??? ).
You can use sqlj, or you can not use it... depends upon the way you've architected your application/environment and your needs and desires.
Note (if you haven't already ) that you can also do a heck of a lot of validation at the entity/view object level.
In my case ( an application ) I have a jdbc connection up at the front end for all my miscellaneous stuff, and a validate PL/SQL stored function. The nice things about using stored procedures/functions are that the validate routines can be nested for quick and easy use by triggers and stored procedures. If you put it outside the database it gets more fun should you want to get at the common validation routines from all approaches.
Curious as to how other folk are architecting their validations....

Similar Messages

  • JTextField and JButtons not appearing until clicked.

    I'm writing a program to refresh my CS1 java skills. For some reason when I try to add a JTextField and two JButtons to my container they don't appear until Ive clicked them.
    Actually more specifically, this only happens after a 100ms wait after setting the frame visible. Any less and the components wind up visible, but scrunched up in the top middle of my frame.
    Ive found that if I add the components before and after the wait they are visible and in the correct place, but this makes a noticeable flicker.
    I'm running windows vista if that matters.
    If someone could help me I would appreciate it.
    snippet of code:
    public scrollText()
         drawingThread.start();
         mainFrame.setSize(640,160);
         mainFrame.setContentPane(draw);
         mainPane = mainFrame.getContentPane();
         mainPane.setBackground(Color.white);
         mainFrame.setResizable(false);
         mainFrame.setVisible(true);
         try
              Thread.sleep(100);
              addInterface();
         catch(InterruptedException e){}
    public void addInterface()
         textInput.setBounds(1,103,501,31);
         play.setBounds(502,103,65,30);
         play.addActionListener(this);
         stop.setBounds(568,103,65,30);
         stop.addActionListener(this);
         mainPane.add(textInput);
         mainPane.add(play);
         mainPane.add(stop);
    }

    Postings can't be moved between forums. Now you know for the next time.
    The general form for building a GUI is
    frame.getContentPane().add( yourComponentsHere );
    frame.pack();
    frame.setVisible( true );Then all the compnoent will show up according to the rules of the layout managers used.
    However is you add components to the GUI "after" the GUI is visible then the components are not automatically painted. You need to tell the GUI to invoke the layout manager again so your code would be:
    frame.getContentPane().add( componentsToVisibleGUI );
    frame.getContentPane().validate();

  • How to for JTextField and JButton..

    How can i set the size of the JTextField and getting the words alignment to be in Center format?? Can i use JButton, click on it and key in value to be displayed in text form?

    Hi,
    you can change the alignment really simple:
    JTextField textField = new JTextField("Your Text");
    textField.setHorizontalAlignment(JTextField.LEFT);
    textField.setHorizontalAlignment(JTextField.CENTER);
    textField.setHorizontalAlignment(JTextField.RIGHT);The size can be set by
    setPrefferedSize(int w, int h)or try
    setColumns(int columns)L.P.

  • How to put JTextfield and JButton in a cell of JTable

    I'm trying to put two Components into one cell of a JTable. This is no
    problem (in the TableCellRenderer) unless it comes to editing in these
    cells. I have written my own CellEditor for the table.but there is one
    minor problem: Neither the JTextfield nor the JButton has the focus so I
    can't make any input! Does anybody know what's wrong, please help me for this issue ,plese urgent

    Here you go
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.AbstractCellEditor;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellEditor;
    public class TableEdit extends JFrame
         JTable table = new JTable();
         private String[] columnNames = {"non-edit1", "edit", "non-edit2"};
         public TableEdit()
              super("Table Edit");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              createGUI();
              setLocationRelativeTo(null);
              setSize(400, 300);
              setVisible(true);
         private void createGUI()
              table.setModel(new DefaultTableModel(3,3)
                   public int getColumnCount()
                        return 3;
                   public boolean isCellEditable(int row, int column)
                        if(column == 1)
                             return true;
                        return false;
                   public String getColumnName(int column)
                        return columnNames[column];
                   public int getRowCount()
                        return 3;
                   public Class getColumnClass(int column)
                        return String.class;
                   public Object getValueAt(int row, int column)
                        return row + "" + column;
              table.setRowHeight(20);
              table.setDefaultEditor(String.class, new MyTableEditor());
              JScrollPane sp = new JScrollPane(table);
              add(sp);
         public class MyTableEditor extends AbstractCellEditor
         implements TableCellEditor
              JPanel jp = new JPanel(new BorderLayout(5,5));
              JTextField tf = new JTextField();
              JButton btn = new JButton("...");
              public MyTableEditor()
                   jp.add(tf);
                   jp.add(btn, BorderLayout.EAST);
                   btn.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent e)
                             JOptionPane.showMessageDialog(null, "Clicked Lookup");
              public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
                   tf.setText(String.valueOf(value));
                   return jp;
              public Object getCellEditorValue()
                   return tf.getText();
         public static void main(String[] parms)
              new TableEdit();
    }

  • 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;
         });

  • How to print JTextPane containing JTextFields, JLabels and JButtons?

    Hi!
    I want to print a JTextPane that contains components like JTextFields, JLabels and JButtons but I do not know how to do this. I use the print-method that is available for JTextComponent since Java 1.6. My problem is that the text of JTextPane is printed but not the components.
    I wrote this small programm to demonstrate my problem:
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.print.PrinterException;
    public class TextPaneTest2 extends JFrame {
         private void insertStringInTextPane(String text,
                   StyledDocument doc) {
              try {
                   doc.insertString(doc.getLength(), text, new SimpleAttributeSet());
              catch (BadLocationException x) {
                   x.printStackTrace();
         private void insertTextFieldInTextPane(String text,
                   JTextPane tp) {
              JTextField tf = new JTextField(text);
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(tf);
         private void insertButtonInTextPane(String text,
                   JTextPane tp) {
              JButton button = new JButton(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(button);
         private void insertLabelInTextPane(String text,
                   JTextPane tp) {
              JLabel label = new JLabel(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(label);
         public TextPaneTest2() {
              StyledDocument doc = new DefaultStyledDocument();
              StyledDocument printDoc = new DefaultStyledDocument();
              JTextPane tp = new JTextPane(doc);
              JTextPane printTp = new JTextPane(printDoc);
              this.insertStringInTextPane("Text ", doc);
              this.insertStringInTextPane("Text ", printDoc);
              this.insertTextFieldInTextPane("Field", tp);
              this.insertTextFieldInTextPane("Field", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertButtonInTextPane("Button", tp);
              this.insertButtonInTextPane("Button", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertLabelInTextPane("Label", tp);
              this.insertLabelInTextPane("Label", printTp);
              this.insertStringInTextPane(" Text Text", doc);
              this.insertStringInTextPane(" Text Text", printDoc);
              tp.setEditable(false);
              printTp.setEditable(false);
              this.getContentPane().add(tp);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setSize(400,400);
              this.setVisible(true);
              JOptionPane.showMessageDialog(tp, "Start printing");
              try {
                   tp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
              try {
                   printTp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              new TextPaneTest2();
    }First the components are shown correctly in JTextPane, but when printing is started they vanish. So I created another textPane just for printing. But this does not work either. The components are not printed. Does anybody know how to solve this?
    Thanks!

    I do not know how I should try printComponent. From the API-Doc of JComponent of printComponent: This is invoked during a printing operation. This is implemented to invoke paintComponent on the component. Override this if you wish to add special painting behavior when printing. The method print() in JTextComponent is completely different, it starts the print-job. I do not understand how to try printComponent. It won't start a print-job.

  • Reading values from JTextField and using them?

    Hello,
    I am trying to make a login screen to connect to an oracle database. Im pretty new to creaing GUI. I need help with reading the values from the JTextField and to be able to use them for my connection. So do I need to apply a listener? How do I go about doing that in this project. Thanks for any code or advice.
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.sql.*;
    public class UserDialog
        String databaseURL;
        String driver;
        String database;
        String username;
        String password;
        String hostname;
        String port;
        UserDialog() {
            getInfo();
        static String[] ConnectOptionNames = { "Login", "Cancel" };
        static String   ConnectTitle = "Login screen";
        public void getInfo() {
            JPanel      connectionPanel;
            JLabel     databaseURLLabel = new JLabel("Database URL:   ", JLabel.LEFT);
         JTextField databaseURLField = new JTextField("");
         JLabel     driverLabel = new JLabel("Driver:   ", JLabel.LEFT);
         JTextField driverField = new JTextField("");
            JLabel     databaseLabel = new JLabel("Database:   ", JLabel.LEFT);
         JTextField databaseField = new JTextField("");
            JLabel     usernameLabel = new JLabel("User Name:   ", JLabel.LEFT);
         JTextField usernameField = new JTextField("");
            JLabel     passwordLabel = new JLabel("Password:   ", JLabel.LEFT);
         JTextField passwordField = new JPasswordField("");
            JLabel     hostnameLabel = new JLabel("Host Name:   ", JLabel.LEFT);
         JTextField hostnameField = new JTextField("");
            JLabel     portLabel = new JLabel("Port:   ", JLabel.LEFT);
         JTextField portField = new JTextField("");
         connectionPanel = new JPanel(false);
         connectionPanel.setLayout(new BoxLayout(connectionPanel,
                                  BoxLayout.X_AXIS));
         JPanel namePanel = new JPanel(false);
         namePanel.setLayout(new GridLayout(0, 1));
         namePanel.add(databaseURLLabel);
         namePanel.add(driverLabel);
            namePanel.add(databaseLabel);
            namePanel.add(usernameLabel);
            namePanel.add(passwordLabel);
            namePanel.add(hostnameLabel);
            namePanel.add(portLabel);
         JPanel fieldPanel = new JPanel(false);
         fieldPanel.setLayout(new GridLayout(0, 1));
         fieldPanel.add(databaseURLField);
            fieldPanel.add(driverField);
            fieldPanel.add(databaseField);
            fieldPanel.add(usernameField);
         fieldPanel.add(passwordField);
            fieldPanel.add(hostnameField);
            fieldPanel.add(portField);
         connectionPanel.add(namePanel);
         connectionPanel.add(fieldPanel);
            // Connect or quit
            databaseURL = databaseURLField.getText();
            driver = driverField.getText();
            database = databaseField.getText();
            username = usernameField.getText();
            password = passwordField.getText();
            hostname = hostnameField.getText();
            port = portField.getText();
            int n = JOptionPane.showOptionDialog(null, connectionPanel,
                                            ConnectTitle,
                                            JOptionPane.OK_CANCEL_OPTION,
                                            JOptionPane.PLAIN_MESSAGE,
                                            null, ConnectOptionNames,
                                            ConnectOptionNames[0]);
            if (n == 0) {
                System.out.println("Attempting login: " + username);
                String url = databaseURL+hostname+":"+port+":"+database;
             // load the JDBC driver for Oracle
             try{
                   DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                   Connection con =  DriverManager.getConnection (url, username, password);
                System.out.println("Congratulations! You are connected successfully.");
                con.close();
                System.out.println("Connection is closed successfully.");
             catch(SQLException e){
                System.out.println("Error: "+e);
            else if (n == 1)
                    System.exit(0);
        public static void main (String args []) {
             UserDialog ud = new UserDialog();
    }thanks again,
    James

    the reason why you can't get the text is because you are reading the value before some actually inserts anything in any fields.
    Here is what you need to do:
    Create a JDialog/JFrame. Create a JPanel and set that panel as contentPane (dialog.setContentPane(panel)). Insert all the components, ie JLabels and JTextFields. Add two buttons, Login and Cancel to the panel as well. Now get the username and password field values using getText() inside the ActionListener of the Login.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class LoginDialog extends JDialog
    String username, password;
      public LoginDialog( ){
        setTitle( "Login" );
        JPanel content = new JPanel(new GridLayout(0, 2) ); // as many rows, but only 2 columns.
        content.add( new JLabel( "User Name" ) );
        final JTextField nameField = new JTextField( "" );
        content.add( nameField );
        content.add( new JLabel( "Password" ) );
        final JTextField passField = new JTextField( "" );
        content.add( passField );
        JButton login = new JButton( "Login" );
        login.addActionListener( new ActionListener(){
          public void actionPerformed( ActionEvent ae ){
            username = nameField.getText();
            password = passField.getText();
            // call a method or write the code to verify the username and login here...
        content.add( login );
        JButton cancel = new JButton( "Cancel" );
        cancel.addActionListener( new ActionListener( ){
          public void actionPerformed( ActionEvent ae ){
            dispose(); // close the window or write any code that you want here.
        content.add( cancel );
        pack( ); // pack everything in the dialog for display.
        show(); // show the dialog.

  • JTextField and JTextArea don't get focus occuasionally

    I am developing a Java Swing Applet. At edit mode, JComboBox, JCheckBox, JRadioBox, and JButton work fine, but JTextField and JTextArea can't get focus occuasionally while I click them.
    Anyone has idea?
    Thanks

    Thank you Himanshu,
    but that's not exactly what my issue is. This link describes the undesired effect of ending up outisde of the player window and in the browser.
    My problem is kind of the opposite. When I launch the page in the html file I cannot use the tab key to get to any of the controls in the captivate window. I'm stuck in the browser unless I click on the captivate window. That is not acceptable if we want it accessible without using a mouse. I found a way to make it work for chrome like I stated above, but not in FF. Do you have any ideas for this?
    Thanks!
    Monique

  • JPanels and JButtons

    My main file is ExpenseTracker.java. When u
    compile the ExpenseTracker.java , there is a column of buttons on the left
    and a right box. I would like to make the output of the RecordMenu.java
    appear(not pop out) in the right box of my ExoenseTracker when i click one
    of the button 'Record Expenses'. I wonder you can help me in this? I am
    facing that problem right now.=======================================================================
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    public class ExpenseTracker extends JFrame {
    public ExpenseTracker() {
    super("Expense Tracker");
    // FirstPanel
    JPanel FirstPanel = new JPanel();
    FirstPanel.setLayout(null);
    JLabel labeltracker = new JLabel("Expense Tracker");
    JButton recordExpenses = new JButton("Record Expenses");
    JButton viewExpenses = new JButton("View Expenses");
    JButton calendar = new JButton("Calendar" );
    JButton exit = new JButton("Exit");
    labeltracker.setBounds(40,120,135,30);
    recordExpenses.setBounds(25,160,135,30);
    viewExpenses.setBounds(25,210,135,30);
    calendar.setBounds(25,260,135,30);
    exit.setBounds(25,310,135,30);
    FirstPanel.setBounds(5,5,200,500);
    FirstPanel.add(labeltracker);
    FirstPanel.add(recordExpenses);
    FirstPanel.add(viewExpenses);
    FirstPanel.add(calendar);
    FirstPanel.add(exit);
    //SecondPanel
    JPanel SecondPanel = new JPanel();
    SecondPanel.setLayout(new BorderLayout(1,2));
    // SecondPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
    SecondPanel.setBorder(new LineBorder(Color.black));
    SecondPanel.setBounds(210,120,530,270);
    getContentPane().setLayout(null);
    getContentPane().add(FirstPanel);
    getContentPane().add(SecondPanel);
    setSize(800,500);
    setVisible(true);
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    public static void main(String [] args) {
    new ExpenseTracker();
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    public class RecordMenu extends JFrame implements ItemListener,ActionListener {
    >>
    JCheckBox weekly;
    JCheckBox monthly;
    public RecordMenu() {
    super("Choose");
    Container c = getContentPane();
    JPanel checkPanel = new JPanel();
    checkPanel.setLayout(new GridLayout(4,2));
    checkPanel.setBorder(new TitledBorder("Record Expenses"));
    JLabel label2 = new JLabel("Amount to track:");
    JTextField amtField = new JTextField(5);
    //Create the check boxes.
    weekly = new JCheckBox("Weekly");
    weekly.setSelected(false);
    monthly = new JCheckBox("Monthly");
    monthly.setSelected(false);
    //Register a listener for the check boxes.
    weekly.addItemListener(this);
    monthly.addItemListener(this);
    amtField.addActionListener(this);
    //Put the check boxes in a column in a panel
    checkPanel.add(weekly,BorderLayout.NORTH);
    checkPanel.add(monthly,BorderLayout.SOUTH);
    checkPanel.add(label2);
    checkPanel.add(amtField);
    JPanel buttonPanel = new JPanel();
    JButton buttonOk = new JButton("OK");
    JButton buttonCancel = new JButton("Cancel");
    buttonPanel.add(buttonOk);
    buttonPanel.add(buttonCancel);
    c.add(checkPanel,BorderLayout.NORTH);
    c.add(buttonPanel);
    setSize(370,200);
    setVisible(true);
    /** Listens to the check boxes. */
    public void itemStateChanged(ItemEvent event) {
    public static void main(String[] args) {
    new RecordMenu();

    Hi,
    1. When i clicked e 'record expenses' and click 'ok' after that, there will b a JOptionPane that will pop out, i wonder how to make CheckBox.java appear right after the 'ok' button was clicked?
    2. I had also 3 files about creating a calendar.. can you show me how can i make e calendar appear in the right panel when i clicked the 'calendar' in the ExpenseTracker.java?
    As there are many java files, is it possible to make the program work by not putting all codes in a file but calling e codes from another file?
    ================================================================================
    1.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    public class PuttingItTogether {    
    public static void main(String[] args) {   
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(new ExpenseTracker());
    f.setSize(800,500);
    f.setVisible(true);
    class ExpenseTracker extends JPanel implements ActionListener, ItemListener {
         JCheckBox weekly;
         JCheckBox monthly;
         JTextField amtField;
         JButton buttonOk, buttonCancel;
         public ExpenseTracker() {       
         // FirstPanel
         JPanel FirstPanel = new JPanel();
         FirstPanel.setLayout(null);
         JLabel labeltracker = new JLabel("Expense Tracker");
         JButton recordExpenses = new JButton("Record Expenses");
         JButton viewExpenses = new JButton("View Expenses");
         JButton calendar = new JButton("Calendar" );
         JButton exit = new JButton("Exit");
         labeltracker.setBounds(40,120,135,30);
         recordExpenses.setBounds(25,160,135,30);
         viewExpenses.setBounds(25,210,135,30);
         calendar.setBounds(25,260,135,30);
         exit.setBounds(25,310,135,30);
         recordExpenses.setActionCommand("records");
         viewExpenses.setActionCommand("view");
         calendar.setActionCommand("calendar");
         exit.setActionCommand("exit");
         FirstPanel.setBounds(5,5,200,500);
         FirstPanel.add(labeltracker);
         FirstPanel.add(recordExpenses);
         FirstPanel.add(viewExpenses);
         FirstPanel.add(calendar);
         FirstPanel.add(exit);
         // record panel
         JPanel checkPanel = new JPanel();
         checkPanel.setLayout(new GridLayout(4,2));
         checkPanel.setBorder(new TitledBorder("Record Expenses"));
         JLabel label2 = new JLabel("Amount to track:");
         amtField = new JTextField(5);
         //Create the check boxes.
         weekly = new JCheckBox("Weekly");
         weekly.setSelected(false);
         monthly = new JCheckBox("Monthly");
         monthly.setSelected(false);
         //Register a listener for the check boxes.
         weekly.addItemListener(this);
         monthly.addItemListener(this);
         //Put the check boxes in a column in a panel
         checkPanel.add(weekly,BorderLayout.NORTH);
         checkPanel.add(monthly,BorderLayout.SOUTH);
         checkPanel.add(label2);
         checkPanel.add(amtField);
         JPanel buttonPanel = new JPanel();
         buttonOk = new JButton("OK");
         buttonOk.addActionListener(this);
         buttonCancel = new JButton("Cancel");
         buttonCancel.addActionListener(this);
         buttonPanel.add(buttonOk);
         buttonPanel.add(buttonCancel);
         JPanel recordPanel = new JPanel(new BorderLayout());
         recordPanel.add(checkPanel);
         recordPanel.add(buttonPanel, "South");
         //View Expenses panel
         //SecondPanel
         CardLayout cards = new CardLayout();
         JPanel SecondPanel = new JPanel();
         SecondPanel.setLayout(cards);
         SecondPanel.setBorder(new LineBorder(Color.black));
         SecondPanel.setBounds(210,120,530,270);
         JPanel coverPanel = new JPanel();
         SecondPanel.add(coverPanel, "cover");
         SecondPanel.add(recordPanel, "record");
         ButtonListener buttonListener = new ButtonListener(SecondPanel, cards);
         recordExpenses.addActionListener(buttonListener);
         viewExpenses.addActionListener(buttonListener);
         calendar.addActionListener(buttonListener);
         exit.addActionListener(buttonListener);
         setLayout(null);
         add(FirstPanel);
         add(SecondPanel);
         /** * Registered on JButtons buttonOk and buttonCancel */
         public void actionPerformed(ActionEvent e) { 
         String entry = amtField.getText();
    String term = weekly.isSelected() ? "weekly" : "monthly";      
         JButton button = (JButton)e.getSource();
         if(button == buttonOk)
         JOptionPane.showMessageDialog(null, "Total amount to be tracked on a " + term + " basis is $" + entry);
         /** * Listener for JCheckBoxes weekly and monthly. */
         public void itemStateChanged(ItemEvent e) {       
         JCheckBox checkBox = (JCheckBox)e.getSource();
         String stateChange, caller = "";
         if(e.getStateChange() == ItemEvent.SELECTED)
         stateChange = "SELECTED";
         else
         stateChange = "DESELECTED";
         if(checkBox == weekly)
         caller = "weekly";
         if(checkBox == monthly)
         caller = "monthly";
         System.out.println(caller + " " + stateChange);
         /** * Listener for JButtons in ExpenseTracker. */
         class ButtonListener implements ActionListener {    
         JPanel panel;
         CardLayout cards;
         public ButtonListener(JPanel p, CardLayout cl) {       
         panel = p;
         cards = cl;
         public void actionPerformed(ActionEvent e) {       
         JButton button = (JButton)e.getSource();
         String ac = button.getActionCommand();
         if(ac.equals("records"))
         cards.show(panel, "record");
         System.out.println("ac = " + ac);
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.text.DecimalFormat;
    public class CheckBox extends JFrame implements ItemListener, ActionListener {
         private JPanel checkPanel, buttonPanel;
         private     JCheckBox transport, bills, food, gifts, leisure, others;
    private JTextField transportField, billsField, foodField, giftsField,
    leisureField, othersField, totalField;
    double transportAmt, billsAmt, foodAmt, giftsAmt, leisureAmt, othersAmt, totalAmt;
    private JButton buttonTotal, saveButton, dontSaveButton;
    private JLabel showTotal;
    public CheckBox() {
    Container c = getContentPane();
    //create a panel for diaplaying the checkboxs and buttons
    checkPanel = new JPanel();
    checkPanel.setLayout(null);
    //Create the check boxes.
    transport = new JCheckBox("Transport");
    transport.setSelected(false);
    transport.setBounds(10,30,80,30);
    transportField = new JTextField();
    transportField.setEditable(false);
    transportField.setBounds(100,35,45,20);
    bills = new JCheckBox("Bills");
    bills.setSelected(false);
    bills.setBounds(10,60,80,30);
    billsField = new JTextField(5);
    billsField.setEditable(false);
    billsField.setBounds(100,65,45,20);
    food = new JCheckBox("Food");
    food.setSelected(false);
    food.setBounds(10,90,80,30);
    foodField = new JTextField(5);
    foodField.setEditable(false);
    foodField.setBounds(100,95,45,20);
    gifts = new JCheckBox("Gifts");
    gifts.setSelected(false);
    gifts.setBounds(200,30,80,30);
    giftsField = new JTextField(5);
    giftsField.setEditable(false);
    giftsField.setBounds(300,35,45,20);
    leisure = new JCheckBox("Leisure");
    leisure.setSelected(false);
    leisure.setBounds(200,60,80,30);
    leisureField = new JTextField(5);
    leisureField.setEditable(false);
    leisureField.setBounds(300,65,45,20);
    others = new JCheckBox("Others");
    others.setSelected(false);
    others.setBounds(200,90,80,30);
    othersField = new JTextField(5);
    othersField.setEditable(false);
    othersField.setBounds(300,95,45,20);
    //Register a listener for the check boxes.
    transport.addItemListener(this);
    bills.addItemListener(this);
    food.addItemListener(this);
    gifts.addItemListener(this);
    leisure.addItemListener(this);
    others.addItemListener(this);
    transportField.addActionListener(this);
    billsField.addActionListener(this);
    foodField.addActionListener(this);
    giftsField.addActionListener(this);
    leisureField.addActionListener(this);
    othersField.addActionListener(this);
    checkPanel.add(transport);
    checkPanel.add(transportField);
    checkPanel.add(bills);
    checkPanel.add(billsField);
    checkPanel.add(food);
    checkPanel.add(foodField);
    checkPanel.add(gifts);
    checkPanel.add(giftsField);
    checkPanel.add(leisure);
    checkPanel.add(leisureField);
    checkPanel.add(others);
    checkPanel.add(othersField);
    checkPanel.setBounds(1,1,390,180);
    checkPanel.setBorder(new TitledBorder("Check the amount you want to track"));
    buttonTotal = new JButton("Calculate Total");
    buttonTotal.setBounds(150,140,130,30);
    buttonTotal.addActionListener(this);
    showTotal = new JLabel(" = __");
    showTotal.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    showTotal.setBounds(290,140,100,30);
    checkPanel.add(buttonTotal);
    checkPanel.add(showTotal);
    buttonPanel = new JPanel();
    buttonPanel.setLayout(null);
    buttonPanel.setBounds(5,180,200,40);
    saveButton = new JButton("Save");
    saveButton.setBounds(90,190,100,30);
    saveButton.addActionListener(this);
    dontSaveButton = new JButton("Don't Save");
    dontSaveButton.setBounds(200,190,100,30);
    dontSaveButton.addActionListener(this);
    buttonPanel.add(saveButton);
    buttonPanel.add(dontSaveButton);
    c.add(checkPanel);
    c.add(buttonPanel);
    setSize(400,260);
    setVisible(true);
    /** Listens to the check boxes. */
    public void itemStateChanged(ItemEvent e) {          
    if (e.getSource() == transport)
    if (e.getStateChange() == ItemEvent.SELECTED)
    transportField.setEditable(true);
    else
         transportField.setEditable(false);      
    if (e.getSource() == bills)
    if (e.getStateChange() == ItemEvent.SELECTED)
    billsField.setEditable(true);
    else
    billsField.setEditable(false);
    if (e.getSource() == food)
    if (e.getStateChange() == ItemEvent.SELECTED)
    foodField.setEditable(true);
    else
    foodField.setEditable(false);
    if (e.getSource() == gifts)
    if (e.getStateChange() == ItemEvent.SELECTED)
    giftsField.setEditable(true);
    else
    giftsField.setEditable(false);
    if (e.getSource() == leisure)
    if (e.getStateChange() == ItemEvent.SELECTED)
    leisureField.setEditable(true);
    else
    leisureField.setEditable(false);
    if (e.getSource() == others)
    if (e.getStateChange() == ItemEvent.SELECTED)
    othersField.setEditable(true);
    else
    othersField.setEditable(false);
    public void actionPerformed(ActionEvent event) {
         if (event.getSource() == buttonTotal) {
              double transportAmt=0.0, billsAmt=0.0, foodAmt=0.0, giftsAmt=0.0,
              leisureAmt=0.0, othersAmt=0.0, totalAmt=0.0;
    if (!transportField.getText().equals(""))
    transportAmt = Double.parseDouble(transportField.getText());
    if(!billsField.getText().equals(""))
    billsAmt = Double.parseDouble(billsField.getText());
    if(!foodField.getText().equals(""))
    foodAmt = Double.parseDouble(foodField.getText());
    if(!giftsField.getText().equals(""))
    giftsAmt = Double.parseDouble(giftsField.getText());
    if(!leisureField.getText().equals(""))
    leisureAmt = Double.parseDouble(leisureField.getText());
    if(!othersField.getText().equals(""))
    othersAmt = Double.parseDouble(othersField.getText());
    totalAmt = transportAmt + billsAmt + foodAmt + giftsAmt + leisureAmt + othersAmt;
    showTotal.setText("= $" + totalAmt);
    if (event.getSource() == dontSaveButton) {
         System.exit(0);
    public static void main(String[] args) {
    new CheckBox();
    =========================================================================
    2.
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.*;
    import java.util.*;
    import javax.swing.*;
    public class Demo extends JFrame implements PropertyChangeListener
    private DateButton startDateButton;
    private DateButton endDateButton;
    private Date startDate;
    private Date endDate;
    private Demo() {
         super( "DateChooser demo" );
         addWindowListener
         new WindowAdapter() {
              public void windowClosing( WindowEvent e ) {
                   System.exit( 0 );
         startDate = new Date();
         endDate = new Date();
         startDateButton = new DateButton();
         startDateButton.addPropertyChangeListener( "date", this );
         endDateButton = new DateButton();
         endDateButton.addPropertyChangeListener( "date", this );
         getContentPane().setLayout( new GridLayout(2,2) );
         getContentPane().add( new JLabel("Start date") );
         getContentPane().add( startDateButton );
         getContentPane().add( new JLabel("End date") );
         getContentPane().add( endDateButton );
         pack();
         setResizable( false );
    public void propertyChange( PropertyChangeEvent e ) {
         DateButton db = (DateButton)e.getSource();
         if ( db == startDateButton )
         System.out.print( "Start date changed: " );
         else
         System.out.print( "End date changed: " );
         System.out.println( db.getDate() );
    public static void main( String[] args ) {
         (new Demo()).show();
    import java.awt.event.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    * Custom button for entering dates. The <code>DateButton</code> class
    * is just a standard button that defines an additional bound
    * property: "date". The button displays the date property as its
    * label. When clicked, it does not generate an
    * <code>ActionEvent</code>, but displays a {@link DateChooser} dialog
    * instead, that allows you to change the date. When the date is
    * changed, a <code>PropertyChangeEvent</code> is generated, according
    * the contract for bound properties.
    public class DateButton extends JButton
    /** Format to use to display the date property. */
    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd-yyyy");
    /** DateChooser instance to use to change the date. */
    private static final DateChooser DATE_CHOOSER = new DateChooser((JFrame)null,"Select Date");
    /** Date property. */
    private Date date;
    * Called when the button is clicked, in order to fire an
    * <code>ActionEvent</code>. Displays the dialog to change the
    * date instead of generating the event and updates the date
    * property.
    * @param e <code>ActionEvent</code> to fire
    protected void fireActionPerformed( ActionEvent e ) {
         Date newDate = DATE_CHOOSER.select(date);
         if ( newDate == null )
         return;
         setDate( newDate );
    * Constructs a new <code>DateButton</code> object with a given
    * date.
    * @param date initial date
    public DateButton( Date date ) {
         super( DATE_FORMAT.format(date) );
         this.date = date;
    * Constructs a new <code>DateButton</code> object with the system
    * date as the initial date.
    public DateButton() {
         this( new Date() );
    * Gets the value of the date property.
    * @return the current value of the date property
    public Date getDate() {
         return date;
    * Sets the valus of the date property.
    * @param date new value of the date property
    * @return the old value of the date property
    public void setDate( Date date ) {
         Date old = this.date;
         this.date = date;
         setText( DATE_FORMAT.format(date) );
         firePropertyChange( "date", old, date );
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    * Custom dialog box to enter dates. The <code>DateChooser</code>
    * class presents a calendar and allows the user to visually select a
    * day, month and year so that it is impossible to enter an invalid
    * date.
    public class DateChooser extends JDialog
    implements ItemListener, MouseListener, FocusListener, KeyListener, ActionListener
    /** Names of the months. */
    private static final String[] MONTHS =
         new String[] {
         "January",
         "February",
         "March",
         "April",
         "May",
         "June",
         "July",
         "August",
         "September",
         "October",
         "November",
         "December"
    /** Names of the days of the week. */
    private static final String[] DAYS =
         new String[] {
         "Sun",
         "Mon",
         "Tue",
         "Wed",
         "Thu",
         "Fri",
         "Sat"
    /** Text color of the days of the weeks, used as column headers in
    the calendar. */
    private static final Color WEEK_DAYS_FOREGROUND = Color.black;
    /** Text color of the days' numbers in the calendar. */
    private static final Color DAYS_FOREGROUND = Color.blue;
    /** Background color of the selected day in the calendar. */
    private static final Color SELECTED_DAY_FOREGROUND = Color.white;
    /** Text color of the selected day in the calendar. */
    private static final Color SELECTED_DAY_BACKGROUND = Color.blue;
    /** Empty border, used when the calendar does not have the focus. */
    private static final Border EMPTY_BORDER = BorderFactory.createEmptyBorder(1,1,1,1);
    /** Border used to highlight the selected day when the calendar
    has the focus. */
    private static final Border FOCUSED_BORDER = BorderFactory.createLineBorder(Color.yellow,1);
    /** First year that can be selected. */
    private static final int FIRST_YEAR = 1900;
    /** Last year that can be selected. */
    private static final int LAST_YEAR = 2100;
    /** Auxiliary variable to compute dates. */
    private GregorianCalendar calendar;
    /** Calendar, as a matrix of labels. The first row represents the
    first week of the month, the second row, the second week, and
    so on. Each column represents a day of the week, the first is
    Sunday, and the last is Saturday. The label's text is the
    number of the corresponding day. */
    private JLabel[][] days;
    /** Day selection control. It is just a panel that can receive the
    focus. The actual user interaction is driven by the
    <code>DateChooser</code> class. */
    private FocusablePanel daysGrid;
    /** Month selection control. */
    private JComboBox month;
    /** Year selection control. */
    private JComboBox year;
    /** "Ok" button. */
    private JButton ok;
    /** "Cancel" button. */
    private JButton cancel;
    /** Day of the week (0=Sunday) corresponding to the first day of
    the selected month. Used to calculate the position, in the
    calendar ({@link #days}), corresponding to a given day. */
    private int offset;
    /** Last day of the selected month. */
    private int lastDay;
    /** Selected day. */
    private JLabel day;
    /** <code>true</code> if the "Ok" button was clicked to close the
    dialog box, <code>false</code> otherwise. */
    private boolean okClicked;
    * Custom panel that can receive the focus. Used to implement the
    * calendar control.
    private static class FocusablePanel extends JPanel
         * Constructs a new <code>FocusablePanel</code> with the given
         * layout manager.
         * @param layout layout manager
         public FocusablePanel( LayoutManager layout ) {
         super( layout );
         * Always returns <code>true</code>, since
         * <code>FocusablePanel</code> can receive the focus.
         * @return <code>true</code>
         public boolean isFocusTraversable() {
         return true;
    * Initializes this <code>DateChooser</code> object. Creates the
    * controls, registers listeners and initializes the dialog box.
    private void construct()
         calendar = new GregorianCalendar();
         month = new JComboBox(MONTHS);
         month.addItemListener( this );
         year = new JComboBox();
         for ( int i=FIRST_YEAR; i<=LAST_YEAR; i++ )
         year.addItem( Integer.toString(i) );
         year.addItemListener( this );
         days = new JLabel[7][7];
         for ( int i=0; i<7; i++ ) {
         days[0] = new JLabel(DAYS[i],JLabel.RIGHT);
         days[0][i].setForeground( WEEK_DAYS_FOREGROUND );
         for ( int i=1; i<7; i++ )
         for ( int j=0; j<7; j++ )
              days[i][j] = new JLabel(" ",JLabel.RIGHT);
              days[i][j].setForeground( DAYS_FOREGROUND );
              days[i][j].setBackground( SELECTED_DAY_BACKGROUND );
              days[i][j].setBorder( EMPTY_BORDER );
              days[i][j].addMouseListener( this );
         ok = new JButton("Ok");
         ok.addActionListener( this );
         cancel = new JButton("Cancel");
         cancel.addActionListener( this );
         JPanel monthYear = new JPanel();
         monthYear.add( month );
         monthYear.add( year );
         daysGrid = new FocusablePanel(new GridLayout(7,7,5,0));
         daysGrid.addFocusListener( this );
         daysGrid.addKeyListener( this );
         for ( int i=0; i<7; i++ )
         for ( int j=0; j<7; j++ )
              daysGrid.add( days[i][j] );
         daysGrid.setBackground( Color.white );
         daysGrid.setBorder( BorderFactory.createLoweredBevelBorder() );
         JPanel daysPanel = new JPanel();
         daysPanel.add( daysGrid );
         JPanel buttons = new JPanel();
         buttons.add( ok );
         buttons.add( cancel );
         Container dialog = getContentPane();
         dialog.add( "North", monthYear );
         dialog.add( "Center", daysPanel );
         dialog.add( "South", buttons );
         pack();
         setResizable( false );
    * Gets the selected day, as an <code>int</code>. Parses the text
    * of the selected label in the calendar to get the day.
    * @return the selected day or -1 if there is no day selected
    private int getSelectedDay()
         if ( day == null )
         return -1 ;
         try {
         return Integer.parseInt(day.getText());
         } catch ( NumberFormatException e ) {
         return -1;
    * Sets the selected day. The day is specified as the label
    * control, in the calendar, corresponding to the day to select.
    * @param newDay day to select
    private void setSelected( JLabel newDay )
         if ( day != null ) {
         day.setForeground( DAYS_FOREGROUND );
         day.setOpaque( false );
         day.setBorder( EMPTY_BORDER );
         day = newDay;
         day.setForeground( SELECTED_DAY_FOREGROUND );
         day.setOpaque( true );
         if ( daysGrid.hasFocus() )
         day.setBorder( FOCUSED_BORDER );
    * Sets the selected day. The day is specified as the number of
    * the day, in the month, to selected. The function compute the
    * corresponding control to select.
    * @param newDay day to select
    private void setSelected( int newDay )
         setSelected( days[(newDay+offset-1)/7+1][(newDay+offset-1)%7] );
    * Updates the calendar. This function updates the calendar panel
    * to reflect the month and year selected. It keeps the same day
    * of the month that was selected, except if it is beyond the last
    * day of the month. In this case, the last day of the month is
    * selected.
    private void update()
         int iday = getSelectedDay();
         for ( int i=0; i<7; i++ ) {
         days[1][i].setText( " " );
         days[5][i].setText( " " );
         days[6][i].setText( " " );
         calendar.set( Calendar.DATE, 1 );
         calendar.set( Calendar.MONTH, month.getSelectedIndex()+Calendar.JANUARY );
         calendar.set( Calendar.YEAR, year.getSelectedIndex()+FIRST_YEAR );
         offset = calendar.get(Calendar.DAY_OF_WEEK)-Calendar.SUNDAY;
         lastDay = calendar.getActualMaximum(Calendar.DATE);
         for ( int i=0; i<lastDay; i++ )
         days[(i+offset)/7+1][(i+offset)%7].setText( String.valueOf(i+1) );
         if ( iday != -1 ) {
         if ( iday > lastDay )
              iday = lastDay;
         setSelected( iday );
    * Called when the "Ok" button is pressed. Just sets a flag and
    * hides the dialog box.
    public void actionPerformed( ActionEvent e ) {
         if ( e.getSource() == ok )
         okClicked = true;
         hide();
    * Called when the calendar gains the focus. Just re-sets the
    * selected day so that it is redrawn with the border that
    * indicate focus.
    public void focusGained( FocusEvent e ) {
         setSelected( day );
    * Called when the calendar loses the focus. Just re-sets the
    * selected day so that it is redrawn without the border that
    * indicate focus.
    public void focusLost( FocusEvent e ) {
         setSelected( day );
    * Called when a new month or year is selected. Updates the calendar
    * to reflect the selection.
    public void itemStateChanged( ItemEvent e ) {
         update();
    * Called when a key is pressed and the calendar has the
    * focus. Handles the arrow keys so that the user can select a day
    * using the keyboard.
    public void keyPressed( KeyEvent e ) {
         int iday = getSelectedDay();
         switch ( e.getKeyCode() ) {
         case KeyEvent.VK_LEFT:
         if ( iday > 1 )
              setSelected( iday-1 );
         break;
         case KeyEvent.VK_RIGHT:
         if ( iday < lastDay )
              setSelected( iday+1 );
         break;
         case KeyEvent.VK_UP:
         if ( iday > 7 )
              setSelected( iday-7 );
         break;
         case KeyEvent.VK_DOWN:
         if ( iday <= lastDay-7 )
              setSelected( iday+7 );
         break;
    * Called when the mouse is clicked on a day in the
    * calendar. Selects the clicked day.
    public void mouseClicked( MouseEvent e ) {
         JLabel day = (JLabel)e.getSource();
         if ( !day.getText().equals(" ") )
         setSelected( day );
         daysGrid.requestFocus();
    public void keyReleased( KeyEvent e ) {}
    public void keyTyped( KeyEvent e ) {}
    public void mouseEntered( MouseEvent e ) {}
    public void mouseExited( MouseEvent e) {}
    public void mousePressed( MouseEvent e ) {}
    public void mouseReleased( MouseEvent e) {}
    * Constructs a new <code>DateChooser</code> with the given title.
    * @param owner owner dialog
    * @param title dialog title
    public DateChooser( Dialog owner, String title )
         super( owner, title, true );
         construct();
    * Constructs a new <code>DateChooser</code>.
    * @param owner owner dialog
    public DateChooser( Dialog owner )
         super( owner, true );
         construct();
    * Constructs a new <code>DateChooser</code> with the given title.
    * @param owner owner frame
    * @param title

  • JtextField and list of data

    Hi everyone (and sorry for my english language....).
    I've this problem:
    I've a Frame with a JtextField and a button. When I click on this button, I want to show a list of data from a database and then I must choose a value that must go to the JtextField.
    Have you an idea how I can implement this? Sorry for this generic question, but I don't know how to do..
    Thank you!

    >
    As to your question.
    I've a Frame with a JtextField and a button. When I click on this button, I want to show a list of data from a database and then I must choose a value that must go to the JtextField.
    Have you an idea how I can implement this? ..Sure, plenty of people. But they will want to know exactly what you are having trouble with. E.G.
    - Getting data from a DB.
    - Putting data into a JList.
    - Adding listeners to that JList so that choices are acted on, rather than simply high-lighted as the selection.
    - Using the event provided to the listener, to update the JTextField.
    - Adding a JTextField and JList to a JFrame using layout managers.
    If your answer is 'all of that', then I suspect they would be tempted to:
    a) Advise you to put this project aside until you have considerably more experience.
    b) Refer you to the [Java Tutorial|http://java.sun.com/docs/books/tutorial/].

  • JTextField and JPasswordField

    Hi!
    How do I limit the character number that can be inserted into a JtextField and JPasswordField.
    For examen is the Password can be mam 6 characters, how do I do from limit the input?
    Thanks

    The most common way to limit what is entered in a JTextField is to create your own document. See the following thread:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=414464
    Graeme

  • JTextField and TextListener

    I am using an JTextField and I want to be notified when the text there have been changed. But there is no TextListener accessible in JTextField. Do I have to modify a CaretListener ?
    many Thanks/ Sam

    I am using an JTextField and I want to be notified
    when the text there have been changed. But there is no
    TextListener accessible in JTextField. Do I have to
    modify a CaretListener ?DocumentListener.

  • JTextField and transparency

    I have a JTextField and I am trying to set it up so it is somewhat transparent.
    mTextField.setBackground(new Color(255,255,255,50));
    But what happens when i do that is this: the textfield as a text value gets the text that i have set up for one of the neighbouring components.
    I am not sure why this happens.
    Has anyone experienced this problem before? Is there a fix to it?
    I tried setting up the text using setText to an empty string but it happens agian. I dont have this problem when the transparency is Not set.
    Cheers
    Dan

    I am not sure why this happens. An opaque component is responsible for painting the entire area of the component, which basically means that the RepaintManager doesnt' have to worry about the garbage that may exist where the component is about to be repainted.
    Since you background is somewhat transparent, you can see the garbage left behind. (Don't ask me what its left behind from, thats in the details of the Swing repaint manager which I know nothing about).
    Michaels suggestion makes the component transparent which means Swing will paint the background of the components parent. However when you do this, the background of your component isn't painted.
    So heres a solution that paints the background of the parent and the child:
    JTextField textField = new JTextField("Some Text")
         protected void paintComponent(Graphics g)
              g.setColor( getBackground() );
              g.fillRect(0, 0, getSize().width, getSize().height);
              super.paintComponent( g );
    textField.setBackground(new Color(0, 255, 255, 50));
    textField.setOpaque( false );

  • Accelerators, JTextField, and focus

    I created a JMenuItem for Save. I also created an accelerator for the Save menu item.
    JMenuItem saveItem;
    JMenu fileMenu = new JMenu ("File");
    fileMenu.add (saveItem = new JMenuItem ("Save"));
    saveItem.setMnemonic ('S');
    KeyStroke cntrlS = KeyStroke.getKeyStroke(KeyEvent.VK_S,
    Event.CTRL_MASK);
    saveItem.setAccelerator (cntrlS);
    saveItem.addActionListener (new ActionListener() {
    public void actionPerformed (ActionEvent e) {
    doSaveNote();
    When the user is finished entering data into the JTextField(s), the user then either presses ctrl-S or clicks on the Save button on the menu. My code (not shown) validates data in JTextFields when the Save accelerator or button is pressed (blank field is considered invalid as well as wrong flight number). If data is invalid, then the first field with invalid data gets focus.
    If the JTextField has focus and invalid data is there, then when the user clicks the Save button the JTextField still has focus with a message letting the user know the data is invalid. However, if the user puts invalid data in the JTextField and uses the accelerator ctrl-S without tabbing out of the field first, the invalid JTextField does not get focus and no error message is presented. When using the accelerator the invalid JTextField only gets focus and prints an error message if the user tabs out of the JTextField befor pressing ctrl-S.
    I don't want to tab out of the field. Why is the behavior different between the accelerator and clicking the Save button? Any help is appreciated.

    You can request focus for another component.
    Or you could do: myTextField.setFocusable(false). But in this case you would have to make it fosucable later on if you want to use it.

  • JTextField [] and MouseEntered

    Hello
    I know this type of question has been asked in the forums before, but might is kind of different...i think.
    I have an array of JTextFields and i want each of there color to turn to GRAY when the mouse is on top of them.
    So if mouse is on top of TextField1 then only TextField1 turns GRAY.
    my Current mouseEntered() method is this
    public void mouseEntered(MouseEvent me)
                 for (int i=0; i < nasdaqTFs.length; i++){
                nasdaqTFs.setEditable(false);
              nasdaqTFs[i].setBackground(Color.GRAY);
    This, obviously, turns ALL the TextFields to GRAY when the cursor is in the Panel. So cursor can be anywhere and they all turn GRAY.
    So the question is...how do i find out when the Cursor is on the Specific TextField.

    Learning from earlier today This time i did write a Short Example of what i want done.
    Maybe this time i didnt do a bad job at it
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Listener extends JFrame implements MouseListener
         JTextField t;
         JTextField t1;
         public Listener ()
              super ("test");
              Container c = getContentPane();
              c.setLayout(new BorderLayout());
              t = new JTextField(4);
              c.add(t, BorderLayout.NORTH);
              t1 = new JTextField (4);
              c.add(t1, BorderLayout.SOUTH);
              addMouseListener(this);
              setVisible(true);
              setSize(300,300);
              MouseMotionListener don = new MouseMotionAdapter(){
              public void mouseEntered(MouseEvent me) {
                   System.out.println("Enterd)");
                 me.getComponent().setBackground(Color.GRAY);
              t.addMouseMotionListener(don);
              t1.addMouseMotionListener(don);
         public static void main (String args[])
              Listener l = new Listener ();
           public void mouseEntered(MouseEvent me)
             /*JTextField tf = (JTextField) me.getSource();
             tf.setBackground(Color.GREEN);*/
                me.getComponent().setBackground(Color.GREEN);
           public void mouseExited(MouseEvent me)
             /*JTextField tf = (JTextField) me.getSource();
             tf.setBackground(Color.white);*/
                me.getComponent().setBackground(Color.WHITE);
           public void mousePressed(MouseEvent me){}
           public void mouseReleased(MouseEvent me){}
           public void mouseClicked(MouseEvent me){}
    }This GUI wont change colors of TF's either. However when i move around the GUI i see somethin Green flickering!

Maybe you are looking for

  • How to transfer files (word,pdf) from my laptop to iphone5?

    how to transfer files (word,pdf) from my laptop to iphone5?

  • JCO_COMMUNICATION_FAILURE

    Can anybody explain the cause of this error and how to fix it? <SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="1">   <SAP:Category>XIServer</SAP:Category>   <SAP:Code

  • Problem with 2 computers Airport network

    While long time comfortable with Mac, I am novice with Airport/network. I have a MacMini (with Airport card) and a new PowerBookPro (15" 2.2 Intel Core 2 Duo and Airport card). I have new Airport Extreme Base device and I have successfully set up wir

  • Deleting modified/original images

    I had a question earlier for how to delete original pictures after I had rotated them, but today I found out that pictures that I had deleted from the library (cause I didn't want them) still are in the iPhoto folder! My camera automatically rotates

  • "Back to my Mac" computer does't appear in finder's "Shared"

    Hi, I have my iMac at the office and a Macbook Air at home. Sometimes, I can access the iMac from home via the "Shared" section in the finder on the left. Sometimes I can't. But I always can access it via SSH. I conclude, the computer is not asleep a