JOptionPane equivalent in AWT?

Is there an JOptionPane equivalent in AWT? If not, is there one available somewhere? I could write one myself but I don't want to re-invent the wheel as this would seem to be a basic component of any user interface. I am writing a simple inventory program for a Pocket PC using Geode as a runtime environment and it doesn't support swing.

int i = Aop.getStatus(this,"text");
static public class Aop extends Dialog implements ActionListener
     private Button  ok  = new Button("Ok");
     private Button  ca  = new Button("Cancel");
     static  int     oc  = 0;
public Aop(Frame frame, String text)
     super(frame,true);  
     setBounds(100,100,300,100); 
     setLayout(new GridLayout(2,1,5,5));
     add(new Label(text));
     add(new Label(""));
     add(ok);
     add(ca);
     ok.addActionListener(this);
     ca.addActionListener(this);
     addWindowListener(new WindowAdapter()
    {     public void windowClosing(WindowEvent ev)
               setVisible(false);
     setVisible(true);
public void actionPerformed(ActionEvent ae)
     if (ae.getSource() == ok) oc = 1;
     setVisible(false);
static public int getStatus(Frame frame, String text)
     Aop aop = new Aop(frame,text);
     aop.dispose();
     return(oc);
}Noah

Similar Messages

  • JOptionPane event blocking problem

    Hi,
    JOptionPane is causing me a problem.
    I have a simple frame that contains a text field and a button.
    Pressing the button should write something to the standard output.
    When the text field loses focus a JOptionPane in poped to the user.
    The following scenario is problematic:
    1. The text field owns the focus.
    2. The user presses the button.
    Expected result:
    The JOptionPane appears due to the lost focus event on the text field.
    After closing it some text is written to the standard output due to the action event on the button.
    The actual result:
    The JOptionPane does appears but after closing it nothing is written to the standard output. The button stays in a curious state (when the mouse hovers over the button the button looks pressed, and when the mouse doesn't hover over the button the button looks unpressed).
    Probable reason for this behaviour:
    The JOptionPane blocks all awt/swing events while it is opened. Some of the button code is perfomed due to the button press, but the ActionListener's actionPerformed method is not invoked.
    I need the actionPerfomed method to be invoked.
    Can anyone help me?
    Here is the source code:
    package test;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test {
    public Test() {
    public static void main(String[] args) {
    //Test test1 = new Test();
    final JFrame f = new JFrame("Test");
    JButton b = new JButton("Click Here");
    JTextField tField = new JTextField("Text", 10);
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    System.out.println("Button pressed!");
    tField.addFocusListener(new FocusAdapter() {
    public void focusLost(FocusEvent e) {
    if (e.isTemporary()) return;
    JOptionPane.showMessageDialog(f,
    "Focus lost",
    "Title",
    JOptionPane.INFORMATION_MESSAGE);
    JPanel content = (JPanel)f.getContentPane();
    content.setLayout(new BoxLayout(content, BoxLayout.X_AXIS));
    content.add(tField);
    content.add(Box.createHorizontalStrut(5));
    content.add(b);
    f.pack();
    f.show();
    Thanks,
    Shai

    Hello Shai.
    The JOptionPane seems to consume all events when its shown. (Check the stack after JOptionPane is shown.) I've solved a similar problem with the SwingUtilities.invokeLater() method. Maybe the following example will help:
    Runnable doDlgError = new Runnable() {
    public void run() {
    JOptionPane.showMessageDialog(this, "Error", "Error",
    JOptionPane.ERROR_MESSAGE);
    SwingUtilities.invokeLater(doDlgError);
    -Olaf

  • JOptionPane buttons in English and in another language?

    How do I change the language of the buttons in JOptionPane.showInputDialog?
    When I use the Traditional Chinese Windows, I see Chinese characters in the buttons.
    Can I have buttons in English even if I use the Traditional Chinese Windows? How? What web pages should I consult?
    Locale locale = Locale.getDefault();
        locale = new Locale("en", "US");
        Locale.setDefault(locale);does not help me to get the correct human language I prefer, e.g. on the confirm button.
    Edited by: tse2009 on Sep 12, 2009 6:22 AM

    Finally, I searched the web and got some ideas from:
    [http://jackywu1978.javaeye.com/blog/forum/97|http://jackywu1978.javaeye.com/blog/forum/97]
    Then, I can get the preferred language on the buttons on JOptionPane.
    import sun.awt.AppContext;
    public class getTheRightLanguagePreferred{
    Locale locale = Locale.getDefault();
        locale = new Locale("en", "US");
        Locale.setDefault(locale);
    AppContext.getAppContext().put("JComponent.defaultLocale", locale);
    }If you think that it is useful, please comment.

  • Hard awt problem.

    Introduction:
    An applet opens a modal java.awt.Dialog. The dialog contains a grid for displaying data. When the dialog is opened a separate thread is fetching data from the server. When the data arrives it is displayed in the grid in the dialog. The grid adds a scrollbar to itself whenever required (if the number of rows to be displayed is greater than the number of rows that fit inside the visible part of the grid).
    The code for adding/ removing the scrollbar is in the doLayout() method of the Grid.
    Problem:
    When I call invalidate() or validate() on the grid in the modal dialog the call hangs until the modal dialog returns from it�s setVisible() method. Why ???! It seems to be impossible to trigger a refresh of the layout of the grid programmatically. If I do not refresh the layout the scrollbar will only get added if I resize the window or in any other way make the system trigger a refresh of the layout. When I use the same Grid in any Container that is not a modal dialog there is no problem at all.
    What is the reason for this behavior, and how do I solve the problem?
    Ragnvald

    Thanks Luke, but that doesn�t work for me.
    This is an awt- applet, supposed to run on IE without signing or any additional downloading. That implies java 1.1.8 only. awt and no swing. And all the security restrictions apply as well.
    There must be a workaround!!!!
    The swing you provided has it�s equivalent in awt://1.1.8:
    Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(event);
    //and 1.2:
    Toolkit.getEventQueue().postEvent(new InvocationEvent(Toolkit.getDefaultToolkit(), runnable));The problem is the applet restriction. I get an exception:
    SecurityException at getSystemEventQueue
    There has got to be another solution!
    Ragnvald.

  • JOptionPane in applet - Help!

    Beginning to write a program and narrowed down the problem. When I ask for an input for the number of sticks to take away, the popup keeps coming back! How do I make the program accept the first input and stop?
    Thanks!
    import java.util.*;
    import java.applet.Applet;
    import javax.swing.JOptionPane;
    import java.awt.*;
    public class jaeglenim2 extends Applet
    public void paint(Graphics g)
    Graphics2D g2 = (Graphics2D)g;
    g2.drawString("The Game of Nim", 100,30);
    Random generator = new Random();
    boolean smart = true;
    boolean firstPlayer = true;
    int totalNumber = 10 + generator.nextInt(100);
    g2.drawString("Total number of sticks left: " + totalNumber,300,50);
    if (firstPlayer == true)
    g2.drawString("You go first.", 0,60);
    String input = JOptionPane.showInputDialog("Choose the number of sticks to take away.");
    int number = Integer.parseInt(input);
    g2.drawString("You take " + number, 0,80);
    totalNumber = totalNumber - number;
    g2.drawString("Total number of sticks left: " + totalNumber, 300, 80);
    else
    g2.drawString("Computer goes first.",0,60);
    System.exit(0)

    You shouldn't ask for input in the paint method, that method should restrict its actions to graphics.

  • Does anyone know how to...?

    Hi all,
    could someone explain how to set the background color of a cell in a JTable. I have read the tutoral and seen other wesites full of examples but i dont know how to incorpaorate a cell renderer into my table shown below.
    could someone show me. i would appreciate any help.
    import javax.swing.JTable;import javax.swing.table.AbstractTableModel;import javax.swing.JScrollPane;import javax.swing.JPanel;import javax.swing.SwingUtilities;import javax.swing.JOptionPane;import java.awt.*;import java.awt.event.*;public class AnimationPanel extends JPanel {     private boolean DEBUG = true;     JTable animationTable;     private Color highLiteColour;     public AnimationPanel() {          MyAnimationTable myTable = new MyAnimationTable();          animationTable = new JTable(myTable);          highLiteColour=Color.green;          //some useful tools          //*****************************************************          animationTable.setFont (new Font("Arial", Font.PLAIN, 18));          animationTable.setForeground(Color.black);          animationTable.setShowVerticalLines( false );          animationTable.setShowHorizontalLines( false );          animationTable.setCellSelectionEnabled(false);          //animationTable.setRowHeight(int row, int height);          animationTable.setBackground(highLiteColour, 4, 4);          // set Font          //mytable.setFont(font);          // set row height          //mytable.setRowHeight(20);          // set column width          //mytable.getColumnModel().getColumn( <column number> ).setPreferredWidth(<int>);         // preventing user from moving column around        //mytable.getTableHeader().setReorderingAllowed(allowColumnMoved);          //animationTable.setOpaque( false );          //headerLabel.setBackground(Color.yellow);          /*  public Color getForeground(int row, int column);            public void setForeground(Color color, int row, int column);            public void setForeground(Color color, int[] rows, int[] columns);            public Color getBackground(int row, int column);            public void setBackground(Color color, int row, int column);            public void setBackground(Color color, int[] rows, int[] columns);*/          //**********************************************          //table.setPreferredScrollableViewportSize(new Dimension(500, 70));          //Create the scroll pane and add the table to it.          //JScrollPane scrollPane = new JScrollPane(table);          //Add the scroll pane to this window.          //getContentPane().add(scrollPane, BorderLayout.CENTER);          //animationTable = new JTable(data, columnNames);          JScrollPane scrollPane = new JScrollPane(animationTable);          animationTable.setPreferredScrollableViewportSize(new Dimension(400, 210));          add(scrollPane);          /*addWindowListener(new WindowAdapter() {               public void windowClosing(WindowEvent e) {                    System.exit(0);               }          });*/     }     class MyAnimationTable extends AbstractTableModel {          Object[][] data = {          {" "," "," ", " ", " ", " ", " ", " ", " ", " "},          {" "," "," ", " ", " ", " ", " ", " ", " ", " "},          {"Carry: "," "," ", " ", " ", " ", " ", " ", " ", " "},          {"X: "," ","0", "0", "0", "0", "0", "0", "0", "0"},          {"Y: "," ","0", "0", "0", "0", "0", "0", "0", "0"},          {"Sum: "," "," ", " ", " ", " ", " ", " ", " ", " "},          {" "," "," ", " ", " ", " ", " ", " ", " ", " "},          {" "," "," ", " ", " ", " ", " ", " ", " ", " "},          {" "," "," ", " ", " ", " ", " ", " ", " ", " "},          {" "," "," ", " ", " ", " ", " ", " ", " ", " "},          {" "," "," ", " ", " ", " ", " ", " ", " ", " "},          {" "," "," ", " ", " ", " ", " ", " ", " ", " "},          {" "," "," ", " "," ", " ", " ", " ", " ", " "}          };          String[] columnNames = {" ", " ", "-128", "64 ", "32 ", "16",          "8", "4", "2", "U"};          public int getColumnCount() {               return columnNames.length;          }          public int getRowCount() {               return data.length;          }          public String getColumnName(int col) {               return columnNames[col];          }          public Object getValueAt(int row, int col) {               return data[row][col];          }          /*           * JTable uses this method to determine the default renderer/           * editor for each cell.  If we didn't implement this method,           * then the last column would contain text ("true"/"false"),           * rather than a check box.           */          public Class getColumnClass(int c) {               return getValueAt(0, c).getClass();          }          /*           * Don't need to implement this method unless your table's           * editable.           */          public boolean isCellEditable(int row, int col) {               //Note that the data/cell address is constant,               //no matter where the cell appears onscreen.                    return false;          }          /*           * Don't need to implement this method unless your table's           * data can change.           */           //anim.animationTable.setValueAt(" ",5,i);          public void setValueAt(Object value, int row, int col) {               /*if (DEBUG) {                    System.out.println("Setting value at " + row + "," + col                                           + " to " + value                                           + " (an instance of "                                           + value.getClass() + ")");               }*/               data[row][col] = value;               fireTableCellUpdated(row, col);               //if (data[0][col] instanceof Integer                //       && !(value instanceof Integer)) {                    //With JFC/Swing 1.1 and JDK 1.2, we need to create                    //an Integer from the value; otherwise, the column                    //switches to contain Strings.  Starting with v 1.3,                    //the table automatically converts value to an Integer,                    //so you only need the code in the 'else' part of this                    //'if' block.                    //XXX: See TableEditDemo.java for a better solution!!!                    /*try {                         data[row][col] = new Integer(value.toString());                         fireTableCellUpdated(row, col);                    } catch (NumberFormatException e) {                         JOptionPane.showMessageDialog(AnimationPanel.this,                              "The \"" + getColumnName(col)                              + "\" column accepts only integer values.");                    }*/             // } else {                    data[row][col] = value;                    fireTableCellUpdated(row, col);             // }               /*if (DEBUG) {                    System.out.println("New value of data:");                    //printDebugData();               }*/        }     }}

    still havent found a descent answer to this question,
    begining to think that no-one actually knows.What did you expect? You have posted probably the most
    unreadable message I have seen for a long time on this forum.
    Do yourself a favor and read the following: http://forum.java.sun.com/thread.jsp?forum=31&thread=271751
    Also, read this: http://forum.java.sun.com/features.jsp

  • Focus Problem on Solaris with jdk 1.3.1

    Hi all,
    We are having a focus problem on Solaris. The same code works fine on Windows without any problem.
    I am sending the test code and run steps below which you can compile and repeat the problem.
    NOTE: When we put a comment on the line "f1.requestFocus();" in TestFocus.java it works OK.
    Run Steps :
    1. Run TestFocus.class
    2. A JFrame appears with 2 text field and a button
    3. Try to write something on the text fields. It works OK.
    4. Click the button to open a new JFrame
    5. A new JFrame opens with a single text field and a button.
    6. Click the button to close the second frame
    7. You are now on the main JFrame
    8. Try to write something on the text fields. It works OK.
    9. Repeat the steps 4-7
    10. Try to write something on the text fields. You are able to focus and write on the first field. BUT you cannot select or write the second Field!
    JAVA SOURCE FILES :
    PenHesapListener.java :
    public interface PenHesapListener extends java.util.EventListener {
    void tamam_actionPerformed(java.util.EventObject newEvent);
    void iptal_actionPerformed(java.util.EventObject newEvent);
    ------PenHesapLisEventMulticaster.java----------------------------------
    public class PenHesapLisEventMulticaster extends java.awt.AWTEventMulticaster implements PenHesapListener {
    * Constructor to support multicast events.
    * @param a java.util.EventListener
    * @param b java.util.EventListener
    protected PenHesapLisEventMulticaster(java.util.EventListener a, java.util.EventListener b) {
         super(a, b);
    * Add new listener to support multicast events.
    * @return muhasebe.HesappenListener
    * @param a muhasebe.HesappenListener
    * @param b muhasebe.HesappenListener
    public static PenHesapListener add(PenHesapListener a, PenHesapListener b) {
         return (PenHesapListener)addInternal(a, b);
    * Add new listener to support multicast events.
    * @return java.util.EventListener
    * @param a java.util.EventListener
    * @param b java.util.EventListener
    protected static java.util.EventListener addInternal(java.util.EventListener a, java.util.EventListener b) {
         if (a == null) return b;
         if (b == null) return a;
         return new PenHesapLisEventMulticaster(a, b);
    * @return java.util.EventListener
    * @param oldl muhasebe.HesappenListener
    protected java.util.EventListener remove(PenHesapListener oldl) {
         if (oldl == a) return b;
         if (oldl == b) return a;
         java.util.EventListener a2 = removeInternal(a, oldl);
         java.util.EventListener b2 = removeInternal(b, oldl);
         if (a2 == a && b2 == b)
              return this;
         return addInternal(a2, b2);
    * Remove listener to support multicast events.
    * @return muhasebe.HesappenListener
    * @param l muhasebe.HesappenListener
    * @param oldl muhasebe.HesappenListener
    public static PenHesapListener remove(PenHesapListener l, PenHesapListener oldl) {
         if (l == oldl || l == null)
              return null;
         if(l instanceof PenHesapLisEventMulticaster)
              return (PenHesapListener)((PenHesapLisEventMulticaster) l).remove(oldl);
         return l;
    public void tamam_actionPerformed(java.util.EventObject newEvent) {
         ((PenHesapListener)a).tamam_actionPerformed(newEvent);
         ((PenHesapListener)b).tamam_actionPerformed(newEvent);
    public void iptal_actionPerformed(java.util.EventObject newEvent) {
         ((PenHesapListener)a).iptal_actionPerformed(newEvent);
         ((PenHesapListener)b).iptal_actionPerformed(newEvent);
    ---------TestFocus2.java-----------------------------------------
    import javax.swing.*;
    import javax.swing.JOptionPane;
    import java.awt.event.WindowAdapter;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.StringTokenizer;
    import java.text.SimpleDateFormat;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.Color;
    import java.util.Locale;
    import java.util.ResourceBundle;
    public class TestFocus2 extends JFrame implements ActionListener
         protected transient PenHesapListener PenhListener = null ;
         JTextField f10 = null;
         JButton b10= null ;
         JTextField f1 = new JTextField() ;
         JButton b1 = new JButton() ;
         JFrame f20 = null;
         public TestFocus2()
              getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
              getContentPane().add(f1);
              getContentPane().add(b1);
              pack();
              setVisible(true);
              b1.addActionListener(this);
         public void actionPerformed(ActionEvent e)
              if(e.getSource() == b1)
                   fireTamam_actionPerformed(e);
         public void addPenHesapListener(PenHesapListener newListener)
              PenhListener = PenHesapLisEventMulticaster.add(PenhListener, newListener);
              return;
         protected void fireTamam_actionPerformed(java.util.EventObject newEvent) {
              PenhListener.tamam_actionPerformed(newEvent);
              this.setVisible(false);
         protected void fireiptal_actionPerformed(java.util.EventObject newEvent) {
              PenhListener.iptal_actionPerformed(newEvent);
         public static void main(String x[])
              TestFocus2 gen01 = new TestFocus2();
    --------TestFocus.java-----------------------------------
    import javax.swing.*;
    import javax.swing.JOptionPane;
    import java.awt.event.WindowAdapter;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.StringTokenizer;
    import java.text.SimpleDateFormat;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.Color;
    import java.util.Locale;
    import java.util.ResourceBundle;
    import java.awt.Container;
    public class TestFocus extends JFrame implements ActionListener
         PenKreKart aPenKreKart = null ;      
         Container ctn = null;
         JTextField f10 = null;
         JButton b10= null ;
         JTextField f1 = new JTextField() ;
         JTextField f2 = new JTextField() ;
         JButton b1 = new JButton() ;
         JFrame f20 = null;
         public TestFocus()
              //aPenKreKart = new PenKreKart(true);
              //aPenKreKart.aTemelPencere.setVisible(false);
              getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
              getContentPane().add(f1);
              getContentPane().add(f2);
              getContentPane().add(b1);
              pack();
              setVisible(true);
              b1.addActionListener(this);
         public void actionPerformed(ActionEvent e)
              if(e.getSource() == b1)
                   pencere_islemi();
         // pencere koyma k?sm? .. begin                               
         public void pencere_islemi() {     
              ctn = this;
              ctn.setEnabled(false);
              TestFocus2 fpen = new TestFocus2();
              //aPenKreKart.aTemelPencere.setVisible(true); //buras?          
              //aPenKreKart.aTemelPencere.addPenHesapListener(new PenHesapListener() {
              fpen.addPenHesapListener(new PenHesapListener() {
                        // metod      tamam_actionPerformed begin...          
                        public void tamam_actionPerformed(java.util.EventObject newEvent) {
                             ctn.setEnabled(true);
                             ctn.requestFocus();
                             // Problem is when we comment the below line it works .....
                             f1.requestFocus();
                             System.out.println("tamam");
                        // metod      tamam_actionPerformed end...          
                        // metod      iptal_actionPerformed begin...          
                        public void iptal_actionPerformed(java.util.EventObject newEvent) {
                             ctn.setEnabled(true);
                             ctn.requestFocus();
                             System.out.println("iptal");
                        // metod      iptal_actionPerformed begin...          
         // pencere koyma k?sm? .. end                               
         public static void main(String x[])
              TestFocus gen01 = new TestFocus();

    Hi all,
    We are having a focus problem on Solaris. The same code works fine on Windows without any problem.
    I am sending the test code and run steps below which you can compile and repeat the problem.
    NOTE: When we put a comment on the line "f1.requestFocus();" in TestFocus.java it works OK.
    Run Steps :
    1. Run TestFocus.class
    2. A JFrame appears with 2 text field and a button
    3. Try to write something on the text fields. It works OK.
    4. Click the button to open a new JFrame
    5. A new JFrame opens with a single text field and a button.
    6. Click the button to close the second frame
    7. You are now on the main JFrame
    8. Try to write something on the text fields. It works OK.
    9. Repeat the steps 4-7
    10. Try to write something on the text fields. You are able to focus and write on the first field. BUT you cannot select or write the second Field!
    JAVA SOURCE FILES :
    PenHesapListener.java :
    public interface PenHesapListener extends java.util.EventListener {
    void tamam_actionPerformed(java.util.EventObject newEvent);
    void iptal_actionPerformed(java.util.EventObject newEvent);
    ------PenHesapLisEventMulticaster.java----------------------------------
    public class PenHesapLisEventMulticaster extends java.awt.AWTEventMulticaster implements PenHesapListener {
    * Constructor to support multicast events.
    * @param a java.util.EventListener
    * @param b java.util.EventListener
    protected PenHesapLisEventMulticaster(java.util.EventListener a, java.util.EventListener b) {
         super(a, b);
    * Add new listener to support multicast events.
    * @return muhasebe.HesappenListener
    * @param a muhasebe.HesappenListener
    * @param b muhasebe.HesappenListener
    public static PenHesapListener add(PenHesapListener a, PenHesapListener b) {
         return (PenHesapListener)addInternal(a, b);
    * Add new listener to support multicast events.
    * @return java.util.EventListener
    * @param a java.util.EventListener
    * @param b java.util.EventListener
    protected static java.util.EventListener addInternal(java.util.EventListener a, java.util.EventListener b) {
         if (a == null) return b;
         if (b == null) return a;
         return new PenHesapLisEventMulticaster(a, b);
    * @return java.util.EventListener
    * @param oldl muhasebe.HesappenListener
    protected java.util.EventListener remove(PenHesapListener oldl) {
         if (oldl == a) return b;
         if (oldl == b) return a;
         java.util.EventListener a2 = removeInternal(a, oldl);
         java.util.EventListener b2 = removeInternal(b, oldl);
         if (a2 == a && b2 == b)
              return this;
         return addInternal(a2, b2);
    * Remove listener to support multicast events.
    * @return muhasebe.HesappenListener
    * @param l muhasebe.HesappenListener
    * @param oldl muhasebe.HesappenListener
    public static PenHesapListener remove(PenHesapListener l, PenHesapListener oldl) {
         if (l == oldl || l == null)
              return null;
         if(l instanceof PenHesapLisEventMulticaster)
              return (PenHesapListener)((PenHesapLisEventMulticaster) l).remove(oldl);
         return l;
    public void tamam_actionPerformed(java.util.EventObject newEvent) {
         ((PenHesapListener)a).tamam_actionPerformed(newEvent);
         ((PenHesapListener)b).tamam_actionPerformed(newEvent);
    public void iptal_actionPerformed(java.util.EventObject newEvent) {
         ((PenHesapListener)a).iptal_actionPerformed(newEvent);
         ((PenHesapListener)b).iptal_actionPerformed(newEvent);
    ---------TestFocus2.java-----------------------------------------
    import javax.swing.*;
    import javax.swing.JOptionPane;
    import java.awt.event.WindowAdapter;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.StringTokenizer;
    import java.text.SimpleDateFormat;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.Color;
    import java.util.Locale;
    import java.util.ResourceBundle;
    public class TestFocus2 extends JFrame implements ActionListener
         protected transient PenHesapListener PenhListener = null ;
         JTextField f10 = null;
         JButton b10= null ;
         JTextField f1 = new JTextField() ;
         JButton b1 = new JButton() ;
         JFrame f20 = null;
         public TestFocus2()
              getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
              getContentPane().add(f1);
              getContentPane().add(b1);
              pack();
              setVisible(true);
              b1.addActionListener(this);
         public void actionPerformed(ActionEvent e)
              if(e.getSource() == b1)
                   fireTamam_actionPerformed(e);
         public void addPenHesapListener(PenHesapListener newListener)
              PenhListener = PenHesapLisEventMulticaster.add(PenhListener, newListener);
              return;
         protected void fireTamam_actionPerformed(java.util.EventObject newEvent) {
              PenhListener.tamam_actionPerformed(newEvent);
              this.setVisible(false);
         protected void fireiptal_actionPerformed(java.util.EventObject newEvent) {
              PenhListener.iptal_actionPerformed(newEvent);
         public static void main(String x[])
              TestFocus2 gen01 = new TestFocus2();
    --------TestFocus.java-----------------------------------
    import javax.swing.*;
    import javax.swing.JOptionPane;
    import java.awt.event.WindowAdapter;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.StringTokenizer;
    import java.text.SimpleDateFormat;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.Color;
    import java.util.Locale;
    import java.util.ResourceBundle;
    import java.awt.Container;
    public class TestFocus extends JFrame implements ActionListener
         PenKreKart aPenKreKart = null ;      
         Container ctn = null;
         JTextField f10 = null;
         JButton b10= null ;
         JTextField f1 = new JTextField() ;
         JTextField f2 = new JTextField() ;
         JButton b1 = new JButton() ;
         JFrame f20 = null;
         public TestFocus()
              //aPenKreKart = new PenKreKart(true);
              //aPenKreKart.aTemelPencere.setVisible(false);
              getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
              getContentPane().add(f1);
              getContentPane().add(f2);
              getContentPane().add(b1);
              pack();
              setVisible(true);
              b1.addActionListener(this);
         public void actionPerformed(ActionEvent e)
              if(e.getSource() == b1)
                   pencere_islemi();
         // pencere koyma k?sm? .. begin                               
         public void pencere_islemi() {     
              ctn = this;
              ctn.setEnabled(false);
              TestFocus2 fpen = new TestFocus2();
              //aPenKreKart.aTemelPencere.setVisible(true); //buras?          
              //aPenKreKart.aTemelPencere.addPenHesapListener(new PenHesapListener() {
              fpen.addPenHesapListener(new PenHesapListener() {
                        // metod      tamam_actionPerformed begin...          
                        public void tamam_actionPerformed(java.util.EventObject newEvent) {
                             ctn.setEnabled(true);
                             ctn.requestFocus();
                             // Problem is when we comment the below line it works .....
                             f1.requestFocus();
                             System.out.println("tamam");
                        // metod      tamam_actionPerformed end...          
                        // metod      iptal_actionPerformed begin...          
                        public void iptal_actionPerformed(java.util.EventObject newEvent) {
                             ctn.setEnabled(true);
                             ctn.requestFocus();
                             System.out.println("iptal");
                        // metod      iptal_actionPerformed begin...          
         // pencere koyma k?sm? .. end                               
         public static void main(String x[])
              TestFocus gen01 = new TestFocus();

  • Exception with DefaultTableModel

    Dear all,
    I want to instatiate this class and add to my JTable. However, I can't make an instance of this.
    If I extend AbstractTableModel my code is working fine but with DefaultTableModel I get the exception: "Exception caught in Scenegraph: null".
    Why do I get null exception in this code?
    !!!Please notice that the code is working fine with AbstractTableModel but not with DefaultTableModel!!!
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.*;
    import javax.swing.DefaultCellEditor;
    import java.util.Vector;
    //public class MyTableModel extends AbstractTableModel
    public class MyTableModel extends DefaultTableModel
    private boolean DEBUG = true;
    final String[] columnNames = {"IFCOBJECTS OR PROCESSES", "QUANTITY", "UNITS", "UNIT COST (?)", "TOTAL COST (?)"};
    static Object[][] data = new Object[IFC_Tree.totalVector.size()][5];
    static double totalCost = 0.0;
    public MyTableModel()
    for(int i=0; i < IFC_Tree.totalVector.size(); i++)
    Vector tmp = (Vector)(IFC_Tree.totalVector.elementAt(i));
    for(int j=0; j < tmp.size(); j++)
    Object value = tmp.get(j);
    data[i][j] = value;
    public int getColumnCount()
    return columnNames.length;
    public int getRowCount()
    return data.length;
    public String getColumnName(int col)
    return columnNames[col];
    public Object getValueAt(int row, int col)
    return data[row][col];
    public boolean isCellEditable(int row, int col)
    if (col < 3)
    return false;
    else if (col == 3)
    return true;
    else
    return false;
    public void setValueAt(Object value, int row, int col)
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    if(col == 3)
    try
    String str = (String)data[row][col];
    data[row][col+1] = new Double( ((Float)data[row][col-2]).doubleValue() * Double.valueOf(str).doubleValue() );
    fireTableCellUpdated(row, col+1);
    totalCost = 0.0;
    for (int k=0; k<TableDemo.costTable.getRowCount(); k++)
    totalCost = totalCost + ((Double)data[k][4]).doubleValue();
    data[TableDemo.costTable.getRowCount() - 1][4] = new Double (totalCost);
    fireTableCellUpdated(TableDemo.costTable.getRowCount() - 1, 4);
    catch(Exception ex)
    System.out.println("Exception caught in MyTableModel class: INVALID INPUT " + ex.getMessage());
    System.out.println(":-(");
    private void printDebugData()
    int numRows = getRowCount();
    int numCols = getColumnCount();
    for (int i=0; i < numRows; i++)
    System.out.print("row " + i + ":");
    for (int j=0; j < numCols; j++)
    System.out.print(" " + data[i][j]);
    System.out.println();
    }

    Hi vreznik;
    Actually, my original code is just exactly the same you suggested.
    I get the exception with DefaultTableModel only.
    public MyTableModel()
    //System.out.println("TableModel_1");
    for(int h=0; h < IFC_Tree.totalVector.size(); h++)
    Vector tmp = (Vector)(IFC_Tree.totalVector.elementAt(i));
    for(int j=0; j < tmp.size(); j++)
    Object value = tmp.get(j);
    data[h][j] = value;
    }

  • Lots of problems with program

    Guys,
    I really am having a lot of problems with a program. I got the program to compile but it looks absolutely nothing like it is supposed to look. I have a deadline for tomorrow and sent my teacher an email but the chances of him getting back to me by tomorrow night for a weekend is pretty much slim to none. Anyways I am sending my output and if anyone could give me advice or feedback on why it does not look right if it is something small and if its alot of things go ahead and call me dumb.
    here is my code:
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.awt.event.*;
    public class Checkerboard extends Frame implements ActionListener
         private Panel topPanel;
         private TextArea topDisplay[];
         private Panel bottomPanel;
         private TextField startField = new TextField(10);
         private TextField stopField = new TextField(10);
         private TextField stepField = new TextField(10);
         private Label startLabel = new Label ("Start");
         private Label stopLabel = new Label ("Stop");
         private Label stepLabel = new Label ("Step");
         private Button goButton;
         private Button clearButton;
         private boolean clearText;
         private boolean first;
         private int start;
         private int stop;
         private int step;
         //constructor methods
         public Checkerboard()
              //construct components and initialize beginning values
              topPanel = new Panel();
              topDisplay = new TextArea[16];
              goButton = new Button("Go");
              clearButton = new Button("Clear");
              first = true;
              bottomPanel = new Panel();
              int start = 0;
              int stop = 0;
              int step = 0;
              bottomPanel.add(startField);
              bottomPanel.add(stopField);
              bottomPanel.add(stepField);
              bottomPanel.add(startLabel);
              bottomPanel.add(stopLabel);
              bottomPanel.add(stepLabel);
              bottomPanel.add(goButton);
              goButton.addActionListener(this);
              bottomPanel.add(clearButton);
              clearButton.addActionListener(this);
              clearText = true;
              //set layouts for the Frame and Panels
              setLayout(new BorderLayout());
              topPanel.setLayout(new GridLayout(4, 4, 10, 10));
              bottomPanel.setLayout(new GridLayout(3, 3, 5, 5));
              //construct the Display
              for(int i = 1; i <= 15; i++)
                        topDisplay[i] = new TextArea(null, 3, 5, 3);
              //set color to the panel
              //row 1
              for(int x = 1; x <= 4; x++)
              //set color for
              setBackground(Color.white);
              //row 2
              for(int x = 5; x <= 8; x++)
              //set color for
              setBackground(Color.white);
              //row 3
              for(int x = 9; x <= 12; x++)
              //set color for
              setBackground(Color.white);
              //row 4
              for(int x = 13; x <= 16; x++)
              //set color for
              setBackground(Color.white);
              //add components to frame
              add(topPanel, BorderLayout.NORTH);
              add(bottomPanel, BorderLayout.CENTER);
              //allow the x to close the application
              addWindowListener(new WindowAdapter()
                        public void windowclosing(WindowEvent e)
                                  System.exit(0);
                   } //end window adapter
         public static void main(String args[])
              Checkerboard f = new Checkerboard();
              f.setTitle("Checkerboard Array");
              f.setBounds(50, 100, 300, 400);
              f.setLocationRelativeTo(null);
              f.setVisible(true);
         } //end main
         public void actionPerformed(ActionEvent e)
              //convert data in TextField to int
              int start = Integer.parseInt(startField.getText());
              int stop = Integer.parseInt(stopField.getText());
              int step = Integer.parseInt(stepField.getText());
              for(int i = 1; i <=16; i++)
              setBackground(Color.blue);
              for(int i = start; i <= stop; i++)
              setBackground(Color.yellow);
              //test clear
              String arg = e.getActionCommand();
              //clear button was clicked
              if(arg.equals("Clear"))
                   clearText = true;
                   start = 0;
                   stop = 0;
                   step = 0;
                   first = true;
                   setBackground(Color.white);
                   startField.requestFocus();
              } //end the if clear
         }//end action listener
    }//end classThis will incorporate arrays, for loops, and Frames all in one.
    Create a panel containing an array of 16 TextArea components that change color to correspond with the start, stop, and step values entered by the user. Perform the following tasks to create the Checkerboard Array application shown below. When the user enters the start, stop, and step fields and then clicks the Go button, the results are also shown below.
    1.     Call your application Checkerboard.java
    2.     You will need the following variables� declare them as private:
    a.     16 component TextArea array
    b.     a Panel to hold the array
    c.     3 TextField components with length of 10
    d.     3 int variables to receive the start, stop, and step values
    e.     3 Labels to display the words Start, Stop, and Step
    f.     a Go button
    g.     a Clear button
    h.     a Panel to hold the 3 TextFields, 3 Labels, and the 2 Buttons
    3.     Create a constructor method to:
    a.     construct each of the components declared above and initializes the start, stop, and step variables to zero (when constructing the TextArea components, use the following parameters: null, 3, 5, 3)
    b.     set the Frame layout to BorderLayout
    c.     write a for loop to loop the array and set each of the 16 TextArea components in that array so they cannot be edited. In the same loop, set each of the TextArea components text to be 1 more than the index number. Also in this same loop, set the background of each of the TextArea components to white.
    d.     set the Panel for the TextArea components to GridLayout with 4 rows, 4 columns, and both gaps set to 10
    e.     set the Panel for the TextFields, Labels, and button to GridLayout with 3 rows, 3 columns, and both gaps set to 5
    f.     add the components to their respective Panels
    g.     make the buttons clickable
    h.     place the Panels in the Frame� put one in the NORTH and one in the CENTER
    i.     Enter the addWindowListener() method described in the chapter� this is the method that overrides the click of the X so it terminates the application
    4.     In your actionPerformed() method:
    a.     convert the data in your TextFields to int and store them in the variables declared above
    b.     write a loop that goes through the array setting every background color to blue
    c.     write another loop that�s based on the user inputs. Each time the loop is executed, change the background color to yellow (so� start your loop at the user�s specified starting condition. You�ll stop at the user�s specified stopping value. You�ll change the fields to yellow every time you increment your loop based on the step value. REMEMBER: Your displayed values are 1 off from your index numbers!!)
    5.     Write a main() method that creates an instance of the Checkerboard Frame.
    a.     set the bounds for the frame to 50, 100, 300, 400
    b.     set the title bar caption to Checkerboard Array
    c.     use the setVisible() method to display the application Frame during execution
    6.     After you get all of this complete, include error handling to make sure:
    a.     the values entered in the TextFields are valid integers
    b.     the start value is greater than or equal to 1 and less than or equal to 16
    c.     the stop value is greater than or equal to 1 and less than or equal to 16
    d.     the step value is greater than or equal to 1 and less than or equal to 16
    e.     the start condition is less than the stop condition
    f.     when an error occurs, give an error message in a dialog box that is specific to their error, remove the text from the invalid field, and put the cursor in that field so the user has a chance to re-enter� this can be accomplished by using multiple try/catch statements
    g.     only change the colors if the numbers are valid
    7.     Create a clear button as seen in the example below. This button should:
    a.     clear out all 3 TextFields
    b.     change the background color of all TextArea array elements to white
    c.     put the cursor in the start field
    8.     Document!!
    I know you guys are probably busy with your own stuff but any help and I would certainly appreciate it

    got the yellow boxes to come up but just one box.....so is there something wrong with my yellow set background because I am not seeing any more errors
    //packages to import
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.awt.event.*;
    public class Checkerboard extends Frame implements ActionListener
         private Panel topPanel;
         private TextArea topDisplay[];
         private Panel bottomPanel;
         private TextField startField = new TextField(10);
         private TextField stopField = new TextField(10);
         private TextField stepField = new TextField(10);
         private Label startLabel = new Label ("Start");
         private Label stopLabel = new Label ("Stop");
         private Label stepLabel = new Label ("Step");
         private Button goButton;
         private Button clearButton;
         private boolean clearText;
         private boolean first;
         private int start;
         private int stop;
         private int step;
         //constructor methods
         public Checkerboard()
              //construct components and initialize beginning values
              topPanel = new Panel();
              topDisplay = new TextArea[16];
              goButton = new Button("Go");
              clearButton = new Button("Clear");
              first = true;
              bottomPanel = new Panel();
              int start = 0;
              int stop = 0;
              int step = 0;
              bottomPanel.add(startField);
              bottomPanel.add(stopField);
              bottomPanel.add(stepField);
              bottomPanel.add(startLabel);
              bottomPanel.add(stopLabel);
              bottomPanel.add(stepLabel);
              bottomPanel.add(goButton);
              goButton.addActionListener(this);
              bottomPanel.add(clearButton);
              clearButton.addActionListener(this);
              clearText = true;
              //set layouts for the Frame and Panels
              setLayout(new BorderLayout());
              topPanel.setLayout(new GridLayout(4, 4, 10, 10));
              bottomPanel.setLayout(new GridLayout(3, 3, 5, 5));
              //construct the Display
              for(int i = 0; i <= 15; i++)
                        topDisplay[i] = new TextArea(null, 3, 5, 3);
                        topDisplay.setText(String.valueOf(i+1));
                        topDisplay[i].setEditable(false);
                        topPanel.add(topDisplay[i]);
              //add components to frame
              add(topPanel, BorderLayout.NORTH);
              add(bottomPanel, BorderLayout.CENTER);
              //allow the x to close the application
              addWindowListener(new WindowAdapter()
                        public void windowClosing(WindowEvent e)
                                  System.exit(0);
                   } //end window adapter
              public static void main(String args[])
                        Checkerboard f = new Checkerboard();
                        f.setTitle("Checkerboard Array");
                        f.setBounds(50, 100, 300, 400);
                        f.setLocationRelativeTo(null);
                        f.setVisible(true);
                   } //end main
                   public void actionPerformed(ActionEvent e)
                        boolean done = false;
                        //test go
                        String arg = e.getActionCommand();
                        //go button was clicked
                        if(arg.equals("Go"))
                   //convert data in TextField to int
                   int start = Integer.parseInt(startField.getText());
                   int stop = Integer.parseInt(stopField.getText());
                   int step = Integer.parseInt(stepField.getText());
                   while(!done)
                        try
                             if((start <= 1) && (start > 16)) throw new NumberFormatException();
                             else done = true;
                        } //end try
                        catch (NumberFormatException f)
                             JOptionPane.showMessageDialog(null, "You must enter start between 1 and 16", "Error", JOptionPane.ERROR_MESSAGE);
                             startField.setText(" ");
                             startField.requestFocus();
                        } //end catch
                        try
                             if ((stop < 1) && (stop > 16)) throw new NumberFormatException();
                             else done = true;
                        } //end try
                        catch (NumberFormatException f)
                             JOptionPane.showMessageDialog(null, "You must enter stop between 1 and 16", "Error", JOptionPane.ERROR_MESSAGE);
                             stopField.setText(" ");
                             stopField.requestFocus();
                        } //end catch
                        try
                             if ((step < 1) && (step > 16)) throw new NumberFormatException();
                             else done = true;
                        } //end try
                        catch (NumberFormatException f)
                             JOptionPane.showMessageDialog(null, "You must enter step between 1 and 16", "Error", JOptionPane.ERROR_MESSAGE);
                             stepField.setText(" ");
                             stepField.requestFocus();
                        } //end catch
                        try
                             if (start > stop) throw new NumberFormatException();
                             else done = true;
                        } //end try
                        catch (NumberFormatException f)
                             JOptionPane.showMessageDialog(null, "Stop cannot be larger than start", "Error", JOptionPane.ERROR_MESSAGE);
                             startField.setText(" ");
                             stopField.setText(" ");
                             stepField.setText(" ");
                             startField.requestFocus();
                        } //end catch
              } //end while
                        for(int i = 0; i <=15; i++)
                        topDisplay[i].setBackground(Color.blue);
                        for(int i = start; i <= stop; step++)
                        topDisplay[i].setBackground(Color.yellow);
                   } //end the if go
                   //clear button was clicked
                   if(arg.equals("Clear"))
                        clearText = true;
                        startField.setText("");
                        stopField.setText("");
                        stepField.setText("");
                        first = true;
                        setBackground(Color.white);
                        startField.requestFocus();
                   } //end the if clear
         }//end action listener
    }//end class

  • Retrieve 4 inputs from one dialog box at a time

    I have a Jframe and when I click a button I want it to open a new Jdialog box. I want 4 different input fields. Two will be for strings, 1 int, 1 double. But I can't get it to open up a dialog with all of those things. Will I have to accept them all as strings then convert them to double and int? and what will the code for 4 input fields in a dialog box look like? If you need more info just ask... And I'm using Netbeans, if this makes it easier.

    You could design a custom JDialog or whip up something simpler with JOptionPane:
    import java.awt.*;
    import javax.swing.*;
    public class JOptionPaneExample {
        public static void main(String[] args) {
            JPanel p = new JPanel(new GridLayout(2, 2));
            p.add(new JLabel("name:"));
            p.add(new JTextField(10));
            p.add(new JLabel("age:"));
            p.add(new JTextField(10));
            int result = JOptionPane.showConfirmDialog(null, p, "title",
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.PLAIN_MESSAGE);
    }

  • For loop issue and error exception

    I am finishing up a program and having a few issues....I can send my instructions so it may seem easier to what I want...the first issue deals with the for loop for the 2nd for loop in the actionperformed when i click on go it does not change any of the boxes to yellow
    Also when I check for errors it does not check with the code I have...I know it says on the instructions to use try\catch but I am just going to use if statements because I am not very familar with the try\catch and will accept some points takin off...any help with this by tonight id really appreciate it as long as noone is too busy...Thanks
    instructions:
    This will incorporate arrays, for loops, and Frames all in one.
    Create a panel containing an array of 16 TextArea components that change color to correspond with the start, stop, and step values entered by the user. Perform the following tasks to create the Checkerboard Array application shown below. When the user enters the start, stop, and step fields and then clicks the Go button, the results are also shown below.
    1.     Call your application Checkerboard.java
    2.     You will need the following variables� declare them as private:
    a.     16 component TextArea array
    b.     a Panel to hold the array
    c.     3 TextField components with length of 10
    d.     3 int variables to receive the start, stop, and step values
    e.     3 Labels to display the words Start, Stop, and Step
    f.     a Go button
    g.     a Clear button
    h.     a Panel to hold the 3 TextFields, 3 Labels, and the 2 Buttons
    3.     Create a constructor method to:
    a.     construct each of the components declared above and initializes the start, stop, and step variables to zero (when constructing the TextArea components, use the following parameters: null, 3, 5, 3)
    b.     set the Frame layout to BorderLayout
    c.     write a for loop to loop the array and set each of the 16 TextArea components in that array so they cannot be edited. In the same loop, set each of the TextArea components text to be 1 more than the index number. Also in this same loop, set the background of each of the TextArea components to white.
    d.     set the Panel for the TextArea components to GridLayout with 4 rows, 4 columns, and both gaps set to 10
    e.     set the Panel for the TextFields, Labels, and button to GridLayout with 3 rows, 3 columns, and both gaps set to 5
    f.     add the components to their respective Panels
    g.     make the buttons clickable
    h.     place the Panels in the Frame� put one in the NORTH and one in the CENTER
    i.     Enter the addWindowListener() method described in the chapter� this is the method that overrides the click of the X so it terminates the application
    4.     In your actionPerformed() method:
    a.     convert the data in your TextFields to int and store them in the variables declared above
    b.     write a loop that goes through the array setting every background color to blue
    c.     write another loop that�s based on the user inputs. Each time the loop is executed, change the background color to yellow (so� start your loop at the user�s specified starting condition. You�ll stop at the user�s specified stopping value. You�ll change the fields to yellow every time you increment your loop based on the step value. REMEMBER: Your displayed values are 1 off from your index numbers!!)
    5.     Write a main() method that creates an instance of the Checkerboard Frame.
    a.     set the bounds for the frame to 50, 100, 300, 400
    b.     set the title bar caption to Checkerboard Array
    c.     use the setVisible() method to display the application Frame during execution
    6.     After you get all of this complete, include error handling to make sure:
    a.     the values entered in the TextFields are valid integers
    b.     the start value is greater than or equal to 1 and less than or equal to 16
    c.     the stop value is greater than or equal to 1 and less than or equal to 16
    d.     the step value is greater than or equal to 1 and less than or equal to 16
    e.     the start condition is less than the stop condition
    f.     when an error occurs, give an error message in a dialog box that is specific to their error, remove the text from the invalid field, and put the cursor in that field so the user has a chance to re-enter� this can be accomplished by using multiple try/catch statements
    g.     only change the colors if the numbers are valid
    7.     Create a clear button as seen in the example below. This button should:
    a.     clear out all 3 TextFields
    b.     change the background color of all TextArea array elements to white
    c.     put the cursor in the start field
    8.     Document!!
    my code is:
    //packages to import
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.awt.event.*;
    public class Checkerboard extends Frame implements ActionListener
         private Panel topPanel;
         private TextArea topDisplay[];
         private Panel bottomPanel;
         private TextField startField = new TextField(10);
         private TextField stopField = new TextField(10);
         private TextField stepField = new TextField(10);
         private Label startLabel = new Label ("Start");
         private Label stopLabel = new Label ("Stop");
         private Label stepLabel = new Label ("Step");
         private Button goButton;
         private Button clearButton;
         private boolean clearText;
         private boolean first;
         private int start;
         private int stop;
         private int step;
         //constructor methods
         public Checkerboard()
              //construct components and initialize beginning values
              topPanel = new Panel();
              topDisplay = new TextArea[16];
              goButton = new Button("Go");
              clearButton = new Button("Clear");
              first = true;
              bottomPanel = new Panel();
              int start = 0;
              int stop = 0;
              int step = 0;
              bottomPanel.add(startField);
              bottomPanel.add(stopField);
              bottomPanel.add(stepField);
              bottomPanel.add(startLabel);
              bottomPanel.add(stopLabel);
              bottomPanel.add(stepLabel);
              bottomPanel.add(goButton);
              goButton.addActionListener(this);
              bottomPanel.add(clearButton);
              clearButton.addActionListener(this);
              clearText = true;
              //set layouts for the Frame and Panels
              setLayout(new BorderLayout());
              topPanel.setLayout(new GridLayout(4, 4, 10, 10));
              bottomPanel.setLayout(new GridLayout(3, 3, 5, 5));
              //construct the Display
              for(int i = 0; i <= 15; i++)
                        topDisplay[i] = new TextArea(null, 3, 5, 3);
                        topDisplay.setText(String.valueOf(i+1));
                        topDisplay[i].setEditable(false);
                        topPanel.add(topDisplay[i]);
              //add components to frame
              add(topPanel, BorderLayout.NORTH);
              add(bottomPanel, BorderLayout.CENTER);
              //allow the x to close the application
              addWindowListener(new WindowAdapter()
                        public void windowClosing(WindowEvent e)
                                  System.exit(0);
                   } //end window adapter
         public static void main(String args[])
              Checkerboard f = new Checkerboard();
              f.setTitle("Checkerboard Array");
              f.setBounds(50, 100, 300, 400);
              f.setLocationRelativeTo(null);
              f.setVisible(true);
         } //end main
         public void actionPerformed(ActionEvent e)
              //test go
              String arg = e.getActionCommand();
              //go button was clicked
              if(arg.equals("Go"))
                   //convert data in TextField to int
                   int start = Integer.parseInt(startField.getText());
                   int stop = Integer.parseInt(stopField.getText());
                   int step = Integer.parseInt(stepField.getText());
                   if((start <= 1) && (start > 16))
                        JOptionPane.showMessageDialog(null, "You must enter start between 1 and 16", "Error", JOptionPane.ERROR_MESSAGE);
                        startField.setText(" ");
                        startField.requestFocus();
                   if ((stop < 1) && (stop > 16))
                        JOptionPane.showMessageDialog(null, "You must enter stop between 1 and 16", "Error", JOptionPane.ERROR_MESSAGE);
                        stopField.setText(" ");
                        stopField.requestFocus();
                   if ((step < 1) && (step > 16))
                        JOptionPane.showMessageDialog(null, "You must enter step between 1 and 16", "Error", JOptionPane.ERROR_MESSAGE);
                        stepField.setText(" ");
                        stepField.requestFocus();
                   if (start < stop)
                        JOptionPane.showMessageDialog(null, "Stop cannot be larger than start", "Error", JOptionPane.ERROR_MESSAGE);
                        startField.setText(" ");
                        stopField.setText(" ");
                        stepField.setText(" ");
                        startField.requestFocus();
                   for(int i = 0; i <=16; i++)
                   topDisplay[i].setBackground(Color.blue);
                   for(int i = start; i <= stop; step++)
                   topDisplay[i].setBackground(Color.yellow);
              } //end the if go
              //clear button was clicked
              if(arg.equals("Clear"))
                   clearText = true;
                   startField.setText("");
                   stopField.setText("");
                   stepField.setText("");
                   first = true;
                   setBackground(Color.white);
                   startField.requestFocus();
              } //end the if clear
         }//end action listener
    }//end class

    got the yellow boxes to come up but just one box.....so is there something wrong with my yellow set background because I am not seeing any more errors
    //packages to import
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.awt.event.*;
    public class Checkerboard extends Frame implements ActionListener
         private Panel topPanel;
         private TextArea topDisplay[];
         private Panel bottomPanel;
         private TextField startField = new TextField(10);
         private TextField stopField = new TextField(10);
         private TextField stepField = new TextField(10);
         private Label startLabel = new Label ("Start");
         private Label stopLabel = new Label ("Stop");
         private Label stepLabel = new Label ("Step");
         private Button goButton;
         private Button clearButton;
         private boolean clearText;
         private boolean first;
         private int start;
         private int stop;
         private int step;
         //constructor methods
         public Checkerboard()
              //construct components and initialize beginning values
              topPanel = new Panel();
              topDisplay = new TextArea[16];
              goButton = new Button("Go");
              clearButton = new Button("Clear");
              first = true;
              bottomPanel = new Panel();
              int start = 0;
              int stop = 0;
              int step = 0;
              bottomPanel.add(startField);
              bottomPanel.add(stopField);
              bottomPanel.add(stepField);
              bottomPanel.add(startLabel);
              bottomPanel.add(stopLabel);
              bottomPanel.add(stepLabel);
              bottomPanel.add(goButton);
              goButton.addActionListener(this);
              bottomPanel.add(clearButton);
              clearButton.addActionListener(this);
              clearText = true;
              //set layouts for the Frame and Panels
              setLayout(new BorderLayout());
              topPanel.setLayout(new GridLayout(4, 4, 10, 10));
              bottomPanel.setLayout(new GridLayout(3, 3, 5, 5));
              //construct the Display
              for(int i = 0; i <= 15; i++)
                        topDisplay[i] = new TextArea(null, 3, 5, 3);
                        topDisplay.setText(String.valueOf(i+1));
                        topDisplay[i].setEditable(false);
                        topPanel.add(topDisplay[i]);
              //add components to frame
              add(topPanel, BorderLayout.NORTH);
              add(bottomPanel, BorderLayout.CENTER);
              //allow the x to close the application
              addWindowListener(new WindowAdapter()
                        public void windowClosing(WindowEvent e)
                                  System.exit(0);
                   } //end window adapter
              public static void main(String args[])
                        Checkerboard f = new Checkerboard();
                        f.setTitle("Checkerboard Array");
                        f.setBounds(50, 100, 300, 400);
                        f.setLocationRelativeTo(null);
                        f.setVisible(true);
                   } //end main
                   public void actionPerformed(ActionEvent e)
                        boolean done = false;
                        //test go
                        String arg = e.getActionCommand();
                        //go button was clicked
                        if(arg.equals("Go"))
                   //convert data in TextField to int
                   int start = Integer.parseInt(startField.getText());
                   int stop = Integer.parseInt(stopField.getText());
                   int step = Integer.parseInt(stepField.getText());
                   while(!done)
                        try
                             if((start <= 1) && (start > 16)) throw new NumberFormatException();
                             else done = true;
                        } //end try
                        catch (NumberFormatException f)
                             JOptionPane.showMessageDialog(null, "You must enter start between 1 and 16", "Error", JOptionPane.ERROR_MESSAGE);
                             startField.setText(" ");
                             startField.requestFocus();
                        } //end catch
                        try
                             if ((stop < 1) && (stop > 16)) throw new NumberFormatException();
                             else done = true;
                        } //end try
                        catch (NumberFormatException f)
                             JOptionPane.showMessageDialog(null, "You must enter stop between 1 and 16", "Error", JOptionPane.ERROR_MESSAGE);
                             stopField.setText(" ");
                             stopField.requestFocus();
                        } //end catch
                        try
                             if ((step < 1) && (step > 16)) throw new NumberFormatException();
                             else done = true;
                        } //end try
                        catch (NumberFormatException f)
                             JOptionPane.showMessageDialog(null, "You must enter step between 1 and 16", "Error", JOptionPane.ERROR_MESSAGE);
                             stepField.setText(" ");
                             stepField.requestFocus();
                        } //end catch
                        try
                             if (start > stop) throw new NumberFormatException();
                             else done = true;
                        } //end try
                        catch (NumberFormatException f)
                             JOptionPane.showMessageDialog(null, "Stop cannot be larger than start", "Error", JOptionPane.ERROR_MESSAGE);
                             startField.setText(" ");
                             stopField.setText(" ");
                             stepField.setText(" ");
                             startField.requestFocus();
                        } //end catch
              } //end while
                        for(int i = 0; i <=15; i++)
                        topDisplay[i].setBackground(Color.blue);
                        for(int i = start; i <= stop; step++)
                        topDisplay[i].setBackground(Color.yellow);
                   } //end the if go
                   //clear button was clicked
                   if(arg.equals("Clear"))
                        clearText = true;
                        startField.setText("");
                        stopField.setText("");
                        stepField.setText("");
                        first = true;
                        setBackground(Color.white);
                        startField.requestFocus();
                   } //end the if clear
         }//end action listener
    }//end class

  • Help in understanding GUI's!!!

    Hi everyone, I'm new to this type of forum, but I figured it can't hurt to ask for help wherever I can find it. I'm in a Java II class right now, and I'm having a hard time understanding how to build a GUI. I created the programs provided in the book, but I keep getting an error upon compiling, "unreachable statement". I have included my code, I'm not sure how to paste it properly, so I'm sorry if it's hard to read. Please let me know if anyone can help me out here. I'm not sure how much it matters, but the Java Machine we are using is 1.4.2... Thanks for any help!!!
    **The first part is this: Rooms.java**
         Chapter 5:     Reserve a Party Room
         Programmer:     Sabrina M. Liberski
         Date:          December 16, 2007
         Filename:     Rooms.java
         Purpose:     This is an external class called by the Reservations.java program.
                        Its constructor method receives the number of nonsmoking and smoking rooms
                        and then creates an array of empty rooms.  The bookRoom() method accepts a
                        boolean value and returns a room number.
    public class Rooms
         //declare class variables
         int numSmoking;
         int numNonSmoking;
         boolean occupied[];
         public Rooms(int non, int sm)
              //construct an array of boolean values equal to the total number of rooms
              occupied = new boolean[sm+non];
              for(int i=0; i<(sm+non); i++)
                   occupied[i] = false; //set each occupied room to false or empty
              //initialize the number of smoking and nonsmoking rooms
              numSmoking = sm;
              numNonSmoking = non;
         public int bookRoom(boolean smoking)
              int begin, end, roomNumber=0;
              if(!smoking)
                   begin = 0;
                   end = numNonSmoking;
              else
                   begin = numNonSmoking;
                   end = numSmoking+numNonSmoking;
              for(int i=begin; i<end; i++)
                   if(!occupied) //if room is not occupied
                        occupied[i] = true;
                        roomNumber = i+1;
                        i = end; //to exit loop
              return roomNumber;
    }**The second part is:**  /*
         Chapter 5:     Reserve a Party Room
         Programmer:     Sabrina M. Liberski
         Date:          December 16, 2007
         Filename:     Reservations.java
         Purpose:     This program creates a windowed application to reserve a party room.
                        It calls an external class named Rooms.
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.awt.event.*;
    public class Reservations extends Frame implements ActionListener
         Color lightRed = new Color(255, 90, 90);
         Color lightGreen = new Color(140, 215, 40);
         Rooms room = new Rooms(5,3);
         Panel roomPanel = new Panel();
              TextArea roomDisplay[] = new TextArea[9];
         Panel buttonPanel = new Panel();
              Button bookButton = new Button("Book Room");
         Panel inputPanel = new Panel();
              Label custNameLabel = new Label("Name:");
              TextField nameField = new TextField(15);
              Label custPhoneLabel = new Label("Phone number:");
              TextField phoneField = new TextField(15);
              Label numLabel = new Label("Number in party:");
              Choice numberOfGuests = new Choice();
              CheckboxGroup options = new CheckboxGroup();
                   Checkbox nonSmoking = new Checkbox("Nonsmoking", false, options);
                   Checkbox smoking = new Checkbox("Smoking", false, options);
                   Checkbox hidden = new Checkbox("", true, options);
         public Reservations()
              //set Layouts for frame and three panels
              this.setLayout(new BorderLayout());
                   roomPanel.setLayout(new GridLayout(2,4,10,10));
                   buttonPanel.setLayout(new FlowLayout());
                   inputPanel.setLayout(new FlowLayout());
              //add components to room panel
              for (int i=1; 1<9; i++)
                   roomDisplay[i] = new TextArea(null,3,5,3);
                   if (i<6)
                        roomDisplay[i].setText("Room " + i + " Nonsmoking");
                   else
                        roomDisplay[i].setText("Room " + i + " Smoking");
                   roomDisplay[i].setEditable(false);
                   roomDisplay[i].setBackground(lightGreen);
                   roomPanel.add(roomDisplay[i]);
              //add components to button panel
              buttonPanel.add(bookButton);
              //add components to input panel
              inputPanel.add(custNameLabel);
              inputPanel.add(nameField);
              inputPanel.add(custPhoneLabel);
              inputPanel.add(phoneField);
              inputPanel.add(numLabel);
              inputPanel.add(numberOfGuests);
                   for(int i = 8; i<=20; i++)
                        numberOfGuests.add(String.valueOf(i));
              inputPanel.add(nonSmoking);
              inputPanel.add(smoking);
              //add panels to frame
              add(buttonPanel, BorderLayout.SOUTH);
              add(inputPanel, BorderLayout.CENTER);
              add(inputPanel, BorderLayout.NORTH);
              bookButton.addActionListener(this);
              //overriding the windowClosing() method will allow the user to click the Close button
              addWindowListener(
                   new WindowAdapter()
                        public void windowClosing(WindowEvent e)
                             System.exit(0);
         }//end of constructor method
         public static void main(String[] args)
              Reservations f = new Reservations();
              f.setBounds(200,200,600,300);
              f.setTitle("Reserve a Party Room");
              f.setVisible(true);
         } //end of main
         public void actionPerformed(ActionEvent e)
              if (hidden.getState())
                   JOptionPane.showMessageDialog(null, "You must select Nonsmoking or Smoking.", "Error", JOptionPane.ERROR_MESSAGE);
              else
                   int available = room.bookRoom(smoking.getState());
                   if (available > 0) //room is available
                        roomDisplay[available].setBackground(lightRed); //display room as occupied
                        roomDisplay[available].setText(
                                                                roomDisplay[available].getText() +
                                                                "\n" +
                                                                nameField.getText() +
                                                                " " +
                                                                phoneField.getText() +
                                                                "\nparty of " +
                                                                numberOfGuests.getSelectedItem()
                                                           ); //display info in room
                        clearFields();
                   else //room is not available
                        if (smoking.getState())
                             JOptionPane.showMessageDialog(null, "Smoking is full.", "Error", JOptionPane.INFORMATION_MESSAGE);
                        else
                             JOptionPane.showMessageDialog(null, "Nonsmoking is full.", "Error", JOptionPane.INFORMATION_MESSAGE);
                        hidden.setState(true);
                   } //end of else block that checks the available room number
              } //end of else block that checks the state of the hidden option button
         } //end of actionPerformed method
         //reset the text fields and choice component
         void clearFields()
              nameField.setText("");
              phoneField.setText("");
              numberOfGuests.select(0);
              nameField.requestFocus();
              hidden.setState(true);
         } //end of clearFields() method
    } //end of Reservations class                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    In order to display a component, that component has to be added to a container that is either that root container or has a parent container that is the root container. You have at least one JPanel, roomPanel, that is added to nothing. You will have to search through this to see if their are others.
    But more importantly, you are coding this all wrong. You need to code like so:
    1) create your class skeleton, see that it compiles and runs.
    2) add enough to make a JFrame appear, nothing more. Make sure it compiles, runs, and you see the frame.
    3) add code a little bit at a time, and after each addition, compile and run the code, make sure that you see any visual elements.
    4) repeat section 3 until project done.
    5) for larger projects, I create separate classes and run each one with its own main method to check it as I create it before adding it to the greater program.
    If you don't do it this way, you will end up with a mess where when you correct one error, three more show up.
    Also, I recommend that when an error or problem pops up like one did just now (invisible components) that you work on debugging it first for at least 1-2 hours before coming to the forum for answers. Otherwise you don't learn how to debug, an important skill to master.
    Edited by: petes1234 on Dec 17, 2007 10:11 AM

  • How to check the value from user input in database or not?

    Hello;
    I want to check the value of user input from JtextFiled in my database or not.
    If it is in database, then i will pop up a window to tell us, otherwise, it will tell us it is not in database.
    My problem is my code do not work properly, sometimes, it tell me correct information, sometime it tell wrong information.
    Could anyone help,please.Thanks
    The following code is for check whether the value in database or not, and pop up a window to tell us.
    while( rs.next()) {
                    System.out.println("i am testing");
                    bInt=new Integer(rs.getInt("id"));
                    if(aInt.equals(bInt)){ // If i find the value in data base, set flag to 1.
                  flag=1;  //I set a flag to check whether the id in database or not
                        break;
             System.out.println("falg" + flag);
                if(flag==1){ //?????????????????????
              String remove1 = "DELETE FROM Rental WHERE CustomerID=" + a;
              String remove2 = "DELETE FROM Revenus WHERE CustomerID=" +a;
              String remove3 = "DELETE FROM Customer WHERE id=" +a;
              s.executeUpdate(remove1);
              s.executeUpdate(remove2);
              s.executeUpdate(remove3);
                    JOptionPane.showMessageDialog(null,"you have success delete the value");
              s.close();
             else//???????????????????????????????
                  JOptionPane.showMessageDialog(null,"I could not found the value"); -------------------------------------------------------------------
    My whole program
    import java.sql.*;
    import java.awt.BorderLayout;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class DeleteC extends JFrame
        public static int index=0;   
        public static ResultSet rs;
        public static Statement s;
        public static Connection c;
        public static  Object cols[][];
        private static JTable table;
        private static JScrollPane scroller;
        private static int flag=0;
        public DeleteC()
            //information of our connection
            //the url of the database: protocol:subprotocol:subname:computer_name:port:database_name
            String strUrl      = "jdbc:oracle:thin:@augur.scms.waikato.ac.nz:1521:teaching";
            //user name and password
            String strUser      = "xbl1";
            String strPass      = "19681978";
            //try to load the driver
            try {
                Class.forName("oracle.jdbc.driver.OracleDriver");
            catch (ClassNotFoundException e) {
                System.out.println( "Cannot load the Oracle driver. Include it in your classpath.");
                System.exit( -1);
            //a null reference to a Connection object
            c = null;
            try {
                //open a connection to the database
                c = DriverManager.getConnection( strUrl, strUser, strPass);
            catch (SQLException e) {
                System.out.println("Cannot connect to the database. Here is the error:");
                e.printStackTrace();
                System.exit( -1);
           //create a statement object to execute sql statements
        public void getData(String a){
            try {
             //create a statement object to execute sql statements
             s = c.createStatement();
                int index=0;
                Integer aInt= Integer.valueOf(a);
                Integer bInt;
                  //our example query
                String strQuery = "select id from customer";
                //execute the query
                ResultSet rs = s.executeQuery( strQuery);
                //while there are rows in the result set
                while( rs.next()) {
                    System.out.println("i am testing");
                    bInt=new Integer(rs.getInt("id"));
                    if(aInt.equals(bInt)){
                  //JOptionPane.showMessageDialog(null,"I found the value"); 
                  flag=1;
                        break;
             System.out.println("falg" + flag);
                if(flag==1){
              String remove1 = "DELETE FROM Rental WHERE CustomerID=" + a;
              String remove2 = "DELETE FROM Revenus WHERE CustomerID=" +a;
              String remove3 = "DELETE FROM Customer WHERE id=" +a;
              s.executeUpdate(remove1);
              s.executeUpdate(remove2);
              s.executeUpdate(remove3);
                    JOptionPane.showMessageDialog(null,"you have success delete the value");
              s.close();
             else
                  JOptionPane.showMessageDialog(null,"I could not found the value");
            catch (SQLException e) {
                 JOptionPane.showMessageDialog(null,"You may enter wrong id");
    My main program for user input from JTextField.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JOptionPane;
    import java.util.*;
    public class EnterID extends JFrame{
        public JTextField tF1;
        public EnterID enID;
        public String tF1Value;
        private JLabel label1, label2, label3;
        private static JButton button;
        private static ButtonHandler handler;
        private static String aString;
        private static Integer aInteger;
        private static Integer checkV=0;
        public static void main(String args[]){
           EnterID eId= new EnterID();
       public EnterID(){
          handler=new ButtonHandler();
          Container c= getContentPane();
          c.setLayout(new GridLayout(3,1));
          button= new JButton("ok");
          button.addActionListener(handler);
          label1 = new JLabel(" CustomerID, Please");
          label2 = new JLabel("Label2");
          label3 = new JLabel();
          label3.setLayout(new GridLayout(1,1));
          label3.add(button);
          label2.setLayout(new GridLayout(1,1));
          aString = "Enter Id Here";
          tF1 = new JTextField(aString);
          label2.add(tF1);
          c.add(label1);
          c.add(label2);         
          c.add(label3);            
          setSize(150,100);
          setVisible(true);     
       private class ButtonHandler implements ActionListener{
         public void actionPerformed(ActionEvent event){
             tF1Value=tF1.getText();
            //   CheckData cData = new CheckData();
             //  aInteger = Integer.valueOf(tF1Value);      
             if(tF1Value.equals(aString)){
              JOptionPane.showMessageDialog(null,"You didn't type value into box");
              setVisible(false); 
            else {
                DeleteC dC= new DeleteC();
                dC.getData(tF1Value);
                setVisible(false); 
    }

    You may have working code now, but the code you posted is horrible and I'm going to tell you a much much much better approach for the JDBC part. (You should probably isolate your database code from your user interface code as well, but I'm skipping over that structural problem...)
    Do this instead:
        public void getData(String a){
            PreparedStatement p;
            String strQuery = "select count(*) the_count from customer where id = ?";
            try {   
             //create a prepared statement object to execute sql statements, it's better, faster, safer
             p = c.prepareStatement(strQuery);
                // bind the parameter value to the "?"
                p.setInt(1, Integer.parseInt(a) );
                //execute the query
                ResultSet rs = p.executeQuery( );
                // if the query doesn't throw an exception, it will have exactly one row
                rs.next();
                System.out.println("i am testing");
                if (rs.getInt("the_count") > 0 ) {
                // it's there, do what you need to...
             else
                  JOptionPane.showMessageDialog(null,"I could not find the value");
            catch (SQLException e) {
                 // JOptionPane.showMessageDialog(null,"You may enter wrong id");
                 // if you get an exception, something is really wrong, and it's NOT user error
            // always, always, ALWAYS close JDBC resources in a finally block
            finally
                p.close();
        }First, this is simpler and easier to read.
    Second, this retrieves just the needed information, whether or not the id is in the database. Your way will get much much slower as more data goes into the database. My way, if there is an index on the id column, more data doesn;t slow it down very much.
    I've also left some important points in comments.
    No guarantees that there isn't a dumb typo in there; I didn't actually compile it, much less test it. It's at least close though...

  • Multithread TicTacToe Server Problem

    I'm having some problems with finishing up a tic tac toe server and it's driving me crazy. I'm hoping someone can give me some hints or help out with this. All of the code is written for the server which allows 2 clients to connect, but the code for determining if the game is won needs to be finished up.
    I've got the method for determining if the game is over done, that part is easy, and I'm able to send a message to the client who wins when they place the winning marker and end the game for them, but currently the next player gets to place one more marker before being signaled that the game is over. I worked on this forever and I think I'm just missing something simple that I hope someone can help me with. Here's the code:
    Line 180 in TicTacToeServer.java is where I test for the win
    Line 304 in TicTacToeServer.java is where the clients exit the main while loop after determining that the game is won and I send a message letting them know that the game is won
    Server Code:
    TicTacToeServerTest.java
    // Tests the TicTacToeServer.
    import javax.swing.JFrame;
    public class TicTacToeServerTest
       public static void main( String args[] )
          TicTacToeServer application = new TicTacToeServer();
          application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
          application.execute();
       } // end main
    } // end class TicTacToeServerTest
    TicTacToeServer.java
    // This class maintains a game of Tic-Tac-Toe for two clients.
    import javax.swing.JOptionPane;
    import java.awt.BorderLayout;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.io.IOException;
    import java.util.Formatter;
    import java.util.Scanner;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    import java.util.concurrent.locks.Condition;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.SwingUtilities;
    public class TicTacToeServer extends JFrame
       private String[] board = new String[ 9 ]; // tic-tac-toe board
       private JTextArea outputArea; // for outputting moves
       private Player[] players; // array of Players
       private ServerSocket server; // server socket to connect with clients
       private int currentPlayer; // keeps track of player with current move
       private final static int PLAYER_X = 0; // constant for first player
       private final static int PLAYER_O = 1; // constant for second player
       private final static String[] MARKS = { "X", "O" }; // array of marks
       private ExecutorService runGame; // will run players
       private Lock gameLock; // to lock game for synchronization
       private Condition otherPlayerConnected; // to wait for other player
       private Condition otherPlayerTurn; // to wait for other player's turn
       private int winner = 2;
       // set up tic-tac-toe server and GUI that displays messages
       public TicTacToeServer()
          super( "Tic-Tac-Toe Server" ); // set title of window
          // create ExecutorService with a thread for each player
          runGame = Executors.newFixedThreadPool( 2 );
          gameLock = new ReentrantLock(); // create lock for game
          // condition variable for both players being connected
          otherPlayerConnected = gameLock.newCondition();
          // condition variable for the other player's turn
          otherPlayerTurn = gameLock.newCondition();
          for ( int i = 0; i < 9; i++ )
             board[ i ] = new String( "" ); // create tic-tac-toe board
          players = new Player[ 2 ]; // create array of players
          currentPlayer = PLAYER_X; // set current player to first player
          try
             server = new ServerSocket( 12345, 2 ); // set up ServerSocket
          } // end try
          catch ( IOException ioException )
             ioException.printStackTrace();
             System.exit( 1 );
          } // end catch
          outputArea = new JTextArea(); // create JTextArea for output
          add( outputArea, BorderLayout.CENTER );
          outputArea.setText( "Server awaiting connections\n" );
          setSize( 300, 300 ); // set size of window
          setVisible( true ); // show window
       } // end TicTacToeServer constructor
       // wait for two connections so game can be played
       public void execute()
          // wait for each client to connect
          for ( int i = 0; i < players.length; i++ )
             try // wait for connection, create Player, start runnable
                players[ i ] = new Player( server.accept(), i );
                runGame.execute( players[ i ] ); // execute player runnable
             } // end try
             catch ( IOException ioException )
                ioException.printStackTrace();
                System.exit( 1 );
             } // end catch
          } // end for
          gameLock.lock(); // lock game to signal player X's thread
          try
             players[ PLAYER_X ].setSuspended( false ); // resume player X
             otherPlayerConnected.signal(); // wake up player X's thread
          } // end try
          finally
             gameLock.unlock(); // unlock game after signalling player X
          } // end finally
       } // end method execute
       // display message in outputArea
       private void displayMessage( final String messageToDisplay )
          // display message from event-dispatch thread of execution
          SwingUtilities.invokeLater(
             new Runnable()
                public void run() // updates outputArea
                   outputArea.append( messageToDisplay ); // add message
                } // end  method run
             } // end inner class
          ); // end call to SwingUtilities.invokeLater
       } // end method displayMessage
       // determine if move is valid
       public boolean validateAndMove( int location, int player )
          // while not current player, must wait for turn
          while ( player != currentPlayer )
             gameLock.lock(); // lock game to wait for other player to go
             try
                otherPlayerTurn.await(); // wait for player's turn
             } // end try
             catch ( InterruptedException exception )
                exception.printStackTrace();
             } // end catch
             finally
                gameLock.unlock(); // unlock game after waiting
             } // end finally
          } // end while
          // if location not occupied, make move
          if ( !isOccupied( location ) )
             board[ location ] = MARKS[ currentPlayer ]; // set move on board
             currentPlayer = ( currentPlayer + 1 ) % 2; // change player
             // let new current player know that move occurred
             players[ currentPlayer ].otherPlayerMoved( location );
             gameLock.lock(); // lock game to signal other player to go
             try
                otherPlayerTurn.signal(); // signal other player to continue
             } // end try
             finally
                gameLock.unlock(); // unlock game after signaling
             } // end finally
             return true; // notify player that move was valid
          } // end if
          else // move was not valid
             return false; // notify player that move was invalid
       } // end method validateAndMove
       // determine whether location is occupied
       public boolean isOccupied( int location )
          if ( board[ location ].equals( MARKS[ PLAYER_X ] ) ||
             board [ location ].equals( MARKS[ PLAYER_O ] ) )
             return true; // location is occupied
          else
             return false; // location is not occupied
       } // end method isOccupied
       // place code in this method to determine whether game over
       public boolean isGameOver()
          for (int x = 0; x < 2; x++)
               if ((board[0].equals(MARKS[x]) && board[1].equals(MARKS[x]) && board[2].equals(MARKS[x])) ||
                (board[3].equals(MARKS[x]) && board[4].equals(MARKS[x]) && board[5].equals(MARKS[x])) ||
                (board[6].equals(MARKS[x]) && board[7].equals(MARKS[x]) && board[8].equals(MARKS[x])) ||
                (board[0].equals(MARKS[x]) && board[4].equals(MARKS[x]) && board[8].equals(MARKS[x])) ||
                (board[6].equals(MARKS[x]) && board[4].equals(MARKS[x]) && board[2].equals(MARKS[x])) ||
                (board[0].equals(MARKS[x]) && board[3].equals(MARKS[x]) && board[6].equals(MARKS[x])) ||
                (board[1].equals(MARKS[x]) && board[4].equals(MARKS[x]) && board[7].equals(MARKS[x])) ||
                (board[2].equals(MARKS[x]) && board[5].equals(MARKS[x]) && board[8].equals(MARKS[x]))
                winner = x;
                 return true;
          return false; // this is left as an exercise
       } // end method isGameOver
       // private inner class Player manages each Player as a runnable
       private class Player implements Runnable
          private Socket connection; // connection to client
          private Scanner input; // input from client
          private Formatter output; // output to client
          private int playerNumber; // tracks which player this is
          private String mark; // mark for this player
          private boolean suspended = true; // whether thread is suspended
          // set up Player thread
          public Player( Socket socket, int number )
             playerNumber = number; // store this player's number
             mark = MARKS[ playerNumber ]; // specify player's mark
             connection = socket; // store socket for client
             try // obtain streams from Socket
                input = new Scanner( connection.getInputStream() );
                output = new Formatter( connection.getOutputStream() );
             } // end try
             catch ( IOException ioException )
                ioException.printStackTrace();
                System.exit( 1 );
             } // end catch
          } // end Player constructor
          // send message that other player moved
          public void otherPlayerMoved( int location )
                   output.format( "Opponent moved\n" );
                  output.format( "%d\n", location ); // send location of move
                  output.flush(); // flush output
          } // end method otherPlayerMoved
          // control thread's execution
          public void run()
             // send client its mark (X or O), process messages from client
             try
                displayMessage( "Player " + mark + " connected\n" );
                output.format( "%s\n", mark ); // send player's mark
                output.flush(); // flush output
                // if player X, wait for another player to arrive
                if ( playerNumber == PLAYER_X )
                   output.format( "%s\n%s", "Player X connected",
                      "Waiting for another player\n" );
                   output.flush(); // flush output
                   gameLock.lock(); // lock game to  wait for second player
                   try
                      while( suspended )
                         otherPlayerConnected.await(); // wait for player O
                      } // end while
                   } // end try
                   catch ( InterruptedException exception )
                      exception.printStackTrace();
                   } // end catch
                   finally
                      gameLock.unlock(); // unlock game after second player
                   } // end finally
                   // send message that other player connected
                   output.format( "Other player connected. Your move.\n" );
                   output.flush(); // flush output
                } // end if
                else
                   output.format( "Player O connected, please wait\n" );
                   output.flush(); // flush output
                } // end else
                // while game not over
                while ( !isGameOver() )
                   int location = 0; // initialize move location
                   if ( input.hasNext() )
                      location = input.nextInt(); // get move location
                   // check for valid move
                   if ( validateAndMove( location, playerNumber ) )
                      displayMessage( "\nlocation: " + location );
                      output.format( "Valid move.\n" ); // notify client
                      output.flush(); // flush output
                   } // end if
                   else // move was invalid
                      output.format( "Invalid move, try again\n" );
                      output.flush(); // flush output
                   } // end else
                } // end while
                output.format( "Game Over.\n" ); // notify client
                if (winner == 0)
                     output.format("Winner is X\n");
                if (winner == 1)
                     output.format("Winner is O\n");
                output.flush(); // flush output
                gameLock.unlock();
             } // end try
             finally
                try
                   connection.close(); // close connection to client
                } // end try
                catch ( IOException ioException )
                   ioException.printStackTrace();
                   System.exit( 1 );
                } // end catch
             } // end finally
          } // end method run
          // set whether or not thread is suspended
          public void setSuspended( boolean status )
             suspended = status; // set value of suspended
          } // end method setSuspended
       } // end class Player
    } // end class TicTacToeServer
    Client Code:
    TicTacToeClientTest.java
    // Tests the TicTacToeClient class.
    import javax.swing.JFrame;
    public class TicTacToeClientTest
       public static void main( String args[] )
          TicTacToeClient application; // declare client application
          // if no command line args
          if ( args.length == 0 )
             application = new TicTacToeClient( "127.0.0.1" ); // localhost
          else
             application = new TicTacToeClient( args[ 0 ] ); // use args
          application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
       } // end main
    } // end class TicTacToeClientTest
    TicTacToeClient.java
    // Client that let a user play Tic-Tac-Toe with another across a network.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.GridLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.net.Socket;
    import java.net.InetAddress;
    import java.io.IOException;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import java.util.Formatter;
    import java.util.Scanner;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ExecutorService;
    public class TicTacToeClient extends JFrame implements Runnable
       private JTextField idField; // textfield to display player's mark
       private JTextArea displayArea; // JTextArea to display output
       private JPanel boardPanel; // panel for tic-tac-toe board
       private JPanel panel2; // panel to hold board
       private Square board[][]; // tic-tac-toe board
       private Square currentSquare; // current square
       private Socket connection; // connection to server
       private Scanner input; // input from server
       private Formatter output; // output to server
       private String ticTacToeHost; // host name for server
       private String myMark; // this client's mark
       private boolean myTurn; // determines which client's turn it is
       private final String X_MARK = "X"; // mark for first client
       private final String O_MARK = "O"; // mark for second client
       // set up user-interface and board
       public TicTacToeClient( String host )
          ticTacToeHost = host; // set name of server
          displayArea = new JTextArea( 4, 30 ); // set up JTextArea
          displayArea.setEditable( false );
          add( new JScrollPane( displayArea ), BorderLayout.SOUTH );
          boardPanel = new JPanel(); // set up panel for squares in board
          boardPanel.setLayout( new GridLayout( 3, 3, 0, 0 ) );
          board = new Square[ 3 ][ 3 ]; // create board
          // loop over the rows in the board
          for ( int row = 0; row < board.length; row++ )
             // loop over the columns in the board
             for ( int column = 0; column < board[ row ].length; column++ )
                // create square
                board[ row ][ column ] = new Square( " ", row * 3 + column );
                boardPanel.add( board[ row ][ column ] ); // add square
             } // end inner for
          } // end outer for
          idField = new JTextField(); // set up textfield
          idField.setEditable( false );
          add( idField, BorderLayout.NORTH );
          panel2 = new JPanel(); // set up panel to contain boardPanel
          panel2.add( boardPanel, BorderLayout.CENTER ); // add board panel
          add( panel2, BorderLayout.CENTER ); // add container panel
          setSize( 300, 225 ); // set size of window
          setVisible( true ); // show window
          startClient();
       } // end TicTacToeClient constructor
       // start the client thread
       public void startClient()
          try // connect to server, get streams and start outputThread
             // make connection to server
             connection = new Socket(
                InetAddress.getByName( ticTacToeHost ), 12345 );
             // get streams for input and output
             input = new Scanner( connection.getInputStream() );
             output = new Formatter( connection.getOutputStream() );
          } // end try
          catch ( IOException ioException )
             ioException.printStackTrace();
          } // end catch
          // create and start worker thread for this client
          ExecutorService worker = Executors.newFixedThreadPool( 1 );
          worker.execute( this ); // execute client
       } // end method startClient
       // control thread that allows continuous update of displayArea
       public void run()
          myMark = input.nextLine(); // get player's mark (X or O)
          SwingUtilities.invokeLater(
             new Runnable()
                public void run()
                   // display player's mark
                   idField.setText( "You are player \"" + myMark + "\"" );
                } // end method run
             } // end anonymous inner class
          ); // end call to SwingUtilities.invokeLater
          myTurn = ( myMark.equals( X_MARK ) ); // determine if client's turn
          // receive messages sent to client and output them
          while ( true )
             if ( input.hasNextLine() )
                processMessage( input.nextLine() );
          } // end while
       } // end method run
       // process messages received by client
       private void processMessage( String message )
          // valid move occurred
          if ( message.equals( "Valid move." ) )
             displayMessage( "Valid move, please wait.\n" );
             setMark( currentSquare, myMark ); // set mark in square
          } // end if
          else if ( message.equals( "Invalid move, try again" ) )
             displayMessage( message + "\n" ); // display invalid move
             myTurn = true; // still this client's turn
          } // end else if
          else if ( message.equals( "Opponent moved" ) )
             int location = input.nextInt(); // get move location
             input.nextLine(); // skip newline after int location
             int row = location / 3; // calculate row
             int column = location % 3; // calculate column
             setMark(  board[ row ][ column ],
                ( myMark.equals( X_MARK ) ? O_MARK : X_MARK ) ); // mark move
             displayMessage( "Opponent moved. Your turn.\n" );
             myTurn = true; // now this client's turn
          } // end else if
          else
             displayMessage( message + "\n" ); // display the message
       } // end method processMessage
       // manipulate outputArea in event-dispatch thread
       private void displayMessage( final String messageToDisplay )
          SwingUtilities.invokeLater(
             new Runnable()
                public void run()
                   displayArea.append( messageToDisplay ); // updates output
                } // end method run
             }  // end inner class
          ); // end call to SwingUtilities.invokeLater
       } // end method displayMessage
       // utility method to set mark on board in event-dispatch thread
       private void setMark( final Square squareToMark, final String mark )
          SwingUtilities.invokeLater(
             new Runnable()
                public void run()
                   squareToMark.setMark( mark ); // set mark in square
                } // end method run
             } // end anonymous inner class
          ); // end call to SwingUtilities.invokeLater
       } // end method setMark
       // send message to server indicating clicked square
       public void sendClickedSquare( int location )
          // if it is my turn
          if ( myTurn )
             output.format( "%d\n", location ); // send location to server
             output.flush();
             myTurn = false; // not my turn anymore
          } // end if
       } // end method sendClickedSquare
       // set current Square
       public void setCurrentSquare( Square square )
          currentSquare = square; // set current square to argument
       } // end method setCurrentSquare
       // private inner class for the squares on the board
       private class Square extends JPanel
          private String mark; // mark to be drawn in this square
          private int location; // location of square
          public Square( String squareMark, int squareLocation )
             mark = squareMark; // set mark for this square
             location = squareLocation; // set location of this square
             addMouseListener(
                new MouseAdapter() {
                   public void mouseReleased( MouseEvent e )
                      setCurrentSquare( Square.this ); // set current square
                      // send location of this square
                      sendClickedSquare( getSquareLocation() );
                   } // end method mouseReleased
                } // end anonymous inner class
             ); // end call to addMouseListener
          } // end Square constructor
          // return preferred size of Square
          public Dimension getPreferredSize()
             return new Dimension( 30, 30 ); // return preferred size
          } // end method getPreferredSize
          // return minimum size of Square
          public Dimension getMinimumSize()
             return getPreferredSize(); // return preferred size
          } // end method getMinimumSize
          // set mark for Square
          public void setMark( String newMark )
             mark = newMark; // set mark of square
             repaint(); // repaint square
          } // end method setMark
          // return Square location
          public int getSquareLocation()
             return location; // return location of square
          } // end method getSquareLocation
          // draw Square
          public void paintComponent( Graphics g )
             super.paintComponent( g );
             g.drawRect( 0, 0, 29, 29 ); // draw square
             g.drawString( mark, 11, 20 ); // draw mark
          } // end method paintComponent
       } // end inner-class Square
    } // end class TicTacToeClient

    I'll look into doing it that way... One thing I don't understand is that when the winning player places it's final marker and gets the game over message the other player gets passed the Opponent moved message. So shouldn't I be able to pass a Game Over message to the other player after sending the Game Over message to the winning player? I'm not sure where in the code I'd need to put the output statement or what code I'd use to send it to the losing player instead of the winning player. I'm fairly new to threading and working on this for school, the book is not very much help in this area, so excuse my ignorance. Is it possible to send a message to the losing client right after sending one to the winning client after the main while loop exits around line 309 of TicTacToeServer.java? Or is this not possible because of how threading works?

  • JTable - isEditing does not work in Java 1.4

    I just upgraded jdk1.1.8 with swing 1.1.1 to Java1.4. The isEditing method doesn't work on Java1.4. When I edit a cell in the JTable and click a button , the value of the last edited cell is lost. I was able to catch the edited value by calling isEditing in jdk1.1.8 but Java 1.4 does not detect that the cell was edited. Is this a bug? Has anyone experience this problem? Is there a work around solution? Please help!!!

    Hi,
    Below is the code that I modified from a sample code in Java Tutorial. I added an OK button. The isEditing method does not trap the edit the first time but does on the second edit in JDK1.4. However, it works in JDK1.1.8. Am I doing something wrong or is this a bug? I desperately have to solve this problem to upgrade to JDK1.4. Thank-you for your help! I really appreciate it!
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class TableDemo extends JFrame {
    private boolean DEBUG = true;
    private JPanel buttonPanel;
    private JTable table;
    public TableDemo() {
    super("TableDemo");
    MyTableModel myModel = new MyTableModel();
    table = new JTable(myModel);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    // create OK, Reset, and Cancel buttons
    createButtons();
    getContentPane().add(buttonPanel, BorderLayout.SOUTH);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    class MyTableModel extends AbstractTableModel {
    final String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    final Object[][] data = {
    {"Mary", "Campione",
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml",
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath",
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Mark", "Andrews",
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Angela", "Lih",
    "Teaching high school", new Integer(4), new Boolean(false)}
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col
    + " to " + value
    + " (an instance of "
    + value.getClass() + ")");
    if (data[0][col] instanceof Integer
    && !(value instanceof Integer)) {                 
    //With JFC/Swing 1.1 and JDK 1.2, we need to create
    //an Integer from the value; otherwise, the column
    //switches to contain Strings. Starting with v 1.3,
    //the table automatically converts value to an Integer,
    //so you only need the code in the 'else' part of this
    //'if' block.
    //XXX: See TableEditDemo.java for a better solution!!!
    try {
    data[row][col] = new Integer(value.toString());
    fireTableCellUpdated(row, col);
    } catch (NumberFormatException e) {
    JOptionPane.showMessageDialog(TableDemo.this,
    "The \"" + getColumnName(col)
    + "\" column accepts only integer values.");
    } else {
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    if (DEBUG) {
    System.out.println("New value of data:");
    printDebugData();
    private void printDebugData() {
    int numRows = getRowCount();
    int numCols = getColumnCount();
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + data[i][j]);
    System.out.println();
    System.out.println("--------------------------");
    private void createButtons() {
    // create panel to hold buttons
    buttonPanel = new JPanel();
    JButton buttonOK = new JButton("OK");
    buttonOK.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    // detect if a value was edited when OK was pressed without entering
    // return or changing focus
    if (table.isEditing()) {
    System.out.println("****** Table is edited ******");
    // value was edited when OK was pressed without entering return
    // or changing focus
    int row = table.getEditingRow();
    int column = table.getEditingColumn();
    System.out.println("row: " + row + ", column: " + column + " is edited");
    buttonPanel.add(buttonOK);
    public static void main(String[] args) {
    TableDemo frame = new TableDemo();
    frame.pack();
    frame.setVisible(true);

Maybe you are looking for

  • Error while executing program "BBP_STARTUP_TOOL_FOR_CCMS" in SRM 5.

    Hi, I get an error message "Error starting appl. monitor for client 000 and 001; processing terminated." when i execute the program. BBP_STARTUP_TOOL_FOR_CCMS I m not getting wats the problem. Pls help me with so. Thanks Regards.

  • Can no longer scan using preview

    I have Brother DCP-9040CN color laser Printer and I am using the latest version of Mountain Lion. I have been scanning documents with no problems. The last time I tried to scan a document, I get the message the selected folder in not writable. I have

  • How can I reinstall the App Store?

    I have lost all the programs except safari, how can I reinstall everything?

  • What is the "TV" option used fo

    I don't know what I'm supposed to use the TV option in the Video section on my ZEN Creative media player. What am I supposed to download onto it and whee can I download the appropriate files for the TV option?

  • Ridiculous charge for contract switch

    Hello, I managed to get my landlord to sign up for a phone line for me, provided that I did the £120 pay for a year in advance, which I agreed to. An extra £30 for the installation charge and that was that. All was well until I ordered broadband whic