My own JTextField

In a fitness database that I am developing I am hoping to have a JTextField that the user can enter the duration of their workout. I want the format to be preset to 00:00, and the user would just enter in number that would fill in accordingly.
Should I write my own class that extends JTextField or is there a better way to do this?
Thanks in advance for any input!

Thank you for your timely response. Despite my username disclaimer, I feel foolish for not having found that myself!
Anyway, as expected, I have run into some problems now with the JFormattedTextField. Here is the relevant code:
class WorkoutDefPanel extends JPanel
    MaskFormatter mf = new MaskFormatter();
    JFormattedTextField woDur = new JFormattedTextField(mf);
    public WorkoutDefPanel()
     woDur.setLocation((int)(frameW * 0.28),(int)(frameH * 0.25));
     woDur.setSize((int)(frameW * 0.06),(int)(frameH * 0.05));
     //duration text field's input mask
     try{
         mf.setMask("#:##");
         mf.setPlaceholderCharacter('0');
         mf.setValueContainsLiteralCharacters(false);
     }catch(ParseException ex){}
     add(woDur);
    //this is called from my JFrame class when the user selects a "LOG" button
    public void log()
     int t = 0;
     try{
         mf.commitEdit();
         t = Integer.parseInt(mf.valueToString(woDur.getValue()));
     }catch(ParseException ex){}
     int d = ((t/100)*60)+(t % 100);
     Workout nw = new Workout(d);
}I am getting a NumberFormatException at t = Integer.parseInt(mf.valueToString(woDur.getValue()));Also, strangely, the value which throws the exception is 0:00 even after it has been edited. The value only changes to the edited value once enter is pressed, but I still get the runtime exception.
Any thoughts?
Appreciated,
Jeremy

Similar Messages

  • Problems creating my own JTextField

    i'm trying to write my own textfield that will get a string of the following format: 1-4 digits, "/", 2 digits.
    so I wrote a new class, but it doesn't work at all.
    help, please.
    package union.General;
    import javax.swing.*;
    import javax.swing.text.*;
    import union.Entities.UnionCase.*;
    public class JOfficeCaseIdField
    extends JTextField {
    public JOfficeCaseIdField() {
    setText(" / ");
    protected Document createDefaultModel() {
    return new JOfficeCaseIdDocument();
    protected class JOfficeCaseIdDocument extends PlainDocument {
    public void insertString(int offs, String str, AttributeSet a) throws
    BadLocationException {
    char[] source = str.toCharArray();
    char[] result = new char[7];
    int j = 0;
    for (j=0; j<result.length; j++) {
    result[j] = ' ';
    j=0;
    for (int i = 0; i < source.length && j<result.length; i++) {
    if (offs + j == 4) {
    j++;
    if (Character.isDigit(source))
    result[j++] = source[i];
    else {
    //invalid character '/' is done by this document and the user should only enter digits
    result[4] = '/';
    super.insertString(offs, new String(result, 0, j), a);

    how bout this, why doesn't this work well?
    static final private int DASH_PLACE_FROM_END = 3;
    static final private int MAX_STRING = 7;
    static final private char DASH_CHAR = '/';
    static final private String DASH_STRING = new String(new char[] {DASH_CHAR}); //the string "/"
    protected class JOfficeCaseIdDocument extends PlainDocument {
    public void insertString(int offs, String str, AttributeSet a) throws
    BadLocationException {
    char[] source = str.toCharArray();
    char[] target = new char[str.length()];
    int finalLength = 0;
    for (int i=0; i<source.length; i++) {
    if (Character.isDigit(source)) {
    target[finalLength++] = source[i];
    String mainString = new String(target,0,finalLength);
    String oldText = getText(0,getLength());
    String newInsertString;
    this.remove(0,getLength());
    newInsertString = oldText;
    String firstString = "";
    String lastString = "";
    if (offs > 0 ) {
    firstString = newInsertString.substring(0,offs);
    if (offs<newInsertString.length()) {
    lastString = newInsertString.substring(offs,newInsertString.length());
    newInsertString =
    firstString +
    mainString +
    lastString;
    newInsertString.replaceAll(DASH_STRING,"");
    if (newInsertString.length() >= DASH_PLACE_FROM_END) {
    newInsertString =
    newInsertString.substring(0,newInsertString.length()-DASH_PLACE_FROM_END) +
    DASH_STRING +
    newInsertString.substring(newInsertString.length()-DASH_PLACE_FROM_END+1,
    newInsertString.length()-1);
    super.insertString(0, newInsertString, a);

  • How can i create my own component

    hello all,
    how can i create my own componet,
    say for example i want to create my own JTextField.
    give me links, or give me a examples
    thanks
    daya

    http://www.onjava.com/pub/a/onjava/2004/08/11/desktop.html

  • Trying to write an if statement around the return value of a CANCEL_OPTION

    I am writing a program that takes an input String using JOptionPane. The String can be made of only letters of the A-Z alphabet and the space character. I have written an error-checking loop that will pop another input box up along with an error message if any invalid character is detected. The input box has an 'ok' button and a 'cancel' button. As it is, if you hit cancel, the program crashes and you get a NullPointerException. All I want to do is place an if statement inside of the error-checking loop, immediatly after the code to pop up the second input box, that simply does System.exit() and exits the program correctly(rather than crashing) if 'cancel' is clicked.
    My attempt at such an if statement is visible in the following code(letter is a boolean variable defined earlier, and message is the input String that has already been read in):
                   letter = isValidMessage(message);
              while(!letter)
                   message = JOptionPane.showInputDialog(null, "Message must contain only A-Z, a-z, or space character...");
                            if(JOptionPane.CANCEL_OPTION > 0  //or ==0 or ==1 or ==2, nothing works//)
                                JOptionPane.showMessageDialog(null, "No valid message entered - program will terminate...");
                                System.exit(JOptionPane.CANCEL_OPTION);
                   letter = isValidMessage(message);
                    }The if statement doesn't work correctly. If you click 'cancel' when the input box comes up, the program does terminate as it is supposed to. The problem is that if I type something in the box and click 'ok', it also causes the program to terminate rather than continuing. I've tried changing the > to ==. I've tried changing 0 to 1 to 2 to -1(I really am not sure which int return value of CANCEL_OPTION corresponds to which event). I think once I got to do the exact opposite...that is to say, it would continue on with the program whether I clicked 'cancel' or 'ok'. Which is equally bad. I don't know what I'm doing wrong.
    It's probably something simple that I'm just overlooking.

    Well, here's what CANCEL_OPTION is, according to the JOptionPane class:
    /** Return value from class method if CANCEL is chosen. */
        public static final int         CANCEL_OPTION = 2;However, I believe you're going about this in the wrong way.
    With JOptionPane, whenever you show a dialog, it usually returns whatever OPTION the user chose.
    For instance,
        int choice = JOptionPane.showConfirmDialog(parentComponent, "hello");That will bring up a dialog centered on parentComponent, with a message of "hello".
    It will have the default options (YES_NO_OPTION).
    What it returns is the option the user chose.
    There are 4 possible things it can return:
    YES_OPTION, when user clicks "Yes"
    NO_OPTION, when user clicks "No"
    ERROR_OPTION, when an unforseen error occurs and the dialog closes
    CANCEL_OPTION, when the user clicks "Cancel" (if that OPTION type were being used), or if they close the dialog
    So this is how you would check for CANCEL_OPTION:
        int choice = JOptionPane.showConfirmDialog(parentComponent, "hello");
        if (choice == JOptionPane.CANCEL_OPTION) {
            // User cancelled
        else if (choice == JOptionPane.YES_OPTION) {
            // User chose yes
        // EtcSo you see, going about it like this:
    if(JOptionPane.CANCEL_OPTION > 0  //or ==0 or ==1 or ==2, nothing works//)Is really the wrong way, because you're not checking what the user DID, but just what the constant variable "CANCEL_OPTION" is.
    However, it seems as if you're in a unique situation where you don't want the OPTION chosen by the user, but an input String.
    This is all well and good, but I think this limits how you can interact with the user, as the "showInputDialog" methods return the String the user input- not the OPTION they chose, and you need to use both.
    What I've done in the past is created a simple JPanel with its own JTextField.
    I pass the JPanel in as the "message" parameter of a showConfirmDialog call, and get both the user input and their chosen OPTION based off a getText call to the JTextField and the OPTION constant returned by showConfirmDialog.
    Basically,
    JPanel promptPanel = new JPanel(new BorderLayout());
    JTextField promptField = new JTextField();
    promptPanel.add(promptField, BorderLayout.CENTER);
    int choice = JOptionPane.showConfirmDialog(parentComponent, promptPanel, "Input", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
    if (choice == JOptionPane.OK_OPTION) {
       // User chose OK, see if invalid characters were entered
       String input = promptField.getText();
    else if (choice == JOptionPane.CANCEL_OPTION) {
       // User cancelled
    }Hope that helps.
    (note that I'm unsure if showConfirmDialog can accept OK_CANCEL_OPTION as its OPTION parameter, as it says only YES_NO_OPTION and YES_NO_CANCEL_OPTION can be used, but I seem to remember using it in the past. if OK_CANCEL_OPTION doesn't want to work, then use one of the other two and adjust your if statements accordingly)
    Cheers!
    Edited by: LukeFoss on Oct 9, 2007 10:39 PM

  • How can I add action listener to a cell or row in a table?

    hi there
    I need to be able to click on one cell or one row in a table, and perform some action, like openning a dialog or something. how can i add listener?

    // See How to Use Tables in tutorial. You will get one idea about Table Renderer and Editors.
    // If u understand the concept, ur problem is very easy to solve by adding Editor to your column.
    "You can think of the renderer as a configurable ink stamp that the table uses to stamp appropriately formatted data onto each cell. When the user starts to edit a cell's data, a cell editor takes over the cell, controlling the cell's editing behavior.
    Here, While tabing thru the table row, default all cell editors are JLabels. (Not editables)
    So u can make it those cells are editable JTextFields or JComboBoxes based on the column while tabbing. And you can add Listeners to that fields too. So those editable fields are called Editor Components.
    // see javax.swing.DefaultCellEditor class for more description
    Here i am adding my own JTextField editor to 3rd column of a table by using
    mytable.getColumnModel().getColumn(2).setCellEditor(editor );
    Here editor is a obj of below class. (Not complete..class)
    public class JbuiEditor extends DefaultCellEditor implements // any listener {
    public JbuiEditor(JTextField tField) {
    super(tField);
    setClickCountToStart(1);
    tField.addFocusListener(this);
    this.editorComponent = tField;
    public Component getComponent(){
         return editorComponent;
    public Component getTreeCellEditorComponent(JTree tree, Object value,
                                  boolean isSelected,
                                  boolean expanded,
                                  boolean leaf, int row) {
         String StringValue = tree.convertValueToText(value, isSelected,
                             expanded, leaf, row, false);
         delegate.setValue(stringValue);
         return editorComponent;
    public Object getCellEditorValue() {
    return super.getCellEditorValue();
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,int row, int column) {
    super.getTableCellEditorComponent(table,value,isSelected,row,column);
    ((JTextField)editorComponent).setText(value.toString());
    //Here u can add any type of listener to this Editor component.like..
    ((JTextField)editorComponent).addActionListener(..);
    ((JTextField)editorComponent).addFocusListener(..);
    return editorComponent;
    Hope gives some idea.

  • I/o streams reading each character for analizise????

    i was wondering if anyone can explain or give me sample code for the following...
    id like to get user input for four numbers, each number has its own JTextfield....( i have managed this) but id like to test to see if the numbers are already in a text file and if so to relay a msg back saying security code in use....(or of sort) but if the code isnt there id like it to add it to the text file.......so is this possible, for instance if the "data.txt" file was somethng like this
    12,99,05,23
    22,44,11,01
    and the user enters say 12,99,05,23
    how would i be able to check the first digit 12 with the file then 99 and so on until its the end of file...
    my basic or practise application is done using the swing api so i cant use system.out.println for the return response, however i have made a very good error class which works fine on reading files....im just stuck with verifying the numbers then i read something about using a delimiter file or comma delimiter and then completely lost the plot...
    somehow this comma delimiter thingo has to fit into it to read each digit...from comma to comma but how does it all go together...
    any help or guidence will be appreicated....
    regard alex

    Read a line from the file with a BufferedReader. Use String.split() to break up the line into the individual number strings. (At the next person suggesting to use StringTokenizer instead: read the part of the ST's API to see that its use is discouraged.)
    Use Integer.parseInt() to read each number string and to convert it to an int. Then you can compare it to your values.

  • Reading data from a text file into a JTextField

    So I am writing a program that will write to and read from a large database. I was hoping to allow a graphical interface for the reading of the data, but I keep getting an error;
    Incompatible Types
    Found: java.lang.string
    Required: javax.swing.JTextField
    Now I know that this means the are incompatible (like trying to give an integer variable a string command) but I can't find any documentation on how to change the String into a JTextField format. I've found several references on how to do the reverse, but with my lack of JAVA knowledge I can't seem to get it to work. (Tried things like getText() and the like, but just end up with more errors).
    *On a side note, is there an easier way to go about reading a file line by line, with each line going into a seperate JTextField, than;
    BufferedReader r;
    try {
    r = new BufferedReader(new FileReader("C:\\temp\\test.txt"));
    while ((thisLine = r.readLine()) != null) {
    array[i] = thisLine;
    i = i + 1
    and then assigning each JTextField it's own array slot?*
    Thank you for your help.

    Try something like this for putting the text in a control:
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    public class Junk{
      String[] s = {"This is String 1.", "This is String 2.", "This is String 3."};
      Junk(){
      public void makeIt(){
        JFrame j = new JFrame("Forum Junk");
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel p = new JPanel();
        p.setPreferredSize(new Dimension(300, 200));
        JTextArea jt = new JTextArea();
        p.add(jt);
        j.add(p);
        jt.setText(s[0]);
        jt.append("\n\r"+s[1]);
        jt.append("\n\r"+s[2]);
        j.pack();
        j.setVisible(true);
      public static void main(String[] args) {
        Junk j = new Junk();
        j.makeIt();
    }Depending on your design you may be able to do away with your array and append the text directly to the JTextArray after each line is read.

  • How to bind JtextFields in Swing to Table fields in the database

    Can some one give the code of how to bind JtextFields in Swing to Table fields in the database
    Am really new to java programming and have interest in learning

    The standard JDK doesn't do this for you. If you search on Google, you may find some 3rd party packages that will do this.
    You need to create your own form add execute the appropriate SQL yourself. Read the tutorial on [url http://java.sun.com/docs/books/tutorial/]JDBC Database Access to get started.

  • 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

  • Max number of characters in a JTextField

    I don't want to alowe more than 4 characters in a JTextField.
    Is where any method in Java corresponding to maxlength for textbox in Visual Basic??
    Or do I have to use KeyListener to check the situation for every key pressed?
    I'll be thankful for any help.

    write your own document & override the insertString() like the one below:
    import javax.swing.text.*;
    public class MyDocument extends PlainDocument {
         public void insertString(int offs, String s, AttributeSet a)
                                                          throws BadLocationException {
              if(getLength() > 4)
              //if(offs > 3)
              //if(getText(0, getLength()).length() > 4)
                   return;
              else
                   super.insertString(offs, s, a);            
    }

  • Validation in JTextField

    Hi ,
    I have a JTextField, a JComboBox , a JButton , a JList and a JTable in my Frame. I enter a value in JTextField which has to be validated with a constant. Where do u write the validation ?
    i have written the validation in focus lost of JTextField.
    This causes problem when i click on the jtable or jcombobox. When i click on the combobox after entering a wrong value in the textfield, cursor remains in the jtextfield but i am able selected a value from the jcombobox as well.
    Following is the sample code.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    * Title:
    * Description:
    * Copyright: Copyright (c) 2001
    * Company:
    * @author
    * @version 1.0
    public class EnabledTest extends JFrame implements FocusListener
    JTextField jTextField1 = new JTextField();
    JTextField jTextField2 = new JTextField();
    JComboBox jComboBox1 = new JComboBox();
    JList jList1 = new JList();
    JButton jButton1 = new JButton();
    JTable jTable1 = new JTable();
    public EnabledTest()
    try
    jbInit();
    addListeners();
    catch(Exception e) {
    e.printStackTrace();
    public static void main(String[] args)
    EnabledTest enabledTest1 = new EnabledTest();
    enabledTest1.setVisible(true);
    enabledTest1.setBounds(0,0,400,400);
    public void addListeners()
    jTextField1.addFocusListener(this);
    jTextField2.addFocusListener(this);
    jComboBox1.addFocusListener(this);
    jList1.addFocusListener(this);
    jButton1.addFocusListener(this);
    public void focusGained(FocusEvent e)
    public void focusLost(FocusEvent e)
    if(e.getSource() == jTextField1)
    jTextField1_validationPerformed(e);
    private void jbInit() throws Exception
    jTextField1.setText("jTextField1");
    jTextField1.setBounds(new Rectangle(49, 39, 144, 38));
    this.getContentPane().setLayout(null);
    jTextField2.setBounds(new Rectangle(227, 40, 144, 38));
    jTextField2.setText("jTextField1");
    jComboBox1.setBounds(new Rectangle(52, 115, 141, 34));
    jComboBox1.addItem("one");
    jComboBox1.addItem("two");
    jList1.setBounds(new Rectangle(239, 110, 135, 120));
    jButton1.setText("jButton1");
    jButton1.setBounds(new Rectangle(56, 187, 127, 29));
    jTable1.setBounds(new Rectangle(55, 251, 330, 117));
    jTable1.setModel(new DefaultTableModel(3,3));
    this.getContentPane().add(jTextField1, null);
    this.getContentPane().add(jTextField2, null);
    this.getContentPane().add(jComboBox1, null);
    this.getContentPane().add(jList1, null);
    this.getContentPane().add(jButton1, null);
    this.getContentPane().add(jTable1, null);
    private void jTextField1_validationPerformed(FocusEvent e)
    jTextField1.removeFocusListener(this);
    int intValue = new Integer(jTextField1.getText()).intValue();
    if (intValue > 100)
    JOptionPane.showMessageDialog(this, "Should be < 100");
    jTextField1.requestFocus();
    jTextField1.addFocusListener(this);
    }

    It is fairly easy to validate for a range. I added this kind of validation (attached (*)). At any time you may want to set the validity range of your NumericJTextField. I did it as follows:
    this.numericTextField.setValidityRange(-999, +999);
    I tested and it does work nicely - couldn't fool it.
    (*) Is there any holy way to post files without having to cut and paste them as a whole in this doubly holy tab-eater JTextArea :-(
    package textfieldvalidator;
    * Title: NumericJTextField
    * Description: An example JTextFiled that accepts only digits
    * Copyright: nobody - use it at will
    * Company:
    * @author Antonio Bigazzi - [email protected]
    * @version 1.0 First and last
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    public class ValidatorExample extends JPanel {
    NumericJTextField numericTextField; // accepts only digit
    JTable table;
    public ValidatorExample() {
    this.setLayout(new BorderLayout());
    this.numericTextField = new NumericJTextField("1234X5");
    this.numericTextField.setBackground(Color.black);
    this.numericTextField.setForeground(Color.yellow);
    this.numericTextField.setCaretColor(Color.white);
    this.numericTextField.setFont(new Font("Monospaced", Font.BOLD, 16));
    this.numericTextField.setValidityRange(-999, +999);
    this.table = new JTable(
    new String[][] { {"a1a", "b2b", "c3c"}, {"456", "777", "234"}},
    new String[] {"Col 1", "Col 2", "Col 3"}
    this.add(this.numericTextField, BorderLayout.NORTH);
    this.add(this.table, BorderLayout.CENTER);
    public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setContentPane(new ValidatorExample());
    f.setLocation(300, 75);
    f.pack();
    f.setVisible(true);
    // ===================== the meat ============================
    // the specialized JTextField that uses a restrictive doc model
    class NumericJTextField extends JTextField {
    NumericJTextField() {this("", 0);}
    NumericJTextField(String text) {this(text, 0);}
    NumericJTextField(int columns) {this("", columns);}
    NumericJTextField(String text, int columns) {
    super(new NumericDocument(), text, columns);
    public void setValidityRange(int min, int max) {
    ((NumericDocument)this.getDocument()).setValidityRange(min, max);
    // check what may have been there already (via constructor)
    this.setText(this.getText());
    // the restricted doc model - non-numbers make it beep
    class NumericDocument extends PlainDocument {
    protected int minValue = Integer.MIN_VALUE;
    protected int maxValue = Integer.MAX_VALUE;
    public void setValidityRange(int minValue, int maxValue) {
    this.minValue = minValue;
    this.maxValue = maxValue;
    public void insertString(int offset, String text, AttributeSet a)
    throws BadLocationException {
    // digits only please (or bring your own restriction/validation)
    StringBuffer buf = new StringBuffer(text.length());
    for (int i = 0; i < text.length(); i++) {
         if (Character.isDigit(text.charAt(i))) {
         buf.append(text.charAt(i));
         } else {
         java.awt.Toolkit.getDefaultToolkit().beep();
    super.insertString(offset, buf.toString(), a);
    // get the whole "document" back for range validation
    while(true) {
    String num = this.getText(0, this.getLength());
         if (num.length() == 0) break;
         int value = Integer.parseInt(num);
         if (value >= this.minValue && value <= this.maxValue) {
         break;
         } else {
         // beeep and chop (or whatever reaction for out of range)
         java.awt.Toolkit.getDefaultToolkit().beep();
         this.remove(this.getLength() - 1, 1);
    // Note: in insertString, length is 1 when typing, but it can be anything
    // when the text comes from the constructor, when it is pasted, etc.
    }

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

  • JTextField.select(int, int) not working in modal JDialog

    Hi
    I have discovered something peculiar. When I have a JDialog, and it is modal, then the select method of any JTextfield will surely fail. (Only tested on win32)
    What the owner is does not matter (even null will give the same result). I made a JFrame for your convenience.
    import javax.swing.*;
    public class MyDialog extends JDialog
         private JTextField     tf     = new JTextField("not selected >selected< not selected");
         public static void main(String[] args)
              JFrame f = new JFrame("Some parent frame");
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.setVisible(true);
              new MyDialog(f);
         public MyDialog(JFrame parent)
              super(parent, "Child dialog", /*Selecct modality*/ true);
              // super();
              super.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
              super.add(this.tf);
              super.pack();
              super.setLocation(0, 50);
              super.setVisible(true);
              // Selection does not work when dialog is modal.
              this.tf.select(14, 22);
              this.tf.requestFocus();
    }I did not find a bug in the database concerning this.
    Did I do something wrong, or should I post this as a bug?

    1) Please do not dredge posts that are months or years old. If you have something important to say, create your own thread.
    2) If you have the same problem, then use the same solution.
    3) If this doesn't work, then show your problem: show your code. We don't want to see all of it, but rather you should condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem, in other words, an SSCCE (Short, Self Contained, Correct (Compilable), Example). For more info on SSCCEs please look here:
    http://homepage1.nifty.com/algafield/sscce.html
    Also, when posting your code, please use code tags so that your code will be well-formatted and readable. To do this, either use the "code" button at the top of the forum Message editor or place the tag &#91;code&#93; at the top of your block of code and the tag &#91;/code&#93; at the bottom, like so:
    &#91;code&#93;
      // your code block goes here.
    &#91;/code&#93;

  • JTextField in JTableHeader

    Hello,
    I am trying to create table with filterbar. I am using my own reneder/editor for the table header which consist of JButton and JTextField on JPanel. After a character is typed to JTextField the table model is filtered and fireTableDataChanged is called. It works fine, but the JTextField loses focus and JTable gains it. I tried to request for focus again when JTable gains it, but it has no effect. Can you help me what should I do? Thank you!

    I tried to request for focus again when JTable gains it, but it has no effectWhen you use the fireTableDataChanged() method the TableColumnMode and TableHeader is recreated. So even though you request focus on your text field this code may be executed before the table header has actually been recreated.
    You can try wrapping the textField.requestFocusInWindow() method in a SwingUtilities.invokeLater() method. This will cause the request to be added to the end of the Event Thread, hopefully after the table has been recreated.
    Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html]How to Use Threads for more information on invokeLater.

  • Line wrap in JTextField...

    Hi everyone..
    I noticed that JAVA recognizes the line wrap in the JTextField if i paste a text with 2 lines....the text in the component appears with 2 lines because of the line wrap...
    how can i solve this?? i don�t want that the line wrap is showed in my component...
    thanx

    The previous post suggested to create your own Document and prevent all newline characters from being added to the Document. Here is a link to the Swing tutorial on "General Rules for Using Text Components" which explains what a Document is and how to add a custom Document to you JTextField:
    http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html

Maybe you are looking for

  • Preview in bin doesn't work in STP 3

    I send a multitrack from FCP 7 to STP 3, withing STP 3 I open the bin & select a file to audition, nothing happens & the play button is grayed out and not selectable. Same in the browser. I browse to a file on my HD, select it & it won't preview... A

  • Report to write about Java Security

    Hello I'm doing a project for my studies; I'm investigating some points of java security (class loader, bytecoder verifier, security manager and applets). In the second part of my report, I would like to do some tests to show these functionalities in

  • Status profile at header and item level

    27.11.2007 Hi friends, I have created a status profile at the header with option like CRTD and APPRD. The transaction control is Forbid billing when CRTD and Allow Billing when APPRD. I have attached this profile to the Sales document header. At the

  • Create custom jobs in DB13

    Hi, For BW we want to schedule a brconnect job for updating the statistics for the infocube. We can do this in the criontab but we prefer to do do this in DB13. Is there a way to create a custom job in DB13? Thanks for the help Regards, Glenn

  • Unable to Download any Files in Safari.

    Hi, Hopefully someone might be able to help with this one..... I tried a trial verson of speed downloader and then uninstalled. Ever since then I cant download anything through Safari. I have followed the directions at removing speed downloader and g