JFrame validation

Hi all,
I have something that I can't understand. Please help.
My problem is in simple JFrame defined like this :
private JFrame frame = null;
public void runFrame(){
          if (this.frame == null){
               frame = new JFrame();
          frame.setBounds(10,10,900,600);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().setLayout(null);
          frame.getContentPane().addMouseListener(new MouseAdapter(){
                     public void mousePressed(MouseEvent e){
                    buttonAt(e.getX(), e.getY());
}Then I have in same class, but in other method code like this
     protected void buttonAt(int xxx, int yyy){
          JButton button= new JButton("halo");
          button.setBounds(xx,yy,xxx,yyy);
          button.setVisible(true);
          frame.getContentPane().add(button);
          frame.validate();
     }and my problem is : Why I can see only some buttons created. Sometimes it validates three at once, sometimes two... but why this frame is not validating everytime the validation is called. Any help? Some improovement of this code could be great. Thanks a lot.
Esteban

Here it is...
package test;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Main {
     protected static JFrame frame;
     protected static int xStart = 0, yStart = 0;
     public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable(){
               public void run(){
                    if (frame == null){
                         frame = new JFrame();
                    frame.setBounds(10,10,900,600);
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.getContentPane().setLayout(null);
                    frame.getContentPane().addMouseListener(new MouseAdapter(){
                         public void mousePressed(MouseEvent e){
                              xStart = e.getX();
                              yStart = e.getY();
                         public void mouseReleased(MouseEvent e){
                              addButton(e.getX(), e.getY());
                    frame.setVisible(true);
     protected static void addButton(int xEnd, int yEnd){
          JButton button = new JButton("halo");
          button.setBackground(new Color(180,180,255));
          button.setBounds(xStart,yStart,xEnd - xStart,yEnd - yStart);
          button.setVisible(true);
          frame.getContentPane().add(button);
          frame.getContentPane().validate();
}Hope you'll help me now...

Similar Messages

  • "relative" positioning of buttons in a JFrame

    I want to draw an image as a background on a JFrame and then position several buttons in the frame such that when the frame is resized, the background is resized and the buttons remain "over" the same thing in the background image. I've tried to "do the right thing" and use a layout manager to position the buttons, but they just don't seem to behave like I need them to.
    Is there an easy way to get a button to appear at e.g. 70% horizontally across the frame and 40% down the frame? And then when I resize, have the button still be 70% across and 40% down (based on the new size of the frame). Or should I just give up on the layout managers, and calculate my own absolute positions for everything?
    Thanks

    Check this out:
    import javax.swing.*;
    import java.awt.*;
    public class CompassButtons extends JFrame {
      JButton nb = new JButton("North");
      JButton sb = new JButton("South");
      JButton eb = new JButton("East");
      JButton wb = new JButton("West");
      JViewport viewport = new JViewport();
      public CompassButtons() {
        super("SpringLayout Compass Demo");
        setSize(500,300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        SpringLayout sl = new SpringLayout();
        Container c = getContentPane();
        c.setLayout(sl);
        int offset = 50;  // gap between buttons and outside edge
        int w      = 80;  // width of buttons
        int h      = 26;  // height of buttons
        int border =  3;  // border around viewport
        Spring offsetS     = Spring.constant(offset);
        Spring borderS     = Spring.constant(border);
        Spring widthS      = Spring.constant(w);
        Spring halfWidthS  = FractionSpring.half(widthS);
        Spring heightS     = Spring.constant(h);
        Spring halfHeightS = FractionSpring.half(heightS);
        Spring leftEdgeS   = sl.getConstraint(SpringLayout.WEST, c);
        Spring topEdgeS    = sl.getConstraint(SpringLayout.NORTH, c);
        Spring rightEdgeS  = sl.getConstraint(SpringLayout.EAST, c);
        Spring bottomEdgeS = sl.getConstraint(SpringLayout.SOUTH, c);
        Spring xCenterS    = FractionSpring.half(rightEdgeS);
        Spring yCenterS    = FractionSpring.half(bottomEdgeS);
        Spring leftBorder  = Spring.sum(leftEdgeS, borderS);
        Spring topBorder   = Spring.sum(topEdgeS, borderS);
        Spring northX = Spring.sum(xCenterS, Spring.minus(halfWidthS));
        Spring southY = Spring.sum(bottomEdgeS, Spring.minus(Spring.sum(heightS,
                                                                        offsetS)));
        Spring eastX = Spring.sum(rightEdgeS, Spring.minus(Spring.sum(widthS,
                                                                      offsetS)));
        Spring eastY = Spring.sum(yCenterS, Spring.minus(halfHeightS));
        c.add(nb, new SpringLayout.Constraints(northX, offsetS, widthS, heightS));
        c.add(sb, new SpringLayout.Constraints(northX, southY, widthS, heightS));
        c.add(wb);
        sl.getConstraints(wb).setX(offsetS);
        sl.getConstraints(wb).setY(eastY);
        sl.getConstraints(wb).setWidth(widthS);
        sl.getConstraints(wb).setHeight(heightS);
        c.add(eb);
        sl.getConstraints(eb).setX(eastX);
        sl.getConstraints(eb).setY(eastY);
        sl.getConstraints(eb).setWidth(widthS);
        sl.getConstraints(eb).setHeight(heightS);
        c.add(viewport); // this sets a bounds of (0,0,pref_width,pref_height)
        // The order here is important...need to have a valid width and height
        // in place before binding the (x,y) location
        sl.putConstraint(SpringLayout.SOUTH, viewport, Spring.minus(borderS),
                         SpringLayout.SOUTH, c);
        sl.putConstraint(SpringLayout.EAST, viewport, Spring.minus(borderS),
                         SpringLayout.EAST, c);
        sl.putConstraint(SpringLayout.NORTH, viewport, topBorder,
                         SpringLayout.NORTH, c);
        sl.putConstraint(SpringLayout.WEST, viewport, leftBorder,
                         SpringLayout.WEST, c);
        ImageIcon icon = new ImageIcon("images/terrain.jpg");
        viewport.setView(new JLabel(icon));
        // Hook up the buttons.  See the CompassScroller class (on-line) for details
        // on controlling the viewport.
        nb.setActionCommand(CompassScroller.NORTH);
        sb.setActionCommand(CompassScroller.SOUTH);
        wb.setActionCommand(CompassScroller.WEST);
        eb.setActionCommand(CompassScroller.EAST);
        CompassScroller scroller = new CompassScroller(viewport);
        nb.addActionListener(scroller);
        sb.addActionListener(scroller);
        eb.addActionListener(scroller);
        wb.addActionListener(scroller);
        setVisible(true);
      public static void main(String args[]) {
        new CompassButtons();
    }Copyright 2003, O'Reilly & Associates
    Provided as example.
    Cheer
    DB

  • Return to the cell after data validation in JTable

    Hi,
    I am implementing an editable JTable. I want the focus or selection return to the current editing cell when the user inputing a wrong format data. I can catch the validation error and pop up a error message to user. But I can not return the focus or selection to the editing cell.
    If anyone has already solved this problem, please give me your solution.
    Thank you!
    I have tried:
    1.
    In tableChanged(TableModelEvent e) method:
    int row = e.getFirstRow();
    int column = e.getColumn();
    Object data = newJTable.getValueAt(row, column);
    if(!validation(data)) // return true if validation OK
    editFailed = true;//class variable
    previousRow = row;//class variable
    previousCol = column;//class variable
    Add a focus listener to the table and implement the focus listener's focusLost method with:
    if(validationFailed)
    table.editCellAt(previousRow, previousCol);
    This does move the focus to the editing cells if you want to continue to edit the table.
    Problems are
    If you move the focus out of the table, the wrong date will be in the table or not edited.
    The selection color was shown on the next cell where you pointed your mouse to after you leave the editing cells.
    2. I have also tried to use:
    in the above focusLost method
    table.clearSelection();
    table.editCellAt(previousRow, previousCol);
    table.setRowSelectionInterval(previousRow, previousRow);
    table.setColumnSelectionInterval(previousCol, previousRow);
    But it did not change the selection.
    Shaolong

    This is the fix for the above problem.
    Basically we need to handle both mouse/keyboard actions on our own.
    This code returns the control to errorCell..
    /* TableCellValidator class */
    /* The class basically validates the input entry in a cell and */
    /* pops up a JOptionPane if its an invalid input */
    /* And an OK is clicked on the JOptionPane, the control returns back */
    /* to the same cell */
    /* Basic Idea: The controls Arrow/Tab/mouse clicks are handled by our */
    /* ----------- custom table. Its has been slightly tricky to handle */
    /* mouse clicks, since when you click the next cell, the */
    /* editingrow/editingcol advances. Hence the */
    /* previousrow/previouscol has been captured in the */
    /* setValueAt method. */
    /* To capture Table/Arrow/Numeric Arrow, The keyStrokes(TAB etc)*/
    /* assigned different AbstractionActions to execute like */
    /* validateBeforeTabbingToNextCell */
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableCellValidator {
    * Constructor.
    * Basically instantiates the class and sets up the
    * JFrame object and the table.
    public TableCellValidator() {
    JFrame f = new JFrame("JTable test");
    f.getContentPane().add(new JScrollPane(createTable()), "Center");
    f.pack();
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    * A method which created our custom table.
    * The JTable methods processMouseEvent
    * and setValueAt are overridden to handle
    * Mouseclicks.
    * The Tables ActionMap is fed with different
    * AbstractAction classes eg: (validateBeforeTabbingToNextCell)
    * (Scroll down below for the innerclass
    * validateBeforeTabbingToNextCell).
    * So basically when TAB is pressed the stuff present
    * in the validateBeforeTabbingToNextCell's actionPerformed(..)
    * method is performed.
    * So we need to handle all the stuff a TAB does.
    * ie. if a TAB hits the end of the row, we need to increment
    * it to the next Row (if the validation is successful)
    * in the current row etc..
    * @return JTable
    * @see validateBeforeTabbingToNextCell
    * @see validateBeforeShiftTabbingToNextCell
    * @see validateBeforeMovingToNextCell
    * @see validateBeforeMovingDownToCell
    * @see validateBeforeMovingUpToCell
    * @see validateBeforeMovingLeftToCell
    private JTable createTable() {
    JTable table = new JTable(createModel()){
    private int previousRow =0;
    private int previousCol =0;
    * Processes mouse events occurring on this component by
    * dispatching them to any registered
    * <code>MouseListener</code> objects.
    * <p>
    * This method is not called unless mouse events are
    * enabled for this component. Mouse events are enabled
    * when one of the following occurs:
    * <p><ul>
    * <li>A <code>MouseListener</code> object is registered
    * via <code>addMouseListener</code>.
    * </ul>
    * <p>Note that if the event parameter is <code>null</code>
    * the behavior is unspecified and may result in an
    * exception.
    * @param e the mouse event
    * @see java.awt.event.MouseEvent
    * @see java.awt.event.MouseListener
    * @see #addMouseListener
    * @see #enableEvents
    * @since JDK1.1
    protected void processMouseEvent(MouseEvent e) {
    boolean canMoveFocus = true;
    int currentRowAndColumn[] = getCurrentRowAndColumn(this); //we pull the current row and column
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    if ( e.getID() == MouseEvent.MOUSE_PRESSED || e.getID() == MouseEvent.MOUSE_CLICKED) {
    stopCurrentCellBeingEdited(this); //stop the cellbeing edited to grab its value
    final String value = (String)getModel().getValueAt(row,column);
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    SwingUtilities.invokeLater(new Runnable(){
    public void run() {
    JOptionPane.showMessageDialog(null,"Alpha value ="+ value ,"Invalid entry!",JOptionPane.WARNING_MESSAGE);
    changeSelection(previousRow,previousCol, true, true);
    editCellAt(previousRow, previousCol);
    requestFocus(); // or t.getEditorCompo
    if ( canMoveFocus ) {
    super.processMouseEvent(e);
    * The method setValueAt of the JTable is overridden
    * to save the previousRow/previousCol to enable us to
    * get back to the error cell when a Mouse is clicked.
    * This is circumvent the problem, when a mouse is clicked in
    * a different cell, the control goes to that cell and
    * when you ask for getEditingRow , it returns the row that
    * the current mouse click occurred. But we need a way
    * to stop at the previous cell(ie. the cell that we were editing
    * before the mouse click occurred) when an invalid data has
    * been entered and return the focus to that cell
    * @param aValue
    * @param row
    * @param col
    public void setValueAt(Object aValue,int row, int col) {     
    this.previousRow = row;
    this.previousCol = col;
    super.setValueAt(aValue,row,col);
    /* These are the various KeyStrokes like
    ENTER,SHIFT-TAB,TAB,Arrow Keys,Numeric Arrow keys being assigned an Abstract action (key string ) in to the
    inputMap first . Then an Action is assigned in the ActionMap object
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0) ,"validateBeforeTabbingToNextCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,1) ,"validateBeforeShiftTabbingToNextCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0) ,"validateBeforeMovingToNextCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_RIGHT,0) ,"validateBeforeMovingToNextCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,0) ,"validateBeforeMovingDownToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_DOWN,0) ,"validateBeforeMovingDownToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0) ,"validateBeforeMovingDownToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP,0) ,"validateBeforeMovingUpToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_UP,0) ,"validateBeforeMovingUpToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0) ,"validateBeforeMovingLeftToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_LEFT,0) ,"validateBeforeMovingLeftToCell");
    table.getActionMap().put("validateBeforeTabbingToNextCell",
    new validateBeforeTabbingToNextCell());
    table.getActionMap().put("validateBeforeShiftTabbingToNextCell",
    new validateBeforeShiftTabbingToNextCell());
    table.getActionMap().put("validateBeforeMovingToNextCell",
    new validateBeforeMovingToNextCell());
    table.getActionMap().put("validateBeforeMovingDownToCell",
    new validateBeforeMovingDownToCell());
    table.getActionMap().put("validateBeforeMovingUpToCell",
    new validateBeforeMovingUpToCell());
    table.getActionMap().put("validateBeforeMovingLeftToCell",
    new validateBeforeMovingLeftToCell());
    table.setPreferredScrollableViewportSize(table.getPreferredSize());
    return table;
    * A table model is created here for 5 rows/5 columns.
    * And the isCellEditable is overridden to return true,
    * indicating that the cell can be edited.
    * So fine tuned control can be done here by saying,
    * the user can be allowed to edit Row 1,3 or 5 only.
    * or column 1 only etc..
    * @return DefaultTableModel
    private DefaultTableModel createModel() {
    DefaultTableModel model = new DefaultTableModel(5, 5) {
    public boolean isCellEditable(int row, int column) {
    return true;
    return model;
    * This method basically returns the currentRow/currentCol value
    * If the current Row/Col is being edited then
    * it returns the getEditingRow/getEditingColumn
    * If its not being edited,
    * it return the getAnchorSelectionIndex of the JTables
    * ListSelectionModel.
    * If the column or row is -1, then it return 0.
    * The first element in the int[] array is the row
    * The second element in the int[] array is the column
    * @param t input a JTable
    * @return int[]
    * @see ListSelectionModel
    * @see JTable
    private int[] getCurrentRowAndColumn(JTable t){
    int[] currentRowAndColum = new int[2];
    int row, column;
    if (t.isEditing()) {
    row = t.getEditingRow();
    column = t.getEditingColumn();
    } else {
    row = t.getSelectionModel().getAnchorSelectionIndex();
    if (row == -1) {
    if (t.getRowCount() == 0) {
    //actually this should never happen.. we need to return an exception
    return null;
    column =t.getColumnModel().getSelectionModel().getAnchorSelectionIndex();
    if (column == -1) {
    if (t.getColumnCount() == 0) {
    //actually this should never happen.. we need to return an exception
    return null;
    column = 0;
    currentRowAndColum[0]=row;
    currentRowAndColum[1]=column;
    return currentRowAndColum;
    * Tbis basically a wrapper method for CellEditors,
    * stopCellEditing method.
    * We need to do this because,
    * for instance we have entered a value in Cell[0,0] as 3
    * and when we press TAB or mouse click or any other relevant
    * navigation keys,
    * ** IF the cell is BEING EDITED,
    * when we do a getValueAt(cellrow,cellcol) at the TableModel
    * level , it would return "null". To overcome this problem,
    * we tell the cellEditor to stop what its doing. and then
    * when you do a getValueAt[cellrow,cellcol] it would
    * return us the current cells value
    * @param t Input a JTable
    * @see CellEditor
    private void stopCurrentCellBeingEdited(JTable t){
    CellEditor ce = t.getCellEditor(); /*this not the ideal way to do..
    since there is no way the CellEditor could be null.
    But a nullpointer arises when trying to work with mouse.. rather than just
    keyboard" */
    if (ce!=null) {
    ce.stopCellEditing();
    * The following Action class handles when a
    * RIGHT ARROW or NUMERIC RIGHT ARROW is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move it to the
    * next Cell.. else take it back to the currentCell
    class validateBeforeMovingToNextCell extends AbstractAction {
    * The following Action class handles when a
    * DOWN ARROW or NUMERIC DOWN ARROW is pressed.
    * There is just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move it to
    * down by one Cell.. else take it back to the currentCell
    * @param e
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    column++;
    if (column >= t.getColumnCount())
    column = column-1;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a
    * DOWN ARROW or NUMERIC DOWN ARROW is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move it to the
    * down by Cell.. else take it back to the currentCell
    class validateBeforeMovingDownToCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    row++;
    if (row >= t.getRowCount())
    row = row - 1;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a
    * UP ARROW or NUMERIC UP ARROW is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move the cursor/
    * editable status up by a Cell.. else take it back to the currentCell
    class validateBeforeMovingUpToCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    row--;
    if (row <0)
    row = 0;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a
    * LEFT ARROW or NUMERIC LEFT ARROW is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move the cursor/
    * editable status up by a Cell.. else take it back to the currentCell
    class validateBeforeMovingLeftToCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    column--;
    if (column <0)
    column = 0;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a TAB is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move the cursor/
    * editable status up by a Cell.. else take it back to the currentCell
    class validateBeforeTabbingToNextCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    column++;
    int rows = t.getRowCount(), columns = t.getColumnCount();
    while (row < rows) {
    while (column < columns) {
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    column++;
    row++;
    column = 0;
    row = 0;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a SHIFT TAB is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move the cursor/
    * editable status up by a Cell.. else take it back to the currentCell
    class validateBeforeShiftTabbingToNextCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    column--;
    int rows = t.getRowCount(), columns = t.getColumnCount();
    while ((row < rows) && (row >= 0)) {
    while ((column < columns) && (column >= 0)) {
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    column--;
    row--;
    column = columns - 1;
    row = rows - 1;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    public static void main(String[] args) {
    new TableCellValidator();

  • Validation in Jform

    i want to know how to enable a button based on the details filled in the form....
    for example the button "next" should be made active only if the form is filled completely and
    displaying an error message automatically in the case of password, ie if the two fields don't match
    thanks & regards
    vumsi..

    Subject: validation in Jform
    What is a Jform? I have heard of a JFrame, and a variety of other J2SE classes, but never a Jform.

  • Source codes and jframes

    Hello ,
    I am trying to make it so that I can somehow place this source code,
    *Hi_LoGame.java*
    Peter Hadlaw
    *2009/10/12*
    *This is a simple guessing game that tells the user if they got the number right or if the are too low or too high, and then asks if they wish to continue. It then prints the results, and the best score.*
    import java.util.*;
    public class Hi_LoGame {
        public static void main(String[] args) {
           Scanner userInput = new Scanner (System.in);
           int userC, userG=0, bestGNum=0, currentGNum=0, gamesP = 0, gNum = 0, cpuNum;
           Random cpuRandNumGen = new Random();
           System.out.println("Welcome to the Hi - Lo game showdown!!!\nWould you like to play: (1)Yes or (2)No?");
           userC = userInput.nextInt();
           while(userC<=0||userC>=3){
                System.out.println("Please enter a valid choice of 1 or 2.");
                userC = userInput.nextInt();
           cpuNum = cpuRandNumGen.nextInt(100)+1;+
    +       while(userC==1){+
    +                 currentGNum++;
                     System.out.print("Please enter a number from 1-100 for you guess: ");
                     userG=userInput.nextInt();
                     while(userG<=0||userG>100){
                          System.out.println("Please enter a valid guess:");
                          userG = userInput.nextInt();
                     if(userG==cpuNum){
                          System.out.println("Congradulations you got it right!");
                          System.out.println("You got it right in "  +currentGNum+  " guesses.");
                          System.out.println("Do you want to play (1)again or do you want to (2)stop");
                          userC = userInput.nextInt();
                          while(userC<=0||userC>=3){
                               System.out.println("Please enter a valid choice of 1 or 2.");
                               userC = userInput.nextInt();
                          if(gamesP==0)
                               bestGNum = currentGNum;
                          if(gamesP>1&&currentGNum<bestGNum){
                               bestGNum = currentGNum;
                          else{//nothing
                          gamesP++;
                          cpuNum = cpuRandNumGen.nextInt(100)+1;+
    +                      if(userC==1){+
    +                           currentGNum=0;+
    +                      }+
    +                      else{+
    +                      }+
    +                 }+
    +                else if(userG>cpuNum){+
    +                     System.out.println("Sorry but you are to high!");+
    +                     System.out.println("Do you want to guess (1)again or do you want to (2)give up");+
    +                      userC = userInput.nextInt();+
    +                      while(userC<=0||userC>=3){+
    +                           System.out.println("Please enter a valid choice of 1 or 2.");+
    +                           userC = userInput.nextInt();+
    +                      }+
    +                      if(userC==2){+
    +                           gamesP++;
                               System.out.println("You gave up ,your guess count was: "  +currentGNum);+
    +                      }+
    +                      else{+
    +                      }+
    +                }+
    +                else{+
    +                     System.out.println("Sorry but you are too low!");+
    +                     System.out.println("Do you want to guess (1)again or do you want to (2)give up");+
    +                      userC = userInput.nextInt();+
    +                      while(userC<=0||userC>=3){+
    +                           System.out.println("Please enter a valid choice of 1 or 2.");+
    +                           userC = userInput.nextInt();+
    +                      }+
    +                      if(userC==2){+
    +                           gamesP++;
                               System.out.println("You gave up ,your guess count was: "  +currentGNum);+
    +                      }+
    +                      else{+
    +                      }+
    +                }+
    +       }+
    +       if(gamesP==0){+
    +            System.out.println("Thanks anyways, please come again.");+
    +       }+
    +       else{+
    +            System.out.println("Thanks for playing, you last score is: "+  currentGNum  +" but your best guess number was in "+  bestGNum + " guesses.");
    }into a jframe, I heard something about text panes or textareas maybe being able to print this, but i just want one simple jframe with the above, and the user can input stuff right then and their.
    Thank You

    What you currently have is a non-OOP class, one that is nothing but a big main method without methods, constructors, etc.
    If this is your code, it suggests that you still have a bit to learn before tackling Java GUI such as writing classes, methods, constructors, etc. I mean feel free to read up on how to create a Swing GUI here [http://java.sun.com/docs/books/tutorial/uiswing/index.html] and jump right in, but just be forewarned that if you're jumping too early, it'll be a frustrating swim. Much luck.

  • Validating JTextField for Date Format

    hello,
    everybody.
    i am trying to perform a validation on text field, i.e if the input is in a date format then it will show, other wise it will consume the character.
    please help me out of this problem i am stucked with it.
    waitng for reply. the following is my code.
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    import java.text.*;
    public class RilJDateField implements KeyListener
         JFrame frame;
         JPanel panel;
         JLabel label;
         JTextField text;
         GridBagLayout gl;
         GridBagConstraints gbc;
         Date date = new Date();
         public static void main(String a[])
              new RilJDateField();
         public RilJDateField()
              panel = new JPanel();
              gl = new GridBagLayout();
              gbc = new GridBagConstraints();
              panel.setLayout(gl);
              label = new JLabel("Only Date Format");
              text = new JTextField(5);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 1;
              gl.setConstraints(label,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 2;
              gbc.gridy = 1;
              gl.setConstraints(text,gbc);
              panel.add(label);
              panel.add(text);
              text.addKeyListener(this);
              text.requestFocus();
              frame = new JFrame("RilJDateField Demo");
              frame.getContentPane().add(panel);
              frame.addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent we)
                             System.exit(0);
              frame.setSize(300,300);
              frame.setVisible(true);
         public void keyTyped(KeyEvent ke)
         public void keyPressed(KeyEvent ke)
              DateFormat df;
              df = DateFormat.getDateInstance();
              df = (DateFormat) ke.getSource();
              if(!(df.equals(date)))
                   ke.consume();
         public void keyReleased(KeyEvent ke)
    }

    hi,
    thanks very much, u gave me great idea.
    according to ur suggestion i used JFormattedTextField as well as SimpleDateFormat, but while giving keyevent i am getting the error,
    so please if possible reply for this.
    the error is
    java.lang.ClassCastException
         at RilJDateField.keyTyped(RilJDateField.java:61)
         at java.awt.Component.processKeyEvent(Unknown Source)
         at javax.swing.JComponent.processKeyEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)and my source code is
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    import java.text.*;
    public class RilJDateField implements KeyListener
         JFrame frame;
         JPanel panel;
         JLabel label;
         JFormattedTextField text;
         GridBagLayout gl;
         GridBagConstraints gbc;
         Date date = new Date();
         SimpleDateFormat formatter;
         public static void main(String a[])
              new RilJDateField();
         public RilJDateField()
              panel = new JPanel();
              gl = new GridBagLayout();
              gbc = new GridBagConstraints();
              panel.setLayout(gl);
              label = new JLabel("Only Date Format");
              text = new JFormattedTextField();
              text.setColumns(10);
              formatter = new SimpleDateFormat("dd mm yyyy");
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 1;
              gl.setConstraints(label,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 2;
              gbc.gridy = 1;
              gl.setConstraints(text,gbc);
              panel.add(label);
              panel.add(text);
              text.addKeyListener(this);
              text.requestFocus();
              frame = new JFrame("RilJDateField Demo");
              frame.getContentPane().add(panel);
              frame.addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent we)
                             System.exit(0);
              frame.setSize(300,300);
              frame.setVisible(true);
         public void keyTyped(KeyEvent ke)
              Date date = (Date) ke.getSource();
              if(!(date.equals(formatter)))
                   ke.consume();
         public void keyPressed(KeyEvent ke)
         public void keyReleased(KeyEvent ke)
    }

  • Problem in refreshing JFrame

    Hi,
    I am getting problem in validating JFrame when I intent to remove one panel and try to add another on runtime. I did call a validate() method but still JFrame dose not refresh completely.
    Note: I compile with JDK1.6
    Here is the code
    ///////////////// Code starts here
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Prob extends JFrame implements ActionListener
    Container c;
    JPanel p1;
    JPanel p2;
    public Prob()
         p1=new JPanel();
         p1.setLayout(null);
         JButton bt1=new JButton("Button");
         JTextField tf=new JTextField();
         bt1.setBounds(10,10,100,30);
         bt1.addActionListener(this);
         tf.setBounds(10,100,100,20);
         p1.add(bt1);
         p1.add(tf);
         c=getContentPane();
         c.setLayout(null);
         p1.setBounds(0,0,150,200);
         c.add(p1);
         setSize(150,200);
         setVisible(true);
    public void actionPerformed(ActionEvent e)
              p2=new JPanel();
              p2.setLayout(null);
              p2.setBounds(0,0,150,200);
              JComboBox combobox=new JComboBox();
              combobox.addItem("Item1");
              combobox.addItem("Item2");
              combobox.setBounds(10,10,100,20);
              p2.add(combobox);
              ////////////// I think the problem is in the code below
              c.remove(p1);
              c.add(p2);
              validate();
              //c.validate(); I have also tried this           
    public static void main(String[] args)
              new Prob();
    }

    Since you don't use layout managers I'm not sure that calling validate() really does anything. Maybe you should just call repaint() instead.

  • How do you switch between jpanels in a jframe?

    I have, what seems, a relatively simple question; however I cant find a solution to it anywhere!
    I have a jframe with a jmenubar which has 4 menu items. When each item is clicked a new JFrame is displayed with certain content. What I am trying to do, instead of creating a new Jframe each time a menu item is clicked, is display all jpanels within the current jframe. When different menu items in the jmenu are clicked it "switches" the main jpanel to display the required content.
    So basically I want 1 JFrame, which has 4 JPanels, (alhough only 1 is shown at any given time). When a menu item in the jmenubar is clicked the JPanel which corresponds to the menu item is displayed on the jframe.
    If your still confused, I basically want jtabbedpane functionality only I want to control the switching through tabs via the jmenubar (and I dont want the jtabbedpane tabs obviously).
    Thanks

    Myles wrote:
    Okay that seems obvious ;)
    What do you mean by "validating the content pane" though?
    Thanks for your quick reply.Containers have a method called validate() which will update them when components are added and removed. Without this, you won't see added components.
    And yes, you can have more than 1 container. JPanels are containers themselves and can have components added and removed from them as well. You only have one content pane in the JFrame, but you could add two JPanels to this, one static and one to act as your swapping container.

  • 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.
    }

  • JFrame setBackground(Color c)

    i'm just curious about Swing so i started reading sun tut Using Swing Components /Using Top-Level Containers and at the same time reviewing a tut i built some time ago called DiveLog (also from sun).
    package divelog;
    import javax.swing.*;
    import java.awt.*;   // Contains all of the classes for creating user
                         // interfaces and for painting graphics and images.
    import java.awt.event.*; // Provides interfaces and classes for
                             // dealing with different types of events fired by AWT components
    public class DiveLog {
        private JFrame dlframe;
        //private JTabbedPane tabbedPane;
        public DiveLog() {
            JFrame.setDefaultLookAndFeelDecorated(true);
            dlframe = new JFrame ("T?tulo do frame");
            dlframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            dlframe.setSize(400, 200);
            //dlframe.setBackground(Color(49, 106, 197));
            Color c = new Color(49, 106, 197);
            dlframe.setBackground(c);
            //dlframe.setForeground(c);
            //dlframe.pack();
            // Causes this Window to be sized to fit the
            // preferred size and layouts of its subcomponents.
            // If the window and/or its owner are not yet displayable,
            // both are made displayable before calculating the preferred size.
            // The Window will be validated after the preferredSize is calculated.
            dlframe.setVisible(true);
            System.out.print(dlframe.getBackground());
        public static void main(String args[]) {
            DiveLog dl = new DiveLog();
    }My Q:
    what's the use of
    .setBackground(c); if we cant see it?

    The content pane is always painted over the JFrame. So you would set the background color of the content pane, not the frame. So, I agree with you, there is no need for that line of code.
    The only possible reason I could think of is that when using a slow computer the painting may not be done fast enough and you could get a flicker as the frame is painted and then the content pane.
    JFrame frame = new JFrame();
    frame.setBackground( Color.RED );
    frame.getContentPane().setBackground( Color.GREEN );
    frame.setSize(300, 300);
    frame.setVisible(true);
    Run the above code and you will notice a flicker as the frame is first painted red and then green. So to reduce flicker you could set the frame background to green as well. In most cases when using the default background color of gray you don't notice the flicker so you don't usually worry about it.

  • Having trouble displaying a JPanel on a JFrame

    Hello all,
    I'm fairly new to Java and I am having trouble displaying a JPanel on a JFrame. Pretty much I have a class called Task which has a JPanel object. Everytime the user creates a new task, a JPanel with the required information is created on screen. However, I cannot get the JPanel to display.
    Here is some of the code I have written. If you guys need to see more code to help don't hesitate to ask.
    The user enters the information on the form and clicks the createTask button. If the information entered is valid, a new task is created and the initializeTask method is called.
    private void createTaskButtonMouseClicked(java.awt.event.MouseEvent evt) {                                             
        if (validateNewTaskEntry())
         String name = nameTextField.getText().trim();
         Date dueDate = dueDateChooser.getDate();
         byte hourDue = Byte.parseByte(hourFormattedTextField.getText());
         byte minuteDue = Byte.parseByte(minuteFormattedTextField.getText());
         String amOrPm = amPmComboBox.getSelectedItem().toString();
         String group = groupComboBox.getSelectedItem().toString();
         numberTasks++;
    //     if (numberTasks == 1)
    //     else
         Task newTask = new Task(mainForm, name, dueDate, hourDue, minuteDue,
             amOrPm, group);
         newTask.initializeTask();
         this.setVisible(false);
    }This is the code that I thought would display the JPanel. If I put this code in anther form's load event it will show the panel with the red border.
    public void initializeTask()
         taskPanel = new JPanel();
         taskPanel.setVisible(true);
         taskPanel.setBorder(BorderFactory.createLineBorder(Color.RED));
         taskPanel.setBounds(0,0,50,50);
         taskPanel.setLayout(new BorderLayout());
         mainForm.setLayout(new BorderLayout());
         mainForm.getContentPane().add(taskPanel);
    }I was also wondering if this code had anything to do with it:
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new AddTaskForm(new MainForm()).setVisible(true);
        }As you can see I create a new MainForm. The MainForm is where the task is supposed to be drawn. This code is from the AddTaskForm (where they enter all the information to create a new task). I had to do this because AddTaskForm needs to use variables and methods from the MainForm class. I tried passing the mainForm I already created, but I get this error: non-static variable mainForm cannot be referenced from a static context. So to allow the program to compile I passed in new MainForm() instead. However, in my AddTaskForm class constructor, I pass the original MainForm. Here is the code:
    public AddTaskForm(MainForm mainForm)
       initComponents();
       numberTasks = 0;
       this.mainForm = mainForm;
    }Is a new mainForm actually being created and thats why I can't see the JPanel on the original mainForm? If this is the case, how would I pass the mainForm to addTaskForm? Thanks a ton for any help/suggestions!
    Brian

    UPDATE
    While writing the post an idea popped in my head. I decided to not require a MainForm in the AddTaskForm. Instead to get the MainForm I created an initializeMainForm method.
    This is what I mean by not having to pass new MainForm():
        public static void main(String args[])
         java.awt.EventQueue.invokeLater(new Runnable()
             public void run()
              new MainForm().setVisible(true);
        }Even when I don't create the new MainForm() the JPanel still doesn't show up.
    Again, thanks for any help.
    Brian

  • How to make a Login Page with JFrame

    Hi,
    I have a to make a login page and to check the user name and password
    and also to check the user permission and then check the permission
    for which group...he had acess...
    like i had 3 tables...
    user table, permission tabel , and access tabel.
    so plz can any one help me out with some codes

    Hi Ranjan,
    Run this demo and if it is ok then we could move to tree view.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Frame1 extends JFrame {
    private static final String text = "<html> <center><b><font size=+3>Central</font></b> <br><b><font size=+3>Manager</font></b></center> </html>";
    JPanel jPanel1 = new JPanel();
    BorderLayout borderLayout1 = new BorderLayout();
    JLabel jLabel1 = new JLabel();
    JPanel jPanel2 = new JPanel();
    GridBagLayout gridBagLayout1 = new GridBagLayout();
    JLabel jLabel2 = new JLabel();
    JLabel jLabel3 = new JLabel();
    JTextField loginTextField = new JTextField(20);
    JPasswordField passwordTextField = new JPasswordField(20);
    JPanel jPanel3 = new JPanel();
    JButton exitButton = new JButton();
    JButton enterButton = new JButton();
    FlowLayout flowLayout1 = new FlowLayout();
    public Frame1() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void login(ActionEvent e) {
    String login = loginTextField.getText();
    String password = new String(passwordTextField.getPassword());
    //validate login and password here. validity will be done by sending login/password to the server
    if (login.equals("ranjan") && password.equals("ranjan")) {
    System.out.println("login successfull");
    showTreeView();
    } else {
    JOptionPane.showMessageDialog(this,"Incorrect login or password","Error",JOptionPane.ERROR_MESSAGE);
    loginTextField.setText("");
    passwordTextField.setText("");
    loginTextField.requestFocusInWindow();
    private void showTreeView() {
    getContentPane().removeAll();
    TreeViewPanel treeview = new TreeViewPanel();
    getContentPane().add(treeview);
    getContentPane().validate();
    private void exit(ActionEvent e) {
    setVisible(false);
    public static void main(String[] args) {
    Frame1 f = new Frame1();
    f.setLocation(200,200);
    f.pack();
    f.show();
    private void jbInit() throws Exception {
    jPanel1.setLayout(borderLayout1);
    jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
    jLabel1.setText(text);
    jPanel2.setLayout(gridBagLayout1);
    jLabel2.setText("Password:");
    jLabel3.setText("Login:");
    exitButton.setText("Exit");
    exitButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    exit(e);
    enterButton.setText("Enter");
    enterButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    login(e);
    jPanel3.setLayout(flowLayout1);
    flowLayout1.setAlignment(FlowLayout.RIGHT);
    this.getContentPane().add(jPanel1, BorderLayout.CENTER);
    jPanel1.add(jLabel1, BorderLayout.NORTH);
    jPanel1.add(jPanel2, BorderLayout.CENTER);
    jPanel2.add(loginTextField, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0
    ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 11, 0, 0), 0, 0));
    jPanel2.add(jLabel2, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0
    ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(11, 0, 0, 0), 0, 0));
    jPanel2.add(passwordTextField, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0
    ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(11, 11, 0, 0), 0, 0));
    jPanel2.add(jLabel3, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0
    ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
    jPanel1.add(jPanel3, BorderLayout.SOUTH);
    jPanel3.add(enterButton, null);
    jPanel3.add(exitButton, null);
    import java.awt.*;
    import javax.swing.*;
    public class TreeViewPanel extends JPanel {
    BorderLayout borderLayout1 = new BorderLayout();
    JScrollPane jScrollPane1 = new JScrollPane();
    JTree tree = new JTree();
    JPanel jPanel1 = new JPanel();
    JButton jButton1 = new JButton();
    public TreeViewPanel() {
    try {
    jbInit();
    catch(Exception ex) {
    ex.printStackTrace();
    void jbInit() throws Exception {
    this.setLayout(borderLayout1);
    jButton1.setText("Manage Group");
    this.add(jScrollPane1, BorderLayout.CENTER);
    jScrollPane1.getViewport().add(tree, null);
    this.add(jPanel1, BorderLayout.SOUTH);
    jPanel1.add(jButton1, null);
    }

  • Time validator

    I am trying to come up with some way of producing an applet that will deal with the following:
    In this task you are required to design, create and test a new class called newTime.
    1. Design a solution for a new class called newTime.      
    a. public boolean valid24Time (int hh, int mm)
         The hours (hh) can only be in the range 0-23 and the
    minutes (mm) can only be in the range 0-59.
         This method must return true if the time is valid and false
    if the time is invalid.
         b. public String convert24ToStd (int hh, int mm)
         The time is passed to the method as hours (hh) and minutes
    (mm)with the time in 24
         hour format. The 24 hour format must be changed into standard
    format in the form
         hh:mm AM for a morning time and hh:mm PM for an afternoon time.
         This method must return a string containing the time in
    standard format.
         c. public int convertStdTo24 (String hhmm)
         The time is passed to the method as a string in standard format
    in the form hh:mm
         AM for a morning time and hh:mm PM for an afternoon time. The
    standard format     must be changed into 24 hour format.
         This method must return an integer containing the time in 24
    hour format.
         d. public int addTime (int hh1, int mm1, int hh2, int mm2)
         Two times are passed to the method in 24 hour format as hours
    and minutes (hh1 and mm1, hh2 and mm2). The two times must be
    added together.
         This method returns the calculated time as an integer in 24
    hour format.
         e. public int subtractTime (int hh1, int mm1, int hh2, int mm2)
         Two times are passed to the method in 24 hour format as hours
    and minutes (hh1 and mm1, hh2 and mm2). The second time must be
    subtracted from the first.
         This method must return the calculated time as an integer in 24
    hour format.
    2. Error handling routines must be included to deal with exceptions.
    3. Write the code for the newTime class.
    4. Design and create a testnewTime class which tests the methods in the newTime class.
    Document the layout of any input and output screens used.
    5. Create test data to test the newTime class and determine the expected results.
    6. Prepare a test plan.
    7. Test the software, compare the actual results to the expected results keeping a log for
    each test which identifies any discrepancies between actual and expected results and
    records any amendments made to correct errors.
    8. Produce technical documentation to describe the class interface and purpose and
    operation of the newTime class.
    9. Produce a printed program listing.
    Any help would be grateful
    Regards
    Rary Geddi

    I've have tried all ways to get this to work but with out any luck.
    What am I doing wrong?
    public class Frame1 extends JFrame {
    String inputHour;
    String inputMin;
    int hh = 0;
    int mm = 0;
    boolean isHourValid;
    boolean isMinValid;
    public boolean valid24Time ( int hh, int mm)
    {  boolean isHourValid = ( hh>= 0 && hh<24);
    boolean isMinValid = ( mm>= 0 && mm <60);
    return (isHourValid & isMinValid);
    private JPanel contentPane;
    private JPanel jPanel1 = new JPanel();
    private JButton jButton1 = new JButton();
    private JButton jButton2 = new JButton();
    private JButton jButton3 = new JButton();
    private JButton jButton4 = new JButton();
    private JButton jButton5 = new JButton();
    private GridBagLayout gridBagLayout1 = new GridBagLayout();
    private GridBagLayout gridBagLayout2 = new GridBagLayout();
    void jButton1_actionPerformed(ActionEvent e) {
    inputHour = JOptionPane.showInputDialog("Enter Hour");
    hh = Integer.parseInt(inputHour);
    inputMin = JOptionPane.showInputDialog("Enter minute");
    mm = Integer.parseInt(inputMin);
    if ( isHourValid & isMinValid )
    JOptionPane.showMessageDialog
    (null,"Time invalid" hh mm,"Invalid time", JOptionPane.PLAIN_MESSAGE);
    else
    JOptionPane.showMessageDialog
    (null, "Time valid" hh mm, "Valid time", JOptionPane.PLAIN_MESSAGE);
    }

  • Global KeyListener in JFrame with JDK 1.4

    Hi!
    I need to get some keyboard events in my JFrame or JDialog, no matter what subcomponent currently has the focus. I use this for example to display a help screen when the user hits F1.
    In JDK 1.3 I wrote in my constructor:
    this.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyPressed(KeyEvent e) {
    this_keyPressed(e);
    and then had a method
    void this_keyPressed(KeyEvent e) { ... }
    handling those events.
    In JDK 1.4 this code only works, if I call this.requestFocus(), but since the user should be able to TAB through the frame and hit F1 in every textfield, button etc., this is no solution --- as soon as "this" loses the focus, it won't work any more.
    I also tried using Key Bindings, but somehow I couldn't get it working.
    I need a solution for this problem that works with 1.3 as well as with 1.4!! Do you have any ideas of how to do this?
    Thanks for your help!!
    Nicolas Michael <[email protected]>

    looking at the source for Choice its not doing a great deal in add():
    pItems is a vector, so I guess if there is anything that could be slow its the native call, but again this seems unlikely?
    btw, if ur adding to the Choice box when its visible it will be a lot slower - is it possible to initialise before the applet is displayed?
    asjf
    ps. note the demo code above is adding numbers as strings, but I agree this shouldn't make any difference
    //from java/awt/Choice.java (same from 1.2.1 to 1.4.1 - have not checked 1.1)
    public void add(String item) {
       addItem(item);
    public void addItem(String item) {
       synchronized (this) {
          addItemNoInvalidate(item);
       if (valid)
       invalidate();
    private void addItemNoInvalidate(String item) {
       if (item == null) {
          throw new
          NullPointerException("cannot add null item to Choice");
       pItems.addElement(item);
       ChoicePeer peer = (ChoicePeer)this.peer;
       if (peer != null) {
          peer.addItem(item, pItems.size() - 1);
       if (selectedIndex < 0) {
          select(0);
    }

  • Using tab in JFrame

    I have an app with a JFrame and a few different JPanels in it. There are only a few different texboxes that you can put information into and i want to know is there anyway to set up the Tab order so that it will only go to them.
    Also when you tab to a textbox, how do you set it so that the contents of the box are selected/highlighted? you know so that when you type something new the old contents are overwritten
    thanks

    Thanks for putting me in the write direction, but i can't get it working just how i'd like it. I have a key listener in there that selects the contents of the Texbox if "TAB" is pressed. But i cant get the focus listener to work. i'd like it to select all if selected by mouse aswell.
    Here is my code, it's just a class of JTextbox that will only accept numbers.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class NumberField extends JTextField implements FocusListener {
      public class NumberFilterDocument extends PlainDocument {
        private StringBuffer __scratchBuffer;
        public NumberFilterDocument() {
          __scratchBuffer = new StringBuffer();
        public void insertString(int offset, String text, AttributeSet aset)
          throws BadLocationException
          if(text == null)
            return;
          __scratchBuffer.setLength(0);
          // Reject all strings that cause the contents of the field not
          // to be a valid number (i.e., string representation of a double)
          try {
            __scratchBuffer.append(getText(0, getLength()));
            __scratchBuffer.insert(offset, text);
            // Kludge: Append a 0 so that leading decimal points
            // and signs will be accepted
            __scratchBuffer.append('0');
          } catch(BadLocationException ble) {
            ble.printStackTrace();
            return;
          } catch(StringIndexOutOfBoundsException sioobe) {
            sioobe.printStackTrace();
            return;
          try {
            Double.parseDouble(__scratchBuffer.toString());
          } catch(NumberFormatException nfe) {
            // Resulting string will not be number, so reject it
            return;
          super.insertString(offset, text, aset);
    public NumberField(int columns) {
        super(columns);
        setDocument(new NumberFilterDocument());
    protected void processKeyEvent(KeyEvent ke){
              if( ke.getKeyCode() == KeyEvent.VK_TAB){
              this.selectAll();
               super.processKeyEvent( ke);
    public void focusGained(FocusEvent fe) {
                this.selectAll();
    public void focusLost(FocusEvent fe) {}
    }

Maybe you are looking for

  • How do I get rid of passcode to unlock screen. I do not want it

    I just downloaded ios7 and typed in a passcode, thinking it was just to use so others could not take my phone and delete stuff to use it for themselves. I did not know I had to use this passcode every time I wanted to get into my phone or my iPad. So

  • Where ara my music videos.

    I have 2 music videos in my iTunes and after syncing I don't know where to find them in my iPhone. I have checked them. Where can I find my videos to play them in my phone?

  • Minutes and seconds form field

    I need to format a field in a way that a user will enter 2 numbers separated by a comma (f.e. "20.02"), and the value will be stored as minutes and seconds (MM:SS), then I will need this value to be used in various time calculations.

  • Can you change the theme of a page?

    I have a whole site that I've created and I'm finding the black theme a little to dark for me. I want to change it to the lighter "modern" theme but cant seem to find a way. Do I have to totally recreate the whole site to do this?

  • Dock slow to appear

    My macbook suddenly has developed a very slow-appearance of the dock. The boot itself seems normal, through the stage where the gray apple disappears and the desktop is blank. Then it can take 5 to 10 minutes for the dock to appear. I have checked to