Swing JMenu + mysql

Hi,
I try make to import data from Mysql to JMenu, Could somebody help me.
(Table Products, column productid and productname).
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class MenuWithMysql extends JFrame
     static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";       
     static final String DATABASE_URL = "jdbc:mysql://localhost:3306/menuwithmysql";
     public static void main(String[] args)
          Connection connection = null;
          Statement statement = null;
          try
         Class.forName( JDBC_DRIVER ); // load database driver class
         // establish connection to database
         connection = DriverManager.getConnection( DATABASE_URL, "", "" );
         // create Statement for querying database
         statement = connection.createStatement();
         System.out.println("MySQL Successfully connected");
    /*     ResultSet rs = statement.executeQuery("SELECT * FROM products");
         if (rs.next())
              String productid = rs.getString("productid");
              String productname = rs.getString("productname");
              System.out.println(productid + "     " + productname);
     } // end try
      catch ( SQLException sqlException )
         sqlException.printStackTrace();
         System.exit( 1 );
      } // end catch
      catch ( ClassNotFoundException classNotFound )
         classNotFound.printStackTrace();           
         System.exit( 1 );
      } // end catch
      finally // ensure statement and connection are closed properly
         try                                                       
            statement.close();                                     
            connection.close();                                    
         } // end try                                              
         catch ( Exception exception )                       
            exception.printStackTrace();                                    
            System.exit( 1 );                                      
         } // end catch                                            
      } // end finallytry
        JFrame frame = new JFrame("Menu With Mysql");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
       JMenuBar menuBar = new JMenuBar();
      JMenu jMenu1 = new JMenu( "Products" );
      JMenuItem jMenuItem1 = new JMenuItem( "books" );
      JMenuItem jMenuItem2 = new JMenuItem( "hardware" );
      menuBar.add(jMenu1);
      jMenu1.add(jMenuItem1);
      jMenu1.add(jMenuItem2);
      frame.setJMenuBar(menuBar);
}

thank you ignignokt84, it work fine.
I have another question (about JMenu)
DB that use 2 TABLES
a) categories with columns categories_id | parent_id | sort_order |
b) categories_description with columns categories_id | categories_name
categories_id | parent_id | sort_order |
1 | 0 | 1 |
2 | 0 | 2 |
3 | 1 | 1 |
4 | 1 | 2 |
8 | 2 | 1 |
9 | 2 | 2 |
categories_id | categories_name |
1 | Books |
2 | Hardware |
3 | Java Book |
4 | Mysql Book |
8 | keyboard |
9 | mouse |
I try make JMenu with submenu
JMenu = Books {Submenu = Java Book, Mysql Book}
JMenu = Hardware {Submenu = keyboard, mouse}
import javax.swing.event.*;
import java.sql.*;
public class Test
     static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";       
     static final String DATABASE_URL = "jdbc:mysql://localhost:3306/DBname";
    public Test()
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
        JMenu menu1 = new JMenu("Products");
        JMenu subMenu1 = new JMenu();
        JMenu subMenu2 = new JMenu("Hardware");
       JMenu subMenu4 = new JMenu();
        Connection connection = null;
          Statement statement = null;
          try
               Class.forName( JDBC_DRIVER ); // load database driver class
               // establish connection to database
               connection = DriverManager.getConnection( DATABASE_URL, "", "" );
               // create Statement for querying database
               statement = connection.createStatement();
            ResultSet rs =  statement.executeQuery("select CATEGORIES.categories_id, CATEGORIES_DESCRIPTION.categories_name, CATEGORIES.parent_id from  CATEGORIES, CATEGORIES_DESCRIPTION where CATEGORIES.parent_id = 0  AND CATEGORIES.categories_id = CATEGORIES_DESCRIPTION.categories_id");// AND CATEGORIES.parent_id = CATEGORIES.categories_id //select * from products
            while(rs.next())
              menu1.add(new JMenu(rs.getString("categories_name")));
             ResultSet rs2 =  statement.executeQuery("select CATEGORIES.categories_id, CATEGORIES_DESCRIPTION.categories_name, CATEGORIES.parent_id from  CATEGORIES, CATEGORIES_DESCRIPTION where CATEGORIES.parent_id = 1  AND CATEGORIES.categories_id = CATEGORIES_DESCRIPTION.categories_id");// AND CATEGORIES.parent_id = CATEGORIES.categories_id //select * from products
            while(rs2.next())
                subMenu1.add(new JMenuItem(rs2.getString("categories_name")));
            rs.close();
            rs2.close();
        }catch(Exception e) {
            e.printStackTrace();
        menu1.add(subMenu1);
        JMenuBar menuBar = new JMenuBar();
        menuBar.add(menu1);
        frame.setJMenuBar(menuBar);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    public static void main(String[] args)
        new Test();
}this code giveme JMenu then I try another ResultSet2, but nothing , could you HELP ME, I try many things but I thing that this is wrong way.
I try :
rs1.absolute(1);
rs1.absolute(2);and then
while(rs3.next())But don't forgot sort_order column.

Similar Messages

  • Java1.3.1 + (Jframe + Timer(swing) + Jmenu) = jframe quits!!

    Hi,
    I have a program swing which draws polygons (nope, not 3d) on a JPanel in a JFrame.
    I am not sure why, but my Timer (swing, not java.util) and Jmenu component somehow don't like each other.
    My program works fine without the JMenu, or without the Timer, but as soon as I use both, the program fires up and closes immediately without any errors! (running jdb revealed nothing)
    This only happens in java 1.3.1, <b>not 1.4</b>, but before I label this as a bug (which one shouldn't do too quickly!) perhaps someone round here can try this out and perhaps find my (silly) mistake, if it exists.
    Thank you in advance,
    Vilnis
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Scene
    public static void main(String[] args){
    JFrame frame = new Display();
    frame.addWindowListener(new Closer());
    frame.setSize(640,480);
    frame.show();
    class Closer extends WindowAdapter
    public void windowClosing(WindowEvent e){
    //this is the only exiting command in the whole code
    System.out.println("Exited properly");
    System.exit(0);
    class Display extends JFrame
    Drawing graphics;
    JPopupMenu sceneMenu;
    MouseListener popupListener;
    Display(){
    graphics = new Drawing();
    sceneMenu = popMenu();
    popupListener = new PopupListener();
    graphics.addMouseListener(popupListener);
    getContentPane().add(graphics);
    public JPopupMenu popMenu(){
    JPopupMenu menu;
    menu = new JPopupMenu();
    /* one way to stop the problem is to comment out the next three
    * lines, i.e. remove the JMenu component.
    * the other 'solution' is to comment out line 127 (timer)
    JMenu subMenu = new JMenu("subMenu");
    subMenu.add(new JMenuItem("subButton1"));
    menu.add(subMenu);
    menu.add(new JMenuItem("button1"));
    menu.addSeparator();
    menu.add(new JMenuItem("button2"));
    return menu;
    /*this class has nothing to do with the problem -
    I tried commenting it out. */
    class PopupListener extends MouseAdapter
    public void mousePressed(MouseEvent e){
    maybeShowPopup(e);
    public void mouseReleased(MouseEvent e){
    maybeShowPopup(e);
    private void maybeShowPopup(MouseEvent e){
    if (e.isPopupTrigger()){
    sceneMenu.show(e.getComponent(),
    e.getX(), e.getY());
    class Drawing extends JPanel implements ActionListener
    private Polygon drawPoly[];
    private BouncyPolygon bPoly[];
    private Timer reDraw;
    Drawing(){
    //define 2 polygons
    int axs[] = {0,320,30, 50, 145};
    int ays[] = {0, 60, 100, 90, 200};
    int bxs[] = {50,370,80, 80, 220};
    int bys[] = {50, 110, 150, 56, 78};
    drawPoly = new Polygon[2];
    bPoly = new BouncyPolygon[2];
    drawPoly[0] = new Polygon(axs, ays, 5);
    drawPoly[1] = new Polygon(bxs, bys, 5);
    /* the bouncyPolygon class was originally supposed to have
    * it's own timer, but I took it out to see whether this
    * was something to do with the problem.
    * The 'this' (Drawing) class gets passed so getWidth and
    * getHeight can be used to bounce the individual points of
    * the polygons of walls even if the window is resized.
    * the first two params specify x and y coordinates, the third
    * specifies the number of points the polygon has,
    * the forth param is the drawing jPanel
    * and the last one is the speed of movement.
    bPoly[0] = new BouncyPolygon(axs, ays, 5, this, 4);
    bPoly[1] = new BouncyPolygon(bxs, bys, 5, this, 7);
    /* set timer to redraw screen every 30ms
    * (the only timer in the whole program)
    reDraw = new Timer(30,this);
    reDraw.start();
    public void actionPerformed(ActionEvent e)
    for (int i = 0; i <bPoly.length; i++){
    //move polygons
    bPoly.move();
    //update coordinates
    drawPoly[i].xpoints = bPoly[i].getXs();
    drawPoly[i].ypoints = bPoly[i].getYs();
    repaint();
    public void paintComponent(Graphics g){ 
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setPaint(
    new GradientPaint(0,0,Color.red, 320, 240, Color.green, true));
    g2.draw(drawPoly[0]);
    g2.setPaint(
    new GradientPaint(0,0,Color.blue, 320, 240, Color.yellow, true));
    g2.draw(drawPoly[1]);
    class BouncyPolygon
    private int pointCount;
    //coordinates
    private int xs[], ys[];
    //direction flags for each point
    private int dirX[], dirY[];
    //speed
    private int moveSize;
    private JPanel j;
    BouncyPolygon(int xpoints[], int ypoints[], int npoints, JPanel jp,
    int moveAmount){
    if (xpoints.length == npoints && ypoints.length == npoints){
    j = jp;
    pointCount = npoints;
    xs = xpoints;
    ys = ypoints;
    moveSize = moveAmount;
    dirX = new int[npoints];
    dirY = new int[npoints];
    //initialize direction array
    for (int i = 0; i < npoints; i++){
    dirX[i] = 1;
    dirY[i] = 1;
    } else{
    System.out.println(
    "Array size does no equal polygon point count!\n");
    System.exit(1);
    //move the polygons (and bounce of Walls)
    public void move(){
    for (int i = 0; i < pointCount; i++){
    if (dirX[i] == 1 && xs[i] >= j.getWidth() - (moveSize - 1)||
    dirX[i] == -1 && xs[i] <= (moveSize - 1)){
    dirX[i] *= -1;
    xs[i] += (int) (dirX[i] * moveSize);
    if (dirY[i] == 1 && ys[i] >= j.getHeight() - (moveSize - 1) ||
    dirY[i] == -1 && ys[i] <= (moveSize - 1)){
    dirY[i] *= -1;
    ys[i] += (int) (dirY[i] * moveSize);
    public int[] getXs(){
    return xs;
    public int[] getYs(){
    return ys;

    This code should work now ;)
    As I said before, the problem only comes up with java 1.3.1 and not 1.4.
    Ok, I don't know about other versions.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Scene
    public static void main(String[] args){
    JFrame frame = new Display();
    frame.addWindowListener(new Closer());
    frame.setSize(640,480);
    frame.show();
    class Closer extends WindowAdapter
    public void windowClosing(WindowEvent e){
    //this is the only exiting command in the whole code
    System.out.println("Exited properly");
    System.exit(0);
    class Display extends JFrame
    Drawing graphics;
    JPopupMenu sceneMenu;
    MouseListener popupListener;
    Display(){
    graphics = new Drawing();
    sceneMenu = popMenu();
    popupListener = new PopupListener();
    graphics.addMouseListener(popupListener);
    getContentPane().add(graphics);
    public JPopupMenu popMenu(){
    JPopupMenu menu;
    menu = new JPopupMenu();
    /* one way to stop the problem is to comment out the next three
    * lines, i.e. remove the JMenu component.
    * the other 'solution' is to comment out line 127 (timer)
    JMenu subMenu = new JMenu("subMenu");
    subMenu.add(new JMenuItem("subButton1"));
    menu.add(subMenu);
    menu.add(new JMenuItem("button1"));
    menu.addSeparator();
    menu.add(new JMenuItem("button2"));
    return menu;
    /*this class has nothing to do with the problem -
    I tried commenting it out. */
    class PopupListener extends MouseAdapter
    public void mousePressed(MouseEvent e){
    maybeShowPopup(e);
    public void mouseReleased(MouseEvent e){
    maybeShowPopup(e);
    private void maybeShowPopup(MouseEvent e){
    if (e.isPopupTrigger()){
    sceneMenu.show(e.getComponent(),
    e.getX(), e.getY());
    class Drawing extends JPanel implements ActionListener
    private Polygon drawPoly[];
    private BouncyPolygon bPoly[];
    private Timer reDraw;
    Drawing(){
    //define 2 polygons
    int axs[] = {0,320,30, 50, 145};
    int ays[] = {0, 60, 100, 90, 200};
    int bxs[] = {50,370,80, 80, 220};
    int bys[] = {50, 110, 150, 56, 78};
    drawPoly = new Polygon[2];
    bPoly = new BouncyPolygon[2];
    drawPoly[0] = new Polygon(axs, ays, 5);
    drawPoly[1] = new Polygon(bxs, bys, 5);
    /* the bouncyPolygon class was originally supposed to have
    * it's own timer, but I took it out to see whether this
    * was something to do with the problem.
    * The 'this' (Drawing) class gets passed so getWidth and
    * getHeight can be used to bounce the individual points of
    * the polygons of walls even if the window is resized.
    * the first two params specify x and y coordinates, the third
    * specifies the number of points the polygon has,
    * the forth param is the drawing jPanel
    * and the last one is the speed of movement.
    bPoly[0] = new BouncyPolygon(axs, ays, 5, this, 4);
    bPoly[1] = new BouncyPolygon(bxs, bys, 5, this, 7);
    /* set timer to redraw screen every 30ms
    * (the only timer in the whole program)
    reDraw = new Timer(30,this);
    reDraw.start();
    public void actionPerformed(ActionEvent e)
    for (int i = 0; i <bPoly.length; i++){
    //move polygons
    bPoly.move();
    //update coordinates
    drawPoly[i].xpoints = bPoly[i].getXs();
    drawPoly[i].ypoints = bPoly[i].getYs();
    repaint();
    public void paintComponent(Graphics g){
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setPaint(
    new GradientPaint(0,0,Color.red, 320, 240, Color.green, true));
    g2.draw(drawPoly[0]);
    g2.setPaint(
    new GradientPaint(0,0,Color.blue, 320, 240, Color.yellow, true));
    g2.draw(drawPoly[1]);
    class BouncyPolygon
    private int pointCount;
    //coordinates
    private int xs[], ys[];
    //direction flags for each point
    private int dirX[], dirY[];
    //speed
    private int moveSize;
    private JPanel j;
    BouncyPolygon(int xpoints[], int ypoints[], int npoints, JPanel jp,
    int moveAmount){
    if (xpoints.length == npoints && ypoints.length == npoints){
    j = jp;
    pointCount = npoints;
    xs = xpoints;
    ys = ypoints;
    moveSize = moveAmount;
    dirX = new int[npoints];
    dirY = new int[npoints];
    //initialize direction array
    for (int i = 0; i < npoints; i++){
    dirX[i] = 1;
    dirY[i] = 1;
    } else{
    System.out.println(
    "Array size does no equal polygon point count!\n");
    System.exit(1);
    //move the polygons (and bounce of Walls)
    public void move(){
    for (int i = 0; i < pointCount; i++){
    if (dirX[i] == 1 && xs[i] >= j.getWidth() - (moveSize - 1)||
    dirX[i] == -1 && xs[i] <= (moveSize - 1)){
    dirX[i] *= -1;
    xs[i] += (int) (dirX[i] * moveSize);
    if (dirY[i] == 1 && ys[i] >= j.getHeight() - (moveSize - 1) ||
    dirY[i] == -1 && ys[i] <= (moveSize - 1)){
    dirY[i] *= -1;
    ys[i] += (int) (dirY[i] * moveSize);
    public int[] getXs(){
    return xs;
    public int[] getYs(){
    return ys;

  • Swing JMenu Bug ID: 6563939

    Is bug ID:6563939 ever going to get fixed?
    http://bugs.sun.com/view_bug.do?bug_id=6563939
    I commonly get complaints from users about this, but as there is a registered bug out there, I have avoided doing my own work around hoping it will be fixed for the next release. But it has been 5 years now and still no joy.
    I guess the Very Low Priority just never makes it in the pipeline. I do not understand why such a serious usability issue is prioritized so low.
    Does anyone have a decent work around?

    - this bug isn't fixed (I'm din't check that in Java7),m basically in Swing isn't possible to display two JPopup in the same time, e.g. the same issue with JComboBox in JPopup etc.
    - you can to play with isLightWeightPopupEnabled and isLightweightComponent, or with AWT Popup, but I suggest don't do that
    - if you want to display some popup window then to use JWindow or undecorated JDialog, there are only one these significant differencies, and you must to override
    a) the Point for possition on the screen
    b) setVisible(false) on mouse or keyboard FocusLost (Swing Timer and with fading to use transparency with alpha, at 0.5f hide window)
    c) in compare with J/Popup (correctly implemented EDT methods) (for JWindow/JDialog) method setVisible(true) is required / must be wrapped inside invokeLater,

  • JAWS does not always read  Swing menus

    I have come across a problem that involves JAWS 4.51 and Java menus in Internet Explorer.
    I have a Java application that has a JMenuBar. The menu bar contains several JMenus that in turn contain several JMenuItems.
    When navigating through a menu, JAWS reads every JMenuItem. However, once a disabled JMenuItem is reached, JAWS no longer reads the JMenuItems below the disabled one in the open JMenu.
    The problem occurs only in Internet Explorer on "plain" menu items that follow a disabled menu item. The problem does not affect "complex" menu items, such as those that open sub menus.
    I can only reproduce this problem in Internet Explorer 6. Netscape Communicator 7, Web Start clients and a command line launch do not suffer from this problem. Also, JAWS 4.02 is fine as well; only 4.51 has this problem.
    Attached at the end is a sample application that recreates the issue. You'll notice in the sample application that JAWS will not read "A check box menu item" and "Another one" while it will read "A submenu."
    Does anyone have a solution to this? Thanks a lot!
    Sample application:
    ======================================================
    Note: The code below is a modification of the Sun menu tutorial found at http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html
    middle.gif can be downloaded from http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/images/middle.gif
    MenuLookDemoApplet.java:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JRadioButtonMenuItem;
    import javax.swing.ButtonGroup;
    import javax.swing.JMenuBar;
    import javax.swing.KeyStroke;
    import javax.swing.ImageIcon;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JApplet;
    /* MenuLookDemoApplet.java is a 1.4 application that requires images/middle.gif. */
    * This class exists solely to show you what menus look like.
    * It has no menu-related event handling.
    public class MenuLookDemoApplet extends JApplet {
        JTextArea output;
        JScrollPane scrollPane;
        public JMenuBar createMenuBar() {
            JMenuBar menuBar;
            JMenu menu, submenu;
            JMenuItem menuItem;
            JRadioButtonMenuItem rbMenuItem;
            JCheckBoxMenuItem cbMenuItem;
            //Create the menu bar.
            menuBar = new JMenuBar();
            //Build the first menu.
            menu = new JMenu("A Menu");
            menu.setMnemonic(KeyEvent.VK_A);
            menu.getAccessibleContext().setAccessibleDescription(
                    "The only menu in this program that has menu items");
            menuBar.add(menu);
            //a group of JMenuItems
            menuItem = new JMenuItem("A text-only menu item",
                                     KeyEvent.VK_T);
            //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
            menuItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_1, ActionEvent.ALT_MASK));
            menuItem.getAccessibleContext().setAccessibleDescription(
                    "This doesn't really do anything");
            menu.add(menuItem);
            ImageIcon icon = createImageIcon("images/middle.gif");
            menuItem = new JMenuItem("Both text and icon", icon);
            menuItem.setMnemonic(KeyEvent.VK_B);
            menu.add(menuItem);
            menuItem = new JMenuItem(icon);
            menuItem.setMnemonic(KeyEvent.VK_D);
            menu.add(menuItem);
            //a group of radio button menu items
            menu.addSeparator();
            ButtonGroup group = new ButtonGroup();
            rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
            rbMenuItem.setSelected(true);
            rbMenuItem.setMnemonic(KeyEvent.VK_R);
            group.add(rbMenuItem);
            menu.add(rbMenuItem);
            rbMenuItem = new JRadioButtonMenuItem("Another one");
            rbMenuItem.setMnemonic(KeyEvent.VK_O);
            group.add(rbMenuItem);
            menu.add(rbMenuItem);
            rbMenuItem.setEnabled(false);   //@dpb
            //a group of check box menu items
            menu.addSeparator();
            cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
            cbMenuItem.setMnemonic(KeyEvent.VK_C);
            menu.add(cbMenuItem);
            cbMenuItem = new JCheckBoxMenuItem("Another one");
            cbMenuItem.setMnemonic(KeyEvent.VK_H);
            menu.add(cbMenuItem);
            //a submenu
            menu.addSeparator();
            submenu = new JMenu("A submenu");
            submenu.setMnemonic(KeyEvent.VK_S);
            menuItem = new JMenuItem("An item in the submenu");
            menuItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_2, ActionEvent.ALT_MASK));
            submenu.add(menuItem);
            menuItem = new JMenuItem("Another item");
            submenu.add(menuItem);
            menu.add(submenu);
            //Build second menu in the menu bar.
            menu = new JMenu("Another Menu");
            menu.setMnemonic(KeyEvent.VK_N);
            menu.getAccessibleContext().setAccessibleDescription(
                    "This menu does nothing");
            menuBar.add(menu);
            return menuBar;
        public Container createContentPane() {
            //Create the content-pane-to-be.
            JPanel contentPane = new JPanel(new BorderLayout());
            contentPane.setOpaque(true);
            //Create a scrolled text area.
            output = new JTextArea(5, 30);
            output.setEditable(false);
            scrollPane = new JScrollPane(output);
            //Add the text area to the content pane.
            contentPane.add(scrollPane, BorderLayout.CENTER);
            return contentPane;
        /** Returns an ImageIcon, or null if the path was invalid. */
        protected static ImageIcon createImageIcon(String path) {
            java.net.URL imgURL = MenuLookDemo.class.getResource(path);
            if (imgURL != null) {
                return new ImageIcon(imgURL);
            } else {
                System.err.println("Couldn't find file: " + path);
                return null;
        public void init() {
            MenuLookDemoApplet demo = new MenuLookDemoApplet();
            setJMenuBar(demo.createMenuBar());
            setContentPane(demo.createContentPane());
    applet.html:
    <html>
    <head>
        <title>Menu Test Page </title>
    </head>
    <body>
    Here's the applet:
    <applet code="MenuLookDemoApplet.class" width="300" height="300">
    </applet>
    </body>
    </html>

    Unfortunately the menu items are fully accessible (or so our internal accessibility tool claims). It doesn't seem to be a problem on that level, but I was hoping that perhaps something else was interfeering.
    As for the JTable reading the previous cell, I've notice that it reads the last non-empty cell (regardless of whether it was the previous cell or not) when clicking or moving with the arrow keys to an empty cell. It works fine when clicking or moving to non-empty cells.
    I don't have any empty cells in the actual application so I did not try to fix it. My suspicions are that either an event is not being fired or the selection position is not being updated on the empty cells.

  • Swings-JFrame

    IN my program ,JFrame,JButton1 named VIEW ALL ,JComboBox ,JButton2 by clicking this calender will be displayed select the date ,that selected date will come into JComboBox,JButton3 named BY DATE.
    when click on VIEW ALL button data from the database(oracle 10g) will be retrieved into JTable, that table will be displayed in same JFrame.
    If we click on BY DATE button data will be displayed by that date only in the same JFrame.
    view is like this:
    VIEW ALL JCOmboBox JButton2 BY DATE
    display of JTable resultsin the same frame
    i have written the code for JTable like this;
    package crm;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.*;
    import java.lang.*;
    * @author rajeshwari
    public class Callbacks extends javax.swing.JFrame {
    JTable table;
         JTableHeader header;
         Vector data = new Vector();
         String colnames[];
    public Callbacks() {
    getConnection();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    // private void initComponents() {
    // jPanel1 = new javax.swing.JPanel();
    // jPanel2 = new javax.swing.JPanel();
    // jButton1 = new javax.swing.JButton();
    // jButton2 = new javax.swing.JButton();
    // jButton3 = new javax.swing.JButton();
    // jButton4 = new javax.swing.JButton();
    // jButton5 = new javax.swing.JButton();
    // jButton6 = new javax.swing.JButton();
    // jButton7 = new javax.swing.JButton();
    // jLabel1 = new javax.swing.JLabel();
    // jTextField1 = new javax.swing.JTextField();
    // jLabel2 = new javax.swing.JLabel();
    // jTextField2 = new javax.swing.JTextField();
    // jLabel3 = new javax.swing.JLabel();
    // jScrollPane1 = new javax.swing.JScrollPane();
    // jTextArea1 = new javax.swing.JTextArea();
    // jLabel4 = new javax.swing.JLabel();
    // jTextField3 = new javax.swing.JTextField();
    // jLabel5 = new javax.swing.JLabel();
    // jTextField4 = new javax.swing.JTextField();
    // jLabel6 = new javax.swing.JLabel();
    // jTextField5 = new javax.swing.JTextField();
    // jLabel7 = new javax.swing.JLabel();
    // jTextField6 = new javax.swing.JTextField();
    // jLabel8 = new javax.swing.JLabel();
    // jTextField7 = new javax.swing.JTextField();
    // jLabel9 = new javax.swing.JLabel();
    // jTextField8 = new javax.swing.JTextField();
    // jLabel10 = new javax.swing.JLabel();
    // jTextField9 = new javax.swing.JTextField();
    // jLabel11 = new javax.swing.JLabel();
    // jTextField10 = new javax.swing.JTextField();
    // jButton8 = new javax.swing.JButton();
    // jButton9 = new javax.swing.JButton();
    // jPanel3 = new javax.swing.JPanel();
    // jLabel12 = new javax.swing.JLabel();
    // jTextField11 = new javax.swing.JTextField();
    // jLabel13 = new javax.swing.JLabel();
    // jTextField12 = new javax.swing.JTextField();
    // jLabel14 = new javax.swing.JLabel();
    // jTextField13 = new javax.swing.JTextField();
    // jLabel15 = new javax.swing.JLabel();
    // jTextField14 = new javax.swing.JTextField();
    // jScrollPane2 = new javax.swing.JScrollPane();
    // jTextPane1 = new javax.swing.JTextPane();
    // jButton10 = new javax.swing.JButton();
    // jScrollPane3 = new javax.swing.JScrollPane();
    // jTextPane2 = new javax.swing.JTextPane();
    // jMenuBar1 = new javax.swing.JMenuBar();
    // jMenu1 = new javax.swing.JMenu();
    // jMenu2 = new javax.swing.JMenu();
    // jMenu3 = new javax.swing.JMenu();
    // jMenu4 = new javax.swing.JMenu();
    // jMenu5 = new javax.swing.JMenu();
    // jMenu6 = new javax.swing.JMenu();
    // jMenu7 = new javax.swing.JMenu();
    // jMenu8 = new javax.swing.JMenu();
    // setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    // jButton1.setText("Call Back");
    // jButton2.setText("Not Interested");
    // jButton3.setText("Person Not Available\n");
    // jButton4.setText("Answering Machine");
    // jButton5.setText("Person Available");
    // jButton6.setText("Do not Call");
    // jButton7.setText("Next>>...");
    // org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
    // jPanel2.setLayout(jPanel2Layout);
    // jPanel2Layout.setHorizontalGroup(
    // jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel2Layout.createSequentialGroup()
    // .addContainerGap()
    // .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jButton2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton7, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)))
    // jPanel2Layout.setVerticalGroup(
    // jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel2Layout.createSequentialGroup()
    // .addContainerGap()
    // .add(jButton1)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton2)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton3)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton4)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton5)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton6)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton7)
    // .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    // jLabel1.setText("\nCustomer ID:");
    // jTextField1.setText("852");
    // jLabel2.setText("Customer Name:");
    // jTextField2.setText("Rajeshwari");
    // jLabel3.setText("Address:");
    // jTextArea1.setColumns(20);
    // jTextArea1.setRows(5);
    // jScrollPane1.setViewportView(jTextArea1);
    // jLabel4.setText("City:");
    // jTextField3.setText("HYD");
    // jLabel5.setText("State:");
    // jTextField4.setText("A.P");
    // jLabel6.setText("Zip:");
    // jTextField5.setText("39");
    // jLabel7.setText("Phone:");
    // jTextField6.setText("220288");
    // jLabel8.setText("Mobile:");
    // jTextField7.setText("9949162978");
    // jLabel9.setText("Fax:");
    // jTextField8.setText("2343535");
    // jLabel10.setText("Email:");
    // jTextField9.setText("[email protected]");
    // jLabel11.setText("Call Time:");
    // jTextField10.setText("12:34:23");
    // jButton8.setText("Call Backs");
    // jButton8.addActionListener(new java.awt.event.ActionListener() {
    // public void actionPerformed(java.awt.event.ActionEvent evt) {
    // jButton8ActionPerformed(evt);
    // jButton9.setText("Hang");
    // jLabel12.setText("Call Back Date:");
    // jTextField11.setText("12-03-98");
    // jLabel13.setText("Call Back Time:");
    // jTextField12.setText("12:23:45");
    // jLabel14.setText("Called on:");
    // jTextField13.setText("11:12:99");
    // jLabel15.setText("Called At:");
    // jTextField14.setText("jTextField14");
    // jScrollPane2.setViewportView(jTextPane1);
    // jButton10.setText("ADD");
    // org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
    // jPanel3.setLayout(jPanel3Layout);
    // jPanel3Layout.setHorizontalGroup(
    // jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel3Layout.createSequentialGroup()
    // .addContainerGap()
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jLabel12)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jTextField11, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jLabel13)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jTextField12, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
    // .add(27, 27, 27)
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jLabel14)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jTextField13, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 84, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jLabel15)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jTextField14))))
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 187, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(28, 28, 28)
    // .add(jButton10)))
    // .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    // jPanel3Layout.setVerticalGroup(
    // jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel3Layout.createSequentialGroup()
    // .addContainerGap()
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel12)
    // .add(jTextField11, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jLabel14)
    // .add(jTextField13, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(17, 17, 17)
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel13)
    // .add(jTextField12, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jLabel15)
    // .add(jTextField14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)
    // .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
    // .add(jButton10)
    // .add(22, 22, 22))))
    // jScrollPane3.setViewportView(jTextPane2);
    // org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
    // jPanel1.setLayout(jPanel1Layout);
    // jPanel1Layout.setHorizontalGroup(
    // jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(30, 30, 30)
    // .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(32, 32, 32)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jLabel2)
    // .add(jLabel1)
    // .add(jLabel3)
    // .add(jLabel4)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
    // .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    // .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 46, Short.MAX_VALUE)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jTextField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE)
    // .add(jTextField2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE)
    // .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 149, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(58, 58, 58))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
    // .add(org.jdesktop.layout.GroupLayout.LEADING, jTextField3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
    // .add(jTextField4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE))
    // .add(66, 66, 66))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jTextField5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
    // .add(66, 66, 66))))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(254, 254, 254)))
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jButton8)
    // .add(27, 27, 27)
    // .add(jButton9))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
    // .add(jLabel7, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    // .add(jLabel8, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    // .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel9))
    // .add(jLabel10)
    // .add(jLabel11))
    // .add(6, 6, 6)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
    // .add(jTextField10)
    // .add(jTextField9)
    // .add(jTextField8)
    // .add(jTextField7)
    // .add(jTextField6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE)))
    // .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 212, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(45, 45, 45))
    // jPanel1Layout.setVerticalGroup(
    // jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(23, 23, 23)
    // .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(42, 42, 42)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel1)
    // .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jLabel7)
    // .add(jTextField6, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(16, 16, 16)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel2)
    // .add(jTextField2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(25, 25, 25)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jLabel3))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 17, Short.MAX_VALUE)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel4)
    // .add(jTextField3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(18, 18, 18)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel5)
    // .add(jTextField4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jTextField5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jButton8)
    // .add(jButton9)
    // .add(jLabel6, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 34, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(27, 27, 27)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel8)
    // .add(jTextField7, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(27, 27, 27)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel9)
    // .add(jTextField8, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(27, 27, 27)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel10)
    // .add(jTextField9, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(34, 34, 34)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel11)
    // .add(jTextField10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))))
    // .add(63, 63, 63)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
    // .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 88, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(44, 44, 44))))
    // jMenu1.setText("start");
    // jMenuBar1.add(jMenu1);
    // jMenu2.setText("Leads");
    // jMenuBar1.add(jMenu2);
    // jMenu3.setText("Campaign");
    // jMenuBar1.add(jMenu3);
    // jMenu4.setText("Reports");
    // jMenuBar1.add(jMenu4);
    // jMenu5.setText("Recordings");
    // jMenuBar1.add(jMenu5);
    // jMenu6.setText("Agents");
    // jMenuBar1.add(jMenu6);
    // jMenu7.setText("Time Zones");
    // jMenuBar1.add(jMenu7);
    // jMenu8.setText("Help");
    // jMenuBar1.add(jMenu8);
    // setJMenuBar(jMenuBar1);
    // org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
    // getContentPane().setLayout(layout);
    // layout.setHorizontalGroup(
    // layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(layout.createSequentialGroup()
    // .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    // layout.setVerticalGroup(
    // layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(layout.createSequentialGroup()
    // .add(78, 78, 78)
    // .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    // pack();
    // }// </editor-fold>
    public void getConnection()
    // Object src=evt.getSource();
    String name="";
    String call_back_date="";
    String call_back_time="";
    String called_on="";
    String called_at="";
    String phone="";
    String comments="";
    // if(src==jButton8)
    try{
    colnames=new String[]{"name","call_back_date","call_back_time","called_on","called_at","phone","comments"};
    Class.forName("oracle.jdbc.driver.OracleDriver");
    String url="jdbc:oracle:thin:@localhost:1521:oracle";
    Connection con=DriverManager.getConnection(url,"scott","root");
    Statement st=con.createStatement();
    ResultSet rs=st.executeQuery("select * from Callbacks_details");
              while (rs.next())
              name=rs.getString("name");
              call_back_date=rs.getString("call_back_date");
              call_back_time=rs.getString("call_back_time");
    called_on=rs.getString("called_on");
    called_at=rs.getString("called_at");
              phone=rs.getString("phone");
    comments=rs.getString("comments");
    Vector row = new Vector(colnames.length);
    // Vector r=new Vector();
              row.addElement(name);
              row.addElement(call_back_date);
              row.addElement(call_back_time);
    row.addElement(called_on);
    row.addElement(called_at);
              row.addElement(phone);
    row.addElement(comments);
              data.addElement(row);
    // System.out.println(data);
    catch(Exception a)
    a.printStackTrace();
    System.out.println(a);
    table=new JTable(new MyTableModel(colnames,data));
    //int n=table.getColumnCount();
              TableColumn column=null;
              for (int i = 0; i<colnames.length; i++) {
              column = table.getColumnModel().getColumn(i);
         column.setPreferredWidth(100);
              JScrollPane scrollPane = new JScrollPane(table);
              getContentPane().add(scrollPane);
    public class MyTableModel extends AbstractTableModel{
    String[] columnNames;
         Vector d= new Vector(6);
    MyTableModel(String[] columnNames, Vector data){
         this.columnNames = columnNames;
         d = data;
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return d.size();
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
         Vector d

    for displaying table on same frame(do not cross post and use code tags just click CODE and paste the code in between)
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    public class TableShow extends JFrame{
        /** Creates a new instance of TableShow */
        private javax.swing.JButton jButton1;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        public TableShow() {
            jTable1 = new javax.swing.JTable(5,5);
            jScrollPane1 = new javax.swing.JScrollPane(jTable1);
            jButton1 = new javax.swing.JButton("Show");
            jPanel1 = new javax.swing.JPanel();
            jPanel1.setLayout(new BorderLayout());
            jPanel1.add(jScrollPane1);
            jScrollPane1.setVisible(false);
            getContentPane().add(jButton1, BorderLayout.NORTH);
            getContentPane().add(jPanel1, BorderLayout.CENTER);
            setVisible(true);
            setSize(300,300);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            jButton1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if(jScrollPane1.isVisible()) {
                        jScrollPane1.setVisible(false);
                    } else{
                        jScrollPane1.setVisible(true);
                    jPanel1.validate();
        public static void main(String args[]){
            new TableShow();
    }

  • Glassfish SQLException: Error in allocating a connection in MySQL

    Hi All,
    I have just installed the Bundled Netbeans 6.5, Glassfish v2 and v3 Prelude (not including MySQL) that runs on top of MySQL 5.1 (separate installation) on server A, in order to mirror another similar working installation (Bundled Netbeans 6.1, Glassfish v2 including MySQL 5.0) on server B. Both Windows XP servers have got identical setups in their respective C:\Program Files\glassfish-v2ur2\domains\domain1\config\domain.xml files. However, the following error was encountered when trying to deploy the same EnterpriseApplication on server A which had no such problem on server B:
    Glassfish Server Log
    Server: unknown
    RAR5099 : Wrong class name or classpath for Datasource Object
    java.lang.ClassNotFoundException: com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource
            at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1498)
            at com.sun.gjc.common.DataSourceObjectBuilder.getDataSourceObject(DataSourceObjectBuilder.java:251)
            at com.sun.gjc.common.DataSourceObjectBuilder.constructDataSourceObject(DataSourceObjectBuilder.java:106)
    RAR5038:Unexpected exception while creating resource for pool mysqlPool. Exception : Class name is wrong or classpath is not set for : com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource
    RAR5117 : Failed to obtain/create connection from connection pool [ mysqlPool ]. Reason : Class name is wrong or classpath is not set for : com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource
    RAR5114 : Error allocating connection : [Error in allocating a connection. Cause: Class name is wrong or classpath is not set for : com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource]
    Exception occured in J2EEC Phase
    com.sun.enterprise.deployment.backend.IASDeploymentException:
    Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: Class name is wrong or classpath is not set for : com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource
    Error Code: 0
            at oracle.toplink.essentials.exceptions.DatabaseException.sqlException(DatabaseException.java:305)
    EnterpriseApplication (EJB 3.0) Deployment output
    Deploying application in domain failed; Deployment Errorjava.sql.SQLException: Error in allocating a connection. Cause: Class name is wrong or classpath is not set for : com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource --
    Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: Class name is wrong or classpath is not set for : com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource
    Error Code: 0
    C:\Documents and Settings\Jack\EnterpriseApplication\EnterpriseApplicationBean-ejb\nbproject\build-impl.xml:400: The module has not been deployed.Even manually re-creating the same project (as opposed to getting a copy of the Netbeans project folder from server B) did not make any difference. Likewise, the following jdbc connection pool definition was added possibly by Netbeans from Server Database JDBC Connection Resource setting:
          <property name="URL" value="jdbc:mysql://localhost:3306/employeeDB"/>
          <property name="driverClass" value="com.mysql.jdbc.Driver"/>
          <property name="Password" value="abcdef"/>
          <property name="portNumber" value="3306"/>
          <property name="databaseName" value="employeeDB"/>
          <property name="serverName" value="localhost"/>
          <property name="User" value="applicationuser"/>Can anyone see where the problem lies?
    Any assistance would be much appreciated.
    Thanks in advance,
    Jack

    I'm new to Java and GlassFish and I get the same error message when trying to ping my created data pool for MySQL. Inside the NetBeans IDE running Java Swing Applications + MySQL connection via JDBC, it works fine (Classpath settings ok). I set the same path to the JVM settings in Glassfish but every time I try to ping it the mentioned error occurs. Any suggestions?

  • Add Drop Shadow to JMenu Problem

    Hi,
    I got this code from "Swing Hacks", for some reason it does not run for me, but throws exceptions. I can not figure out why this is happening. This code straight out of the book, should be runnable. Below is the custom class, then the driver-test class, then the Exception:
    import javax.swing.plaf.basic.*;
    import javax.swing.plaf.*;
    import javax.swing.border.*;
    import javax.swing.*;
    import java.awt.*;
    public class CustomPopupMenuUI extends BasicPopupMenuUI{
         public static ComponentUI createUI(JComponent c){
              return new CustomPopupMenuUI();
         public Popup getPopup(JPopupMenu popup, int x,
                   int y){
              Popup pp = super.getPopup(popup, x,y);
              JPanel panel = (JPanel)popup.getParent();
              panel.setBorder(new ShadowBorder(3,3));
              panel.setOpaque(false);
              return pp;
    class ShadowBorder extends AbstractBorder{
         int xoff,yoff;
         Insets insets;
         public ShadowBorder(int x, int y){
              this.xoff = x;
              this.yoff = y;
              insets = new Insets(0,0,xoff,yoff);
         public Insets getBorderInsets(Component c){
              return insets;
         public void paintBorder(Component comp, Graphics g,
                   int x, int y, int width, int height){
              g.setColor(Color.BLACK);
              g.translate(x,y);
              // draw right side
              g.fillRect(width-xoff,yoff,xoff,height-yoff);
              // draw bottom side
              g.fillRect(xoff,height-yoff,width-xoff,yoff);
              g.translate(-x,-y);
    // Driver Below
    import javax.swing.*;
    import javax.swing.plaf.ComponentUI;
    import java.awt.*;
    public class MenuTest {
         public static void main(String[] args)throws Exception{
              UIManager.put("PopupMenuUI","CustomPopupMenuUI");
              //UIManager.put("MenuItemUI","LucentMenuItemUI");
              JFrame frame = new JFrame();
              JMenuBar mb = new JMenuBar();
              //mb.setUI(new CustomMenuUI());
              frame.setJMenuBar(mb);
              JMenu menu = new JMenu("File");
              mb.add(menu);
              menu.add(new JMenuItem("Open"));
              menu.add(new JMenuItem("Save"));
              menu.add(new JMenuItem("Close"));
              menu.add(new JMenuItem("Exit"));
              menu = new JMenu("Edit");
              mb.add(menu);
              menu.add(new JMenuItem("Cut"));
              menu.add(new JMenuItem("Copy"));
              menu.add(new JMenuItem("Paste"));
              menu.add(new JMenuItem("Paste Special.."));
              frame.getContentPane().setLayout(new BorderLayout());
              frame.getContentPane().add("North",new JButton("Button"));
              frame.getContentPane().add("Center",new JLabel("Label"));
              frame.getContentPane().add("South",new JCheckBox("checkbox"));
              frame.pack();
              frame.setSize(200,150);
              frame.show();
    }Exception:
    UIDefaults.getUI() failed: no ComponentUI class for: javax.swing.JPopupMenu[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=0,maximumSize=,minimumSize=,preferredSize=,desiredLocationX=0,desiredLocationY=0,label=,lightWeightPopupEnabled=true,margin=,paintBorder=true]
    java.lang.Error
         at javax.swing.UIDefaults.getUIError(Unknown Source)
         at javax.swing.MultiUIDefaults.getUIError(Unknown Source)
         at javax.swing.UIDefaults.getUI(Unknown Source)
         at javax.swing.UIManager.getUI(Unknown Source)
         at javax.swing.JPopupMenu.updateUI(Unknown Source)
         at javax.swing.JPopupMenu.<init>(Unknown Source)
         at javax.swing.JPopupMenu.<init>(Unknown Source)
         at javax.swing.JMenu.ensurePopupMenuCreated(Unknown Source)
         at javax.swing.JMenu.add(Unknown Source)
         at hacks.MenuTest.main(MenuTest.java:23)
    advTHANKSance

    I am also using xp and java version 1.4.2_08, but to no avail.. see below:
    C:\workspace\Swing Hacks\src>java -version
    java version "1.4.2_08"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_08-b03)
    Java HotSpot(TM) Client VM (build 1.4.2_08-b03, mixed mode)
    C:\workspace\Swing Hacks\src>java hacks.MenuTest
    UIDefaults.getUI() failed: no ComponentUI class for: javax.swing.JPopupMenu[,0,0
    ,0x0,invalid,alignmentX=null,alignmentY=null,border=,flags=0,maximumSize=,minimu
    mSize=,preferredSize=,desiredLocationX=0,desiredLocationY=0,label=,lightWeightPo
    pupEnabled=true,margin=,paintBorder=true]
    java.lang.Error
    at javax.swing.UIDefaults.getUIError(UIDefaults.java:689)
    at javax.swing.UIDefaults.getUI(UIDefaults.java:719)
    at javax.swing.UIManager.getUI(UIManager.java:784)
    at javax.swing.JPopupMenu.updateUI(JPopupMenu.java:204)
    at javax.swing.JPopupMenu.<init>(JPopupMenu.java:169)
    at javax.swing.JPopupMenu.<init>(JPopupMenu.java:154)
    at javax.swing.JMenu.ensurePopupMenuCreated(JMenu.java:521)
    at javax.swing.JMenu.add(JMenu.java:556)
    at hacks.MenuTest.main(MenuTest.java:23)
    UIDefaults.getUI() failed: no ComponentUI class for: javax.swing.JPopupMenu[,0,0
    ,0x0,invalid,alignmentX=null,alignmentY=null,border=,flags=0,maximumSize=,minimu
    mSize=,preferredSize=,desiredLocationX=0,desiredLocationY=0,label=,lightWeightPo
    pupEnabled=true,margin=,paintBorder=true]
    java.lang.Error
    at javax.swing.UIDefaults.getUIError(UIDefaults.java:689)
    at javax.swing.UIDefaults.getUI(UIDefaults.java:719)
    at javax.swing.UIManager.getUI(UIManager.java:784)
    at javax.swing.JPopupMenu.updateUI(JPopupMenu.java:204)
    at javax.swing.JPopupMenu.<init>(JPopupMenu.java:169)
    at javax.swing.JPopupMenu.<init>(JPopupMenu.java:154)
    at javax.swing.JMenu.ensurePopupMenuCreated(JMenu.java:521)
    at javax.swing.JMenu.add(JMenu.java:556)
    at hacks.MenuTest.main(MenuTest.java:30)
    I don't understand what the issue could be..
    Can anyone reproduce this error??

  • How to list/access swing components?

    hi all,
    Can anyone give me a clue, how can I access or simply list swing components I have on a frame, long after I created them. E.g. I'd like to change their setEnabled() attribute at a later time, not at creation time, but I don't know how to access them.
    Does Swing/AWT/JFC provides a component hierarchy? can someone share some code on this issue?
    Thanks for any help.
    Thomas

    I guess, you are saying the use of getComponent(int n)?
    Since I'm a beginner in Swing see my short code below:
    import java.awt.BorderLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JTextArea;
    public class EasyFrame {
        public EasyFrame() {
            super();
            startHere();
        public void startHere() {
            JFrame frame = new JFrame("SwingApplication");
            JButton button = new JButton("click here");
            JTextArea area = new JTextArea();
            frame.setSize(300, 200);
            frame.getContentPane().setLayout(new BorderLayout());
            frame.getContentPane().add(area, BorderLayout.CENTER);
            frame.getContentPane().add(button, BorderLayout.SOUTH);
            area.setText("Hello World");
            JMenuBar menuBar = new JMenuBar();
            JMenu menu = new JMenu("A Menu");
            menuBar.add(menu);
            JMenuItem menuItem = new JMenuItem("A text item");
            menu.add(menuItem);
            menu.addSeparator();
            menuItem = new JMenuItem("hello");
            menu.add(menuItem);
            JMenu subMenu = new JMenu("submenu");
            menuItem = new JMenuItem("sub1");
            subMenu.add(menuItem);
            menuItem = new JMenuItem("sub2");
            subMenu.add(menuItem);
            menu.add(subMenu);
            frame.getContentPane().add(menuBar, BorderLayout.NORTH);
            frame.show();
         public static void main(String[] args) {
         EasyFrame ef = new EasyFrame();
    }If I make a System.out.println(frame.getContentPane().getComponentCount());I get 3. But I should dig deeper (with getComponent(2)) to access JMenuBar. But this way I receive a AWT Component / not a JMenuBar Swing component to get its JMenu / and its JMenuItems. And I cannot make it cast to JMenuBar since this walk-through routine should be a universal while(isThereMoreCompenent){} procedure, I don't know when to cast to what (JMenu, JMenuItem, Button and so on).
    My problem is that how can I access the JMenuItems one by one, and change e.g. the setEnabled attribute of the "hello" menu?
    I hope you can make it clear to me.
    Please help if so.

  • Plz help me in creating swing interface

    Hi,
    Iam new to swing.I have one Interface on swing.Now I want to add Jfilechooser object in my interface for selecting file from hard drive.So that I can upload this file through my servlet uploading programme.I want to set remote url also for saving the file.But I confused how I can do that.Plz guide me.
    I try to create one interface but iam sure it is not the correct way.Can u plz try with my codes. Below r my codes:
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.JToolBar;
    import javax.swing.JButton;
    import javax.swing.ImageIcon;
    import javax.swing.JMenuItem;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JMenu;
    import javax.swing.JFrame;
    import javax.swing.JMenuBar;
    import javax.swing.JTextArea;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JProgressBar;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.util.*;
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    import java.net.*;
    import javax.swing.accessibility;
    public class ActionDemo1 extends JFrame implements ActionListener
         JTextArea textArea,textArea1,textArea2,textArea3,textArea4,textArea5,textArea6,textArea7,
         textArea8,textArea9,textArea10,textArea11,textArea12,textArea13,textArea14,textArea15;
         private JProgressBar progressBar;          
         private JButton Button,Button1,Button2;     
         URL url;
         BufferedReader in;
         String str;
    public ActionDemo1()
                        setTitle("Upload Interface");                               
                        addWindowListener(new WindowAdapter()
                             public void windowClosing(WindowEvent e)
                                  System.exit(0);
         Container contentPane = getContentPane();          
         JMenuItem menuItem = null;
    JToolBar toolBar = new JToolBar();
         JToolBar toolBar1 = new JToolBar();     
         JToolBar toolBar2 = new JToolBar();
         JToolBar toolBar3 = new JToolBar();
         JToolBar toolBar4 = new JToolBar();
         JToolBar toolBar5 = new JToolBar();
         JToolBar toolBar6 = new JToolBar();
         JToolBar toolBar7 = new JToolBar();
         JToolBar toolBar8 = new JToolBar();
         JToolBar toolBar9 = new JToolBar();
         JToolBar toolBar10 = new JToolBar();
         JMenu FirstMenu = new JMenu("File");
    FirstMenu.setMnemonic(KeyEvent.VK_F);     
    textArea = new JTextArea(5, 20);
         textArea1 = new JTextArea(2, 15);     
         textArea2 = new JTextArea(2, 15);
         textArea3 = new JTextArea(2, 15);     
         textArea4 = new JTextArea(7, 15);
         textArea5 = new JTextArea(7, 15);     
         textArea6 = new JTextArea(7, 15);
         textArea7 = new JTextArea(7, 15);
         textArea8 = new JTextArea(2, 15);
         textArea9 = new JTextArea(7, 15);
         textArea10 = new JTextArea(2, 15);
         textArea11 = new JTextArea(7, 15);
         textArea12 = new JTextArea(2, 15);
         textArea13 = new JTextArea(7, 15);
         textArea14 = new JTextArea(2, 15);
         textArea15 = new JTextArea(7, 15);
         JScrollPane scrollPane = new JScrollPane(textArea);
         progressBar=new JProgressBar();
         progressBar.setStringPainted(true);     
    contentPane.setLayout(new GridLayout(2,3));
         JPanel panel1 = new JPanel();
         panel1.setLayout(new BorderLayout());
         panel1.setBackground(Color.blue);
         contentPane.add(panel1);
    panel1.add(BorderLayout.NORTH, toolBar);
         panel1.add(scrollPane, BorderLayout.CENTER);
         panel1.add(progressBar,BorderLayout.SOUTH);     
         JPanel panel2 = new JPanel();     
         JLabel statusBar= new JLabel();
         panel2.setLayout(new GridLayout(1,1));     
         panel2.setBackground(Color.gray);     
         contentPane.add(panel2);
         JPanel panel3 = new JPanel();
         panel3.setLayout(new GridLayout(1,1));     
         panel3.setBackground(Color.blue);
         panel2.add(panel3);
         JPanel panel7 = new JPanel();
         panel7.setLayout(new BorderLayout());     
         panel7.setBackground(Color.blue);
         panel7.add(textArea2, BorderLayout.NORTH);     
         panel7.add(BorderLayout.CENTER, toolBar2);
         panel7.add(BorderLayout.SOUTH, textArea4);
         panel3.add(panel7);
         JPanel panel8 = new JPanel();
         panel8.setLayout(new BorderLayout());     
         panel8.setBackground(Color.blue);
         panel8.add(textArea3, BorderLayout.NORTH);     
         panel8.add(BorderLayout.CENTER, toolBar3);
         panel8.add(BorderLayout.SOUTH, textArea5);
         panel3.add(panel8);
         JPanel panel5 = new JPanel();
         panel5.setLayout(new BorderLayout());
         panel5.add(textArea1, BorderLayout.NORTH);
         panel5.add(BorderLayout.CENTER, toolBar5);
         panel5.add(BorderLayout.SOUTH, textArea7);          
         panel5.setBackground(Color.blue);
         panel3.add(panel5);
         JPanel panel6 = new JPanel();
         panel6.setLayout(new BorderLayout());
         panel6.add(toolBar1, BorderLayout.NORTH);          
         panel6.setBackground(Color.blue);
         panel6.setSize(new Dimension(5,5));
         panel6.add(BorderLayout.CENTER, toolBar4);
         panel6.add(BorderLayout.SOUTH, textArea6);
         panel3.add(panel6);
         JPanel panel4 = new JPanel();
         panel4.setLayout(new GridLayout(1,1));
         panel4.setBackground(Color.blue);     
         panel2.add(panel4);
         JPanel panel9 = new JPanel();
         panel9.setLayout(new BorderLayout());     
         panel9.setBackground(Color.blue);
         panel9.add(textArea8, BorderLayout.NORTH);     
         panel9.add(BorderLayout.CENTER, toolBar6);
         panel9.add(BorderLayout.SOUTH, textArea9);
         panel4.add(panel9);
         JPanel panel10 = new JPanel();
         panel10.setLayout(new BorderLayout());     
         panel10.setBackground(Color.blue);
         panel10.add(textArea10, BorderLayout.NORTH);     
         panel10.add(BorderLayout.CENTER, toolBar7);
         panel10.add(BorderLayout.SOUTH, textArea11);
         panel4.add(panel10);
         JPanel panel11 = new JPanel();
         panel11.setLayout(new BorderLayout());
         panel11.add(textArea12, BorderLayout.NORTH);
         panel11.add(BorderLayout.CENTER, toolBar8);
         panel11.add(BorderLayout.SOUTH, textArea13);          
         panel11.setBackground(Color.blue);
         panel4.add(panel11);
         JPanel panel12 = new JPanel();
         panel12.setLayout(new BorderLayout());
         panel12.add(toolBar9, BorderLayout.NORTH);          
         panel12.setBackground(Color.blue);
         panel12.setSize(new Dimension(5,5));
         panel12.add(BorderLayout.CENTER, toolBar10);
         panel12.add(BorderLayout.SOUTH, textArea15);
         panel4.add(panel12);
         //contentPane.setMaximumSize(new Dimension(600, 400));
         /*contentPane.setLayout(new BorderLayout());
         contentPane.setPreferredSize(new Dimension(400, 150));
         contentPane.add(toolBar, BorderLayout.NORTH);     
    statusBar = new JLabel(" ");     
         contentPane.add(scrollPane, BorderLayout.CENTER);
         setContentPane(contentPane);*/     
         JMenuBar mb = new JMenuBar();
         setJMenuBar(mb);
    mb.add(FirstMenu);     
    menuItem = new JMenuItem("Quick connect", KeyEvent.VK_Q);
    FirstMenu.add(menuItem);
         JMenu SecondMenu = new JMenu("Edit");
         SecondMenu.setMnemonic(KeyEvent.VK_E);     
    menuItem = new JMenuItem("Suspend", KeyEvent.VK_S);
    SecondMenu.add(menuItem);
    mb.add(SecondMenu);
    JMenu ThirdMenu = new JMenu("Compress");
         ThirdMenu.setMnemonic(KeyEvent.VK_C);     
    menuItem = new JMenuItem("By Percentage", KeyEvent.VK_B);
    ThirdMenu.add(menuItem);
    mb.add(ThirdMenu);
    JMenu FourthMenu = new JMenu("Help");
         FourthMenu.setMnemonic(KeyEvent.VK_H);     
    menuItem = new JMenuItem("Help", KeyEvent.VK_B);
    FourthMenu.add(menuItem);
    mb.add(FourthMenu);
    ImageIcon QuickConnect=new ImageIcon("images/Q_connect.gif");
    JButton button=new JButton(QuickConnect);
    button.setActionCommand("QuickConnect");
    button.setToolTipText("Quick Connect");
    button.addActionListener(this);
    toolBar.add(button);
    ImageIcon Reconnect=new ImageIcon("images/Reconnect.gif");
    button=new JButton(Reconnect);
    button.setActionCommand("Reconnect");
    button.setToolTipText("Reconnect");
    button.addActionListener(this);
    toolBar.add(button);
    ImageIcon Disconnect=new ImageIcon("images/Disconnect.gif");
    button=new JButton(Disconnect);
    button.setActionCommand("Disconnect");
    button.setToolTipText("Disconnect");
    button.addActionListener(this);
    toolBar.add(button);
    ImageIcon Upload=new ImageIcon("images/Upload.gif");
    Button=new JButton(Upload);
    Button.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    String strCommand=ae.getActionCommand();
    if(str.equals("Upload"))
    /* this is where you write the code to call that servlet.
    control reaches this point when the button is pressed */
    try{
    // you communicate with the servlet here
    url = new URL("http://127.0.0.1:7001/servletUpload");
    in = new BufferedReader(new InputStreamReader(url.openStream()));
    str = in.readLine();
    in.close();
    }//end try
    catch (Exception e1){}
    toolBar.add(Button);
    ImageIcon Suspend=new ImageIcon("images/Suspend.gif");
    Button1=new JButton(Suspend);
    //Button1.setActionCommand("Suspend");
    Button1.setToolTipText("Suspend");
    Button1.addActionListener(this);
    toolBar.add(Button1);
    ImageIcon Refresh=new ImageIcon("images/Refresh.gif");
    button=new JButton(Refresh);
    button.setActionCommand("Refresh");
    button.setToolTipText("Refresh");
    button.addActionListener(this);
    toolBar.add(button);
    ImageIcon DeleteItem=new ImageIcon("images/DeleteItem.gif");
    button=new JButton(DeleteItem);
    button.setActionCommand("DeleteItem");
    button.setToolTipText("DeleteItem");
    button.addActionListener(this);
    toolBar.add(button);
    ImageIcon Resume=new ImageIcon("images/Resume.gif");
    Button2=new JButton(Resume);
    //button.setActionCommand("Resume");
    Button2.setToolTipText("Resume");
    Button2.addActionListener(this);
    toolBar.add(Button2);
    ImageIcon FilePriority=new ImageIcon("images/FilePriority.gif");
    button=new JButton(FilePriority);
    button.setActionCommand("FilePriority");
    button.setToolTipText("FilePriority");
    button.addActionListener(this);
    toolBar.add(button);
    ImageIcon View=new ImageIcon("images/View.gif");
    button=new JButton(View);
    button.setActionCommand("View");
    button.setToolTipText("View");
    button.addActionListener(this);
    toolBar.add(button);
    ImageIcon Rename=new ImageIcon("images/Rename.gif");
    button=new JButton(Rename);
    button.setActionCommand("Rename");
    button.setToolTipText("Rename");
    button.addActionListener(this);
    toolBar.add(button);
    ImageIcon Scrolling=new ImageIcon("images/left.gif");
    button=new JButton(Scrolling);
    button.setActionCommand("Scrolling");
    button.setToolTipText("Scrolling");
    button.addActionListener(this);
    toolBar1.add(button);
    ImageIcon UScrolling=new ImageIcon("images/right.gif");
    button=new JButton( UScrolling);
    button.setActionCommand(" UScrolling");
    button.setToolTipText("UScrolling");
    button.addActionListener(this);
    toolBar1.add(button);
    ImageIcon Name=new ImageIcon("images/Name.gif");
    button=new JButton( Name);
    button.setActionCommand("Name");
    button.setToolTipText("Name");
    button.addActionListener(this);
    toolBar2.add(button);
    ImageIcon Date=new ImageIcon("images/Date.gif");
    button=new JButton( Date);
    button.setActionCommand("Date");
    button.setToolTipText("Date");
    button.addActionListener(this);
    toolBar3.add(button);
    ImageIcon Time=new ImageIcon("images/Time.gif");
    button=new JButton( Time);
    button.setActionCommand("Time");
    button.setToolTipText("Time");
    button.addActionListener(this);
    toolBar4.add(button);
    ImageIcon Size=new ImageIcon("images/Size.gif");
    button=new JButton(Size);
    button.setActionCommand("Size");
    button.setToolTipText("Size");
    button.addActionListener(this);
    toolBar5.add(button);
    ImageIcon TScrolling=new ImageIcon("images/left.gif");
    button=new JButton(TScrolling);
    button.setActionCommand("TScrolling");
    button.setToolTipText("TScrolling");
    button.addActionListener(this);
    toolBar9.add(button);
    ImageIcon DScrolling=new ImageIcon("images/right.gif");
    button=new JButton( DScrolling);
    button.setActionCommand(" DScrolling");
    button.setToolTipText("DScrolling");
    button.addActionListener(this);
    toolBar9.add(button);
    ImageIcon Name1=new ImageIcon("images/Name.gif");
    button=new JButton( Name1);
    button.setActionCommand("Name1");
    button.setToolTipText("Name1");
    button.addActionListener(this);
    toolBar6.add(button);
    ImageIcon Date1=new ImageIcon("images/Date.gif");
    button=new JButton( Date1);
    button.setActionCommand("Date1");
    button.setToolTipText("Date1");
    button.addActionListener(this);
    toolBar7.add(button);
    ImageIcon Time1=new ImageIcon("images/Time.gif");
    button=new JButton( Time1);
    button.setActionCommand("Time1");
    button.setToolTipText("Time1");
    button.addActionListener(this);
    toolBar10.add(button);
    ImageIcon Size1=new ImageIcon("images/Size.gif");
    button=new JButton(Size1);
    button.setActionCommand("Size1");
    button.setToolTipText("Size1");
    button.addActionListener(this);
    toolBar8.add(button);
    public void actionPerformed(ActionEvent e)
    textArea.setText(e.getActionCommand());
    public static void main(String[] args) {
    ActionDemo1 frame = new ActionDemo1();
    frame.pack();
    frame.setSize(new Dimension(650, 400));
    frame.setVisible(true);
    Regards
    Bikash

    You may find this suggestion useless, but I thnk you should seriously consider tossing your IDE in the trash and getting a good text editor and hand coding Swing until you understand how Swing components work.
    Take shortcuts when you understand where they will lead. You will find that hand coding really leads to a deeper understanding of any programming language.
    While you're at it, why don't you consider whether you really need eleven (!) toolbars in your GUI. A GUI generally needs only one toolbar -- save some for later.

  • Apply MVC to a Swing app?

    Folks,
    I got inspired by this thread: http://forum.java.sun.com/thread.jspa?threadID=5244847&start=23&tstart=0
    and wrote the below version of MineSweeper (winmine.exe) in Swing as a learning exercise.
    I'm about half way through my TODO list, and the code is "getting ugly". For instance, It took me a couple of hours to figure out what needed to change in order to keep track of the remaining bombs.
    This leads me to believe that the best way forward might be to declare this version to be "The Prototype" and go back to torres.... taking what I've learned about the problems involved, and designing the whole thing from ground up, applying the MVC paradigm.
    But I'm really unsure of how go about doing that... I studied program design back in the heyday of pseudo-code and structure charts, and I was hoping for some free advise (pretty please) or maybe some practical exercises/tutorials on OO program design. I've read some theory, but to be honest, it just goes over my head... in one ear and out the other. I hope that exercise of applying the principles espoused in the theory to a concrete example will help me to bring the theory into focus... at the moment GOF is rattling around in my brain, but it refuses coalesce into a coherent picture.
    I have a rough design in mind... Please would anyone care to comment?
    The Model
    * A Field has Mine's
    * Field would contain a matrix of Mine's ... mines[col][row]
    * Mine would encapsulate the state of each mine, and expose the a low level set of mutators.
    The View
    * Form extends JFrame - the main form
    * Top JPanel - much like the existing one
    * Bottom JPanel
    .... I'm wondering if a JTable would work in place of the existing matrix of JPanels.
    .... or can this be done with a LayoutManager... I'm thinking GridBagLayout?
    * Can I use a JPanel instead of the existing JPanel contains a JButton?
    .... * I've got an issue with the existing MouseListener implementation. You have to hold
    .... the mouse still and click each button rather deliberately. This ruins the fluidity of
    .... the game-play, substantially reducing the players enjoyment. ie: it gives me the sh1ts.
    .... Please does anyone have any ideas? I've used enough swing/awt apps to know
    .... that this isn't an insoluble problem, but I've got no idea how to address it.
    The Controler
    * A Game class orchestrates the whole thing at the high level.
    ... + main - Creates a new Game and calls it's play method.
    ... - play - Creates and shows the gui on the EDT
    * The MineLayer lays Mine's for the MineSweeper to clean up.
    .... But I'm a but lost as to what should "own" the MineLayer and the MineSweeper.
    .... To me it makes sense for the Controler to kick of the View, but from then on
    .... we're event-driven by the View... so should the View "create and own" the
    .... MineLayer and the MineSweeper? or should they be created by the controler
    .... and passed into the constructor of the main form? This OO stuff always leaves me
    .... feeling a bit thick. Back in my day you just called functions. It was ugly and simple.
    .... OO is ugly and complicated.
    package krc.games;
    import java.util.Random;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import java.awt.EventQueue;
    import java.awt.Container;
    import java.awt.Color;
    import java.awt.Insets;
    import java.awt.Font;
    import java.awt.BorderLayout;
    import java.awt.image.ColorModel;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.ImageIcon;
    import javax.swing.border.LineBorder;
    import javax.imageio.ImageIO;
    import java.awt.image.BufferedImage;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.io.File;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    // TODO:
    // * implement "you win"... track remaining bombs.                DONE
    // * show "not a bomb" at end of game.                            DONE
    // * display remaining bombs.                                     DONE
    // * display a clock.                                             DONE
    // * Resign/Refactor along MVC lines.
    //   M = A Field has Mine's
    //   V = The JFrame, some JPanels, a Grid?
    //   C = Game orchestrates. The MineLayer lays Mine's for the MineSweeper to clean up.
    // * beginner / intermediate / advanced / custom settings.
    //   - Find out how to use menu's in swing
    // * config board from command line args and/or properties file.
    //   - Use an XML Properties file.
    // * restart the same game. Reset the board with existing bombs. 
    //   - TOO EASY - remember the seed used passed to Random.
    // * high score.
    //   - CAPTURE: JOptionPane("Enter your name")
    //   - DISPLAY: A form with a grid
    //   - STORE  : Java only database
    // * save and load a game.
    //   - A de/serialization exercise.
    // * cheats - IDDKFA ;-)
    //   - keyboard listener to show bombs.
    import java.awt.image.BufferedImage;
    public class MineSweeperGame extends JFrame
      private static final long serialVersionUID = 0L;
      private static final int ROWS = 15;
      private static final int COLS = 30;
      private static final int BOMBS = (int)(ROWS * COLS / 4.5);
      private JLabel bombs = null; //count down the bombs
      private int bombsRemaining = BOMBS;
      private JLabel clock = null; //seconds since first click
      private int elapsedTime;
      private volatile boolean isClockRunning = false;
      private static final String DIR = "C:/Java/home/src/krc/games/";
      private static final BufferedImage FLAG_IMAGE     = loadImage(DIR+"/flag.jpg");
      private static final BufferedImage QUESTION_IMAGE = loadImage(DIR+"/question.jpg");
      private static final BufferedImage BOMB_IMAGE     = loadImage(DIR+"/bomb.jpg");
      private static final BufferedImage EXPLODED_IMAGE = loadImage(DIR+"/exploded_bomb.jpg");
      private static final BufferedImage NOT_BOMB_IMAGE = loadImage(DIR+"/not_bomb.jpg");
      // number colors
      private static final Color[] COLORS = {
        Color.black         // 0 not used
      , Color.blue          // 1 blue
      , new Color(0,153,153)// 4 darkGreen
      , Color.red           // 3 red
      , new Color(0,0,204)  // 4 darkBlue
      , new Color(153,0,0)  // 5 brown
      , Color.pink          // 6 pink
      , Color.orange        // 7 orange
      , Color.white         // 8 white
      , Color.magenta       // 9 magenta
      private static final Font FONT = new Font("Dialog", Font.BOLD, 12);
      private MouseListener mouseListener = new MouseAdapter() {
        public void mouseClicked(MouseEvent event) {
          if(!isClockRunning) startClock();
          Cell cell = ((Cell.Button)event.getSource()).getParentCell();
          if ( event.getButton() == MouseEvent.BUTTON1 ) {
            if (cell.isBomb()) {
              if ( cell.isMarkedAsBomb() ) {
                java.awt.Toolkit.getDefaultToolkit().beep();
              } else {
                cell.explode();
                youLost();
            } else {
              revealCell(cell);
          } else if ( event.getButton() == MouseEvent.BUTTON3 ) {
            cell.nextState();
      private class Cell extends JPanel {
        private static final long serialVersionUID = 0L;
        public static final int WIDTH = 17;
        public static final int HEIGHT = 17;
        public static final float Y_OFFSET = 13F;
        public static final float X_OFFSET = 5F;
        private class Button extends JButton {
          private static final long serialVersionUID = 0L;
          private final Cell parentCell;
          public Button(int width, int height, Cell parentCell) {
            this.parentCell = parentCell;
            this.setBounds(0, 0, width, height);
            this.setMargin(new Insets(1,1,1,1));
            this.setFont(new Font("Dialog",0,8));
            this.addMouseListener(mouseListener); // handle right button
          public void reset() {
            this.setText("");
            this.setVisible(true);
            this.setIcon(null);
          public Cell getParentCell() {
            return this.parentCell;
        private final Button button;
        private final int row, col;
        private boolean isBomb = false;
        private boolean isRevealed = false;
        private boolean isExploded = false;
        private int neighbours = 0;
        private ImageIcon[] stateIcons = new ImageIcon[] {
          null,  new ImageIcon(FLAG_IMAGE), new ImageIcon(QUESTION_IMAGE)
        private int state = 0;
        public static final int STATE_UNMARKED = 0;
        public static final int STATE_MARKED_AS_A_BOMB = 1;
        public static final int STATE_MARKED_AS_A_QUESTION = 2;
        Cell(int row, int col) {
          this.row = row;
          this.col = col;
          this.setBounds(col*WIDTH, row*HEIGHT, WIDTH, HEIGHT);
          this.setLayout(null);
          button = new Button(WIDTH, HEIGHT, this);
          this.add(button);
        public boolean isBomb() { return this.isBomb; }
        public void setBomb(boolean isBomb) { this.isBomb = isBomb; }
        public boolean isRevealed() { return this.isRevealed; }
        public void reveal() {
          if(this.isRevealed) return;
          this.button.setVisible(false);
          this.isRevealed = true;
        public void revealNotABomb() {
          button.setText("");
          button.setIcon(new ImageIcon(NOT_BOMB_IMAGE));
        public boolean isExploded() { return this.isExploded; }
        public void explode() {this.isExploded = true;}
        public int getNeighbours() { return this.neighbours; }
        public void setNeighbours(int neighbours) {this.neighbours = neighbours;}
        public void reset() {
          this.isRevealed = false;
          this.isBomb = false;
          this.isExploded = false;
          this.state = STATE_UNMARKED;
          this.button.reset();
        public boolean isMarkedAsBomb() {
          return this.state == Cell.STATE_MARKED_AS_A_BOMB;
        public void nextState() {
          boolean wasMarkedAsABomb = this.isMarkedAsBomb();
          this.state = (this.state+1) % 3;
          button.setIcon(stateIcons[this.state]);
          if (this.isMarkedAsBomb()) {
            setBombsRemaining(getBombsRemaining()-1);
            if (getBombsRemaining() == 0) {
              if (allMarkedBombsAreReallyBombs()) {
                youWon();
              } else {
                youLost();
          } else if (wasMarkedAsABomb) {
            setBombsRemaining(getBombsRemaining()+1);
        @Override
        public void paintComponent(Graphics g) {
          super.paintComponent(g);
          if ( this.isRevealed() ) {
            Graphics2D g2d = (Graphics2D) g;
            if (this.isExploded) {
              g2d.drawImage(EXPLODED_IMAGE, 0, 0, null);
            } else if (this.isBomb) {
              g2d.drawImage(BOMB_IMAGE, 0, 0, null);
            } else if (this.neighbours > 0) {
              g2d.setColor(COLORS[this.neighbours]);
              g2d.setFont(FONT);
              g2d.drawString(""+this.neighbours, X_OFFSET, Y_OFFSET);
      private Cell[][] cells = new Cell[ROWS][COLS];
      MineSweeperGame() {
        super();
        buildAndShowGUI();
      private void buildAndShowGUI() {
        this.setTitle("Miner");
        final int CELLS_X = Cell.WIDTH*COLS;
        final int WASTE_X = 6;
        final int WIN_WIDTH = CELLS_X+WASTE_X;
        final int CELLS_Y = Cell.HEIGHT*ROWS;
        final int WASTE_Y = 32;
        final int TOP_FRAME_Y = 34;
        final int WIN_HEIGHT = CELLS_Y+WASTE_Y+TOP_FRAME_Y;
        this.setSize(WIN_WIDTH, WIN_HEIGHT);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setResizable(false);
        Container pane = this.getContentPane();
        pane.setLayout(null);
        JPanel top = new JPanel();
        top.setBounds(0,0, WIN_WIDTH,TOP_FRAME_Y);
        top.setBorder(new LineBorder(Color.black));
        top.setLayout(null);
        bombs = new JLabel();
        bombs.setBounds(5,7, 23,17);
        bombs.setBorder(new LineBorder(Color.black));
        top.add(bombs);
        clock = new JLabel("0");
        clock.setBounds(WIN_WIDTH-35,7, 23,17);
        clock.setBorder(new LineBorder(Color.black));
        top.add(clock);
        pane.add(top);
        JPanel bot = new JPanel();
        bot.setLayout(null);
        bot.setBackground(Color.white);
        bot.setBounds(0, TOP_FRAME_Y+1, CELLS_X, CELLS_Y);
        for(int r=0; r<ROWS; r++) {
          for(int c=0; c<COLS; c++) {
            cells[r][c] = new Cell(r, c);
            bot.add(cells[r][c]);
        pane.add(bot);
        resetGame();
        this.setVisible(true);
      private void resetGame() {
        resetClock();
        resetCells();
        placeBombs();
        setBombsRemaining(BOMBS);
        countNeighbouringBombs();
      private void resetCells() {
        // reset all the cells
        for(int r=0; r<ROWS; r++) {
          for(int c=0; c<COLS; c++) {
            cells[r][c].reset();
      private void placeBombs() {
        // randomly place however many bombs in the minefield
        Random rand = new Random(System.currentTimeMillis());
        for(int i=0; i<BOMBS; i++) {
          while(true) {
            Cell cell = this.cells[rand.nextInt(ROWS)][rand.nextInt(COLS)];
            if (!cell.isBomb()) {
              cell.setBomb(true);
              cell.button.setText("b");
              break;
      // count the number of bombs neighbouring each cell
      private void countNeighbouringBombs() {
        for(int r=0; r<ROWS; r++) {
          for(int c=0; c<COLS; c++) {
            cells[r][c].setNeighbours(getNeighbourCount(r, c));
      // the number of bombs neighbouring the given cell
      private int getNeighbourCount(int row, int col) {
        int count = 0;
        int firstRow = Math.max(row-1, 0);
        int lastRow  = Math.min(row+1, ROWS-1);
        int firstCol = Math.max(col-1, 0);
        int lastCol  = Math.min(col+1, COLS-1);
        for(int r=firstRow; r<=lastRow; r++) {
          for(int c=firstCol; c<=lastCol; c++) {
            if( this.cells[r][c].isBomb ) count++;
        return count;
      public void setBombsRemaining(int bombsRemaining) {
        this.bombsRemaining = bombsRemaining;
        this.bombs.setText(""+this.bombsRemaining);
      public int getBombsRemaining() {
        return(this.bombsRemaining);
      private void showBombs() {
        for(int r=0; r<ROWS; r++) {
          for(int c=0; c<COLS; c++) {
            Cell cell = cells[r][c];
            if (cell.isBomb) {
              cell.reveal();
            } else if (cell.isMarkedAsBomb()) {
              cell.revealNotABomb();
      private boolean allMarkedBombsAreReallyBombs() {
        for(int r=0; r<ROWS; r++) {
          for(int c=0; c<COLS; c++) {
            Cell cell = this.cells[r][c];
            if (cell.isMarkedAsBomb() && !cell.isBomb() ) {
              return false;
        return true;
      private void revealCell(Cell cell) {
        if(cell.getNeighbours()==0) {
          revealCells(cell, new HashMap<Cell,Object>());
        } else {
          cell.reveal();
      private void revealCells(Cell cell, Map<Cell,Object> ancestors) {
        if (ancestors.containsKey(cell)) return;
        if (cell.isRevealed()) return;
        ancestors.put(cell, null);
        cell.reveal();
        if(cell.getNeighbours()==0) {
          int firstRow = Math.max(cell.row-1, 0);
          int lastRow  = Math.min(cell.row+1, ROWS-1);
          int firstCol = Math.max(cell.col-1, 0);
          int lastCol  = Math.min(cell.col+1, COLS-1);
          for(int r=firstRow; r<=lastRow; r++) {
            for(int c=firstCol; c<=lastCol; c++) {
              Cell x = cells[r][c];
              if (x == cell) continue;
              if( !x.isBomb() && !x.isRevealed() ) {
                revealCells(x, ancestors);
      private void youLost() {
        stopClock();
        showBombs();
        JOptionPane.showMessageDialog(this, "You Lost.", "Game Over", JOptionPane.WARNING_MESSAGE);
        resetGame();
      private void youWon() {
        stopClock();
        JOptionPane.showMessageDialog(this, "You Won. Congratulations.", "Game Over", JOptionPane.INFORMATION_MESSAGE);
        resetGame();
      private static BufferedImage loadImage(String filename) {
        try {
          return ImageIO.read(new File(filename));
        } catch (IOException e) {
          // the game will still kinda work, you just won't see this image.
          e.printStackTrace();
        return null;
      private void startClock() {
        isClockRunning = true;
        new Thread() {
          public void run() {
            while (isClockRunning) {
              clock.setText(""+(elapsedTime++));
              //repaint();
              try{Thread.sleep(1000);}catch(InterruptedException eaten){}
        }.start();
      private void stopClock() {
        this.isClockRunning = false;
      private void resetClock() {
        elapsedTime = 0;
        clock.setText("0");
      public static void main(String[] args) {
        try {
          EventQueue.invokeLater(
            new Runnable() {
              public void run() {
                MineSweeperGame game = new MineSweeperGame();
        } catch (Exception e) {
          e.printStackTrace();
    }Thanx in advance for any ideas.
    Cheers. Keith.
    Edited by: corlettk on Dec 23, 2007 6:15 AM - typos.

    For anyone who's interested... here's the latest (and complete, I think) version of the program.... there's quit a lot of code here, sorry. It should all compile first time... but you'll need to scrape your own set of images from minesweeper (ie: winmine.exe) and google for the wav files... It's a shame we can't post jar's or zip's here.
    MineSweeperGame.java
    package krc.games.sweeper;
    import java.util.Random;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JMenuBar;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JRadioButtonMenuItem;
    import javax.swing.ButtonGroup;
    import java.awt.Color;
    import java.awt.Insets;
    import java.awt.Font;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.ImageIcon;
    import javax.swing.border.LineBorder;
    import java.io.File;
    import javax.imageio.ImageIO;
    import java.awt.image.BufferedImage;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.util.HashMap;
    import java.util.Map;
    import krc.utilz.sound.WavePlayer;
    // TODO:
    // * implement "you win"... track remaining bombs.                    DONE
    // * show "not a bomb" at end of game.                                DONE
    // * display remaining bombs.                                         DONE
    // * display a clock.                                                 DONE
    // * Resign/Refactor along MVC lines.                                 NOT DONE
    //   M = A Field has Mine's
    //   V = The JFrame, some JPanels, a Grid?
    //   C = Controler orcestrates.
    // * beginner / intermediate / advanced / custom settings.            DONE
    //   - Find out how to use menu's in swing
    // * config board from command line args and/or properties file.      DONE
    //   - used a standard properties file
    // * restart the same game. Reset the board with existing bombs.      DONE
    //   - TOO EASY - remember the seed used passed to Random.
    // * high score.
    //   - CAPTURE: JOptionPane("Enter your name")
    //   - DISPLAY: A form with a grid
    //   - STORE  : Java only database
    // * save and load a game.
    //   - A de/serialization exercise.
    // * cheats
    //   until the first 0 is hit
    //   - ctrl-click - is bomb proof (costs 5 seconds)                   DONE
    //   - fifth click reveals the biggest patch of 0's                   DONE
    //   god mode
    //   - ctrl-alt-shift shows the position of all bombs.                DONE
    //     // search for "b" - uncomment that line)
    public class MineSweeperGame extends JFrame
      private static final long serialVersionUID = 0L;
      //these are read from properties files
      private GameSettings settings;
      private JFrame theFrame;
      private JLabel bombs = null; //count down the bombs
      private int bombsRemaining;
      private boolean replayCurrentGame = false;
      private long randomSeed = 0;
      private GameClock clock = null; //seconds since first click
      private static final String DIR = "C:/Java/home/src/krc/games/sweeper/";
      private static final String IMGDIR = DIR+"images/";
      private static final BufferedImage FLAG_IMAGE     = loadImage(IMGDIR+"flag.jpg");
      private static final BufferedImage QUESTION_IMAGE = loadImage(IMGDIR+"question.jpg");
      private static final BufferedImage BOMB_IMAGE     = loadImage(IMGDIR+"bomb.jpg");
      private static final BufferedImage EXPLODED_IMAGE = loadImage(IMGDIR+"exploded_bomb.jpg");
      private static final BufferedImage NOT_BOMB_IMAGE = loadImage(IMGDIR+"not_bomb.jpg");
      private static final String WAVDIR = DIR+"sounds/";
      // number colors
      private static final Color[] COLORS = {
        Color.black         // 0 not used
      , Color.blue          // 1 blue
      , new Color(0,153,153)// 4 darkGreen
      , Color.red           // 3 red
      , new Color(0,0,204)  // 4 darkBlue
      , new Color(153,0,0)  // 5 brown
      , Color.pink          // 6 pink
      , Color.orange        // 7 orange
      , Color.white         // 8 white
      , Color.magenta       // 9 magenta
      private static final Font FONT = new Font("Dialog", Font.BOLD, 12);
      private class GameMenuBar extends JMenuBar
        private static final long serialVersionUID = 0L;
        private ActionListener menuListener = new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            String action = event.getActionCommand().toLowerCase();
            if ("new".equals(action)) {
              hideAndDestroyGUI();
              buildAndShowGUI();
            } else if ("restart".equals(action)) {
              hideAndDestroyGUI();
              replayCurrentGame = true;
              buildAndShowGUI();
            } else if ( "beginner,intermediate,expert,custom".indexOf(action) > -1 ) {
              hideAndDestroyGUI();
              if ( "custom".equals(action) ) {
                CustomSettingsDialog dialog = new CustomSettingsDialog(theFrame, properties.get("custom"));
                settings = dialog.getSettings();
                dialog.dispose();
                properties.set(settings);
              } else {
                settings = properties.get(action);
              buildAndShowGUI();
            } else if ("exit".equals(action)) {
              setVisible(false);
              dispose();
            } else {
              java.awt.Toolkit.getDefaultToolkit().beep();
              System.out.println("Menu item ["+event.getActionCommand()+"] was pressed.");
        public GameMenuBar(String level) {
          JMenu menu = new JMenu("Game");
          menu.add(newJMenuItem("New", 'N'));
          menu.add(newJMenuItem("Restart", 'R'));
          menu.addSeparator();
          ButtonGroup group = new ButtonGroup();
          menu.add(newJRadioButtonMenuItem(group, "Beginner", level));
          menu.add(newJRadioButtonMenuItem(group, "Intermediate", level));
          menu.add(newJRadioButtonMenuItem(group, "Expert", level));
          menu.add(newJRadioButtonMenuItem(group, "Custom", level));
          menu.addSeparator();
          menu.add(newJMenuItem("Exit", 'X'));
          this.add(menu);
        private JMenuItem newJMenuItem(String text, char mneumonic) {
          JMenuItem item = new JMenuItem(text, mneumonic);
          item.addActionListener(this.menuListener);
          return item;
        private JRadioButtonMenuItem newJRadioButtonMenuItem(ButtonGroup group, String text, String level) {
          JRadioButtonMenuItem item = new JRadioButtonMenuItem(text);
          item.addActionListener(this.menuListener);
          group.add(item);
          if(text.equalsIgnoreCase(level)) item.setSelected(true);
          return item;
      private class Cell extends JPanel
        private static final long serialVersionUID = 0L;
        public static final int WIDTH = 17;
        public static final int HEIGHT = 17;
        public static final float Y_OFFSET = 13F;
        public static final float X_OFFSET = 5F;
        private class Button extends JButton {
          private static final long serialVersionUID = 0L;
          private final Cell parentCell;
          public Button(int width, int height, Cell parentCell) {
            this.parentCell = parentCell;
            this.setBounds(0, 0, width, height);
            this.setMargin(new Insets(1,1,1,1));
            this.setFont(new Font("Dialog",0,8));
            this.addMouseListener(mouseListener); // handles left & right button
          public void reset() {
            this.setText("");
            this.setVisible(true);
            this.setIcon(null);
          public Cell getParentCell() {
            return this.parentCell;
          public void removeMouseListener() {
            this.removeMouseListener(mouseListener);
        private final Button button;
        private final int row, col;
        private boolean isBomb = false;
        private boolean isRevealed = false;
        private boolean isExploded = false;
        private int neighbours = 0;
        public static final int STATE_UNMARKED = 0;
        public static final int STATE_MARKED_AS_A_BOMB = 1;
        public static final int STATE_MARKED_AS_A_QUESTION = 2;
        private int state = 0;
        private ImageIcon[] stateIcons = new ImageIcon[] {
          null,  new ImageIcon(FLAG_IMAGE), new ImageIcon(QUESTION_IMAGE)
        Cell(int row, int col) {
          this.row = row;
          this.col = col;
          this.setBounds(col*WIDTH, row*HEIGHT, WIDTH, HEIGHT);
          this.setLayout(null);
          button = new Button(WIDTH, HEIGHT, this);
          this.add(button);
        public boolean isBomb() { return this.isBomb; }
        public void setBomb(boolean isBomb) { this.isBomb = isBomb; }
        public boolean isRevealed() { return this.isRevealed; }
        public void reveal() {
          if(this.isRevealed) return;
          this.button.setVisible(false);
          this.isRevealed = true;
        public void revealNotABomb() {
          button.setText("");
          button.setIcon(new ImageIcon(NOT_BOMB_IMAGE));
        public boolean isExploded() { return this.isExploded; }
        public void explode() {this.isExploded = true;}
        public int getNeighbours() { return this.neighbours; }
        public void setNeighbours(int neighbours) {this.neighbours = neighbours;}
        public void reset() {
          this.isRevealed = false;
          this.isBomb = false;
          this.isExploded = false;
          this.state = STATE_UNMARKED;
          this.button.reset();
        public boolean isMarkedAsBomb() {
          return this.state == Cell.STATE_MARKED_AS_A_BOMB;
        public void nextState() {
          boolean wasMarkedAsABomb = this.isMarkedAsBomb();
          this.state = (this.state+1) % 3;
          button.setIcon(stateIcons[this.state]);
          if (this.isMarkedAsBomb()) {
            setBombsRemaining(getBombsRemaining()-1);
            if (getBombsRemaining() == 0) {
              if (allMarkedBombsAreReallyBombs()) {
                youWon();
              } else {
                youLost();
          } else if (wasMarkedAsABomb) {
            setBombsRemaining(getBombsRemaining()+1);
        public void removeMouseListener() {
          button.removeMouseListener();
        @Override
        public void paintComponent(Graphics g) {
          super.paintComponent(g);
          if ( this.isRevealed() ) {
            Graphics2D g2 = (Graphics2D) g;
            if (this.isExploded) {
              g2.drawImage(EXPLODED_IMAGE, 0, 0, null);
            } else if (this.isBomb) {
              g2.drawImage(BOMB_IMAGE, 0, 0, null);
            } else if (this.neighbours > 0) {
              g2.setColor(COLORS[this.neighbours]);
              g2.setFont(FONT);
              g2.drawString(""+this.neighbours, X_OFFSET, Y_OFFSET);
      private MouseListener mouseListener = null;
      private GameProperties properties = null;
      private Cell[][] cells = null;
      // this game is a "virgin" until the user finds the first 0.
      private boolean isVirgin = false;
      // when the user clears fifth square of a virgin game the
      // largest patch of 0's is automagically cleared.
      private int numCleared = 0;
      MineSweeperGame() {
        theFrame = this;
        this.properties = new GameProperties();
        this.settings = this.properties.get();
        buildAndShowGUI();
      private void setMouseListener(){
        this.mouseListener = new MouseAdapter() {
          public void mouseClicked(MouseEvent event) {
            clock.start();
            Cell cell = ((Cell.Button)event.getSource()).getParentCell();
            if ( event.getButton() == MouseEvent.BUTTON1 ) {
              if(event.isControlDown()) clock.skip(5);
              if (cell.isBomb()) {
                if ( cell.isMarkedAsBomb() ) {
                  java.awt.Toolkit.getDefaultToolkit().beep();
                } else if ( event.isControlDown() ) {
                  WavePlayer.play(WAVDIR+"ricochet.wav");
                } else {
                  WavePlayer.play(WAVDIR+"grenade.wav");
                  cell.explode();
                  youLost();
              } else {
                revealCell(cell);
                if ( isVirgin && ++numCleared==5 ) {
                  WavePlayer.play(WAVDIR+"smokin.wav");
                  revealTheBiggestFreePatch();
            } else if ( event.getButton() == MouseEvent.BUTTON3 ) {
              cell.nextState();
      private void hideAndDestroyGUI() {
        this.setVisible(false);
        for(int r=0; r<settings.rows; r++) {
          for(int c=0; c<settings.cols; c++) {
            cells[r][c].removeMouseListener(); // old mouse listeners send it crazy.
            cells[r][c] = null;
        this.getContentPane().removeAll();
        this.dispose();
      private void buildAndShowGUI() {
        final int CELLS_X = Cell.WIDTH*settings.cols;
        final int WASTE_X = 9;
        final int WIN_WIDTH = CELLS_X+WASTE_X;
        final int CELLS_Y = Cell.HEIGHT*settings.rows;
        final int WASTE_Y = 59;
        final int TOP_FRAME_Y = 34;
        final int WIN_HEIGHT = CELLS_Y+WASTE_Y+TOP_FRAME_Y;
        this.setTitle("Miner");
        this.setSize(WIN_WIDTH, WIN_HEIGHT);
        this.setResizable(false);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setJMenuBar( new GameMenuBar(this.settings.level) );
        this.getContentPane().setLayout(null);
        // the top panel
        JPanel top = new JPanel(null);
        top.setBounds(0,0, WIN_WIDTH-6,TOP_FRAME_Y);
        top.setBorder(new LineBorder(Color.black));
        // the remaining-bomb-counter (on the left)
        bombs = new JLabel();
        bombs.setBounds(5,7, 23,17);
        bombs.setBorder(new LineBorder(Color.black));
        top.add(bombs);
        // the time-counter (on the right)
        this.clock = new GameClock();
        clock.setBounds(WIN_WIDTH-35,7, 23,17);
        top.add(clock);
        this.getContentPane().add(top);
        // the bottom panel
        setMouseListener();
        JPanel bot = new JPanel();
        bot.setLayout(null);
        bot.setBackground(Color.white);
        bot.setBounds(0, TOP_FRAME_Y+1, CELLS_X, CELLS_Y);
        this.cells = new Cell[settings.rows][settings.cols];
        for(int r=0; r<settings.rows; r++) {
          for(int c=0; c<settings.cols; c++) {
            cells[r][c] = new Cell(r, c);
            bot.add(cells[r][c]);
        this.getContentPane().add(bot);
        resetGame();
        this.setVisible(true);
      private void resetGame() {
        clock.reset();
        resetCells();
        isVirgin = true;
        numCleared = 0;
        placeBombs();
        setBombsRemaining(settings.bombs);
        countNeighbouringBombs();
      // reset the state of all the cells to default "empty" values.
      private void resetCells() {
        for(int r=0; r<settings.rows; r++) {
          for(int c=0; c<settings.cols; c++) {
            cells[r][c].reset();
      // randomly place however many bombs in the minefield
      // if replay then reuses the same seed to reproduce the same mine layout.
      private void placeBombs() {
        if(!this.replayCurrentGame) this.randomSeed = System.currentTimeMillis();
        this.replayCurrentGame = false;
        Random rand = new Random(this.randomSeed);
        for(int i=0; i<settings.bombs; i++) {
          while(true) {
            Cell cell = this.cells[rand.nextInt(settings.rows)][rand.nextInt(settings.cols)];
            if (!cell.isBomb()) {
              cell.setBomb(true);
              //cell.button.setText("b");
              break;
      // count the number of bombs neighbouring each cell
      private void countNeighbouringBombs() {
        for(int r=0; r<settings.rows; r++) {
          for(int c=0; c<settings.cols; c++) {
            cells[r][c].setNeighbours(getNeighbourCount(r, c));
      // return the number of bombs neighbouring the given cell
      private int getNeighbourCount(int row, int col) {
        int count = 0;
        int firstRow = Math.max(row-1, 0);
        int lastRow  = Math.min(row+1, settings.rows-1);
        int firstCol = Math.max(col-1, 0);
        int lastCol  = Math.min(col+1, settings.cols-1);
        for(int r=firstRow; r<=lastRow; r++) {
          for(int c=firstCol; c<=lastCol; c++) {
            if( this.cells[r][c].isBomb ) count++;
        return count;
      public void setBombsRemaining(int bombsRemaining) {
        this.bombsRemaining = bombsRemaining;
        this.bombs.setText(""+this.bombsRemaining);
      public int getBombsRemaining() {
        return(this.bombsRemaining);
      private void showBombs() {
        for(int r=0; r<settings.rows; r++) {
          for(int c=0; c<settings.cols; c++) {
            Cell cell = cells[r][c];
            if (cell.isBomb) {
              cell.reveal();
            } else if (cell.isMarkedAsBomb()) {
              cell.revealNotABomb();
      private boolean allMarkedBombsAreReallyBombs() {
        for(int r=0; r<settings.rows; r++) {
          for(int c=0; c<settings.cols; c++) {
            Cell cell = this.cells[r][c];
            if (cell.isMarkedAsBomb() && !cell.isBomb() ) {
              return false;
        return true;
      private void revealCell(Cell cell) {
        if(cell.getNeighbours()==0) {
          revealCells(cell, new HashMap<Cell,Object>());
        } else {
          cell.reveal();
      private void revealTheBiggestFreePatch() {
        Map<Cell,Object> counted = new HashMap<Cell,Object>();
        int count = 0;
        int max = 0;
        Cell maxCell = null;
        for(int r=0; r<settings.rows; r++) {
          for(int c=0; c<settings.cols; c++) {
            Cell cell = this.cells[r][c];
            if(cell.getNeighbours()==0) {
              count = countNeighbouringZeros(cell, counted);
              if(count > max) {
                max = count;
                maxCell = cell;
        revealCell(maxCell);
      private int countNeighbouringZeros(Cell cell, Map<Cell,Object> counted) {
        int count = 0;
        if (counted.containsKey(cell)) return 0;
        counted.put(cell, null);
        if(cell.getNeighbours()==0) {
          count++;
          int firstRow = Math.max(cell.row-1, 0);
          int lastRow  = Math.min(cell.row+1, settings.rows-1);
          int firstCol = Math.max(cell.col-1, 0);
          int lastCol  = Math.min(cell.col+1, settings.cols-1);
          for(int r=firstRow; r<=lastRow; r++) {
            for(int c=firstCol; c<=lastCol; c++) {
              Cell x = cells[r][c];
              if (x == cell) continue;
              if (x.getNeighbours()==0) {
                count += countNeighbouringZeros(x, counted);
        return count;
      private void revealCells(Cell cell, Map<Cell,Object> ancestors) {
        if (ancestors.containsKey(cell)) return;
        if (cell.isRevealed()) return;
        ancestors.put(cell, null);
        cell.reveal();
        if(cell.getNeighbours()==0) {
          isVirgin = false;
          int firstRow = Math.max(cell.row-1, 0);
          int lastRow  = Math.min(cell.row+1, settings.rows-1);
          int firstCol = Math.max(cell.col-1, 0);
          int lastCol  = Math.min(cell.col+1, settings.cols-1);
          for(int r=firstRow; r<=lastRow; r++) {
            for(int c=firstCol; c<=lastCol; c++) {
              Cell x = cells[r][c];
              if (x == cell) continue;
              if( !x.isBomb() && !x.isRevealed() ) {
                revealCells(x, ancestors);
      private void youLost() {
        clock.stop();
        showBombs();
        //WavePlayer.play(WAVDIR+"msstartup.wav");
        Object[] options = { "Replay", "New Game" };
        int choice = JOptionPane.showOptionDialog(
            null
          , "Replay?"
          , "Game Over."
          , JOptionPane.DEFAULT_OPTION
          , JOptionPane.QUESTION_MESSAGE
          , null
          , options
          , options[0]
        if (choice == 0) {
          replayCurrentGame = true;
        resetGame();
      private void youWon() {
        clock.stop();
        WavePlayer.play(WAVDIR+"applause.wav");
        JOptionPane.showMessageDialog(this, "Congratulations. You Won!", "Game Over", JOptionPane.INFORMATION_MESSAGE);
        resetGame();
      private static BufferedImage loadImage(String filename) {
        try {
          return ImageIO.read(new File(filename));
        } catch (Exception e) { //IOExcecption
          // the game will still kinda work, you just won't see the images.
          e.printStackTrace();
        return null;
      public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(
          new Runnable() {
            public void run() {
              MineSweeperGame game = new MineSweeperGame();
    CustomSettingsDialog.java
    package krc.games.sweeper;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class CustomSettingsDialog extends JDialog implements ActionListener
      private static final long serialVersionUID = 0L;
      private static final int ROW_HEIGHT = 24;
      private static final int PAD = 5;
      private boolean isOk = false;
      GameSettings settings;
      private JPanel panel;
      private JTextField rowsTextField;
      private JTextField colsTextField;
      private JTextField bombsTextField;
      private JButton okButton;
      private JButton cancelButton;
      CustomSettingsDialog(JFrame parentFrame, GameSettings settings) {
        super(parentFrame, true);
        this.settings = settings;
        this.setTitle("Custom Miner");
        this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        this.setSize(250, 200);
        this.setResizable(false);
        panel = new JPanel();
        panel.setLayout(null);
        addLabel(0, "rows"); rowsTextField = addField(0, ""+settings.rows);
        addLabel(1, "cols"); colsTextField = addField(1, ""+settings.cols);
        addLabel(2, "bombs"); bombsTextField = addField(2, ""+settings.bombs);
        okButton = addButton(3,0, "Ok");
        cancelButton = addButton(3,1, "Cancel");
        rowsTextField.selectAll();
        rowsTextField.requestFocusInWindow();
        this.add(panel);
        this.setVisible(true);
      boolean isOk() {
        return this.isOk;
      GameSettings getSettings() {
        return this.settings;
      private void addLabel(int row, String caption) {
        JLabel label = new JLabel(caption);
        label.setBounds(PAD, PAD+((ROW_HEIGHT+PAD)*row), 80, ROW_HEIGHT);
        panel.add(label);
      private JTextField addField(int row, String text) {
        JTextField field = new JTextField();
        field.setBounds(80, PAD+((ROW_HEIGHT+PAD)*row), 100, ROW_HEIGHT);
        field.setText(text);
        panel.add(field);
        return(field);
      private JButton addButton(int row, int col, String caption) {
        JButton button = new JButton(caption);
        button.setBounds(20+(col*85), PAD+((ROW_HEIGHT+PAD)*row), 80, ROW_HEIGHT);
        button.addActionListener(this);
        panel.add(button);
        return(button);
      public void actionPerformed(ActionEvent event) {
        if ( okButton == event.getSource() ) {
          try {
            this.settings.level = "custom";
            this.settings.rows = Integer.parseInt(rowsTextField.getText());
            this.settings.cols = Integer.parseInt(colsTextField.getText());
            this.settings.bombs = Integer.parseInt(bombsTextField.getText());
            this.isOk = true;
            this.setVisible(false);
          } catch(NumberFormatException e) {
            JOptionPane.showMessageDialog(this, e.getMessage(), "NumberFormatException", JOptionPane.ERROR_MESSAGE);
        } else if ( cancelButton == event.getSource() ) {
          this.isOk = false;
          this.setVisible(false);
        } else {
          java.awt.Toolkit.getDefaultToolkit().beep();
          System.out.println("CustomSettingsDialog.actionPerformed: Unknown event source "+event.getSource());
    GameProperties.java
    package krc.games.sweeper;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    class GameProperties extends java.util.Properties
      private static final long serialVersionUID = 0L;
      private static final String FILENAME = "MineSweeperGame.properties";
      public GameProperties() {
        super();
        load();
      public GameSettings get(String level) {
        return new GameSettings(
            level
          , getInt(level+"_rows")
          , getInt(level+"_cols")
          , getInt(level+"_bombs")
      public GameSettings get() {
        return get(getProperty("level"));
      public void set(GameSettings settings) {
        setProperty("level", settings.level);
        setProperty(settings.level+"_rows", ""+settings.rows);
        setProperty(settings.level+"_cols", ""+settings.cols);
        setProperty(settings.level+"_bombs", ""+settings.bombs);
      public void load() {
        try {
          load(new FileReader(FILENAME));
        } catch (Exception e) {
          System.err.println("Failed to load properties from "+FILENAME+" - "+e);
          e.printStackTrace();
      public void save() {
        try {
          store(new FileWriter(FILENAME), FILENAME);
        } catch (Exception e) {
          System.err.println("Failed to save properties to "+FILENAME+" - "+e);
          e.printStackTrace();
      private int getInt(String key) {
        try {
          return Integer.parseInt(getProperty(key));
        } catch (Exception e) {
          e.printStackTrace();
          throw new RuntimeException("Failed to getPropertyAsInt("+key+") from "+FILENAME+" - "+e);
    GameSettings.java
    package krc.games.sweeper;
    class GameSettings
      public String level;
      public int rows;
      public int cols;
      public int bombs;
      GameSettings(String level, int rows, int cols, int bombs) {
        this.level = level;
        this.rows = rows;
        this.cols = cols;
        this.bombs = bombs;
    GameClock.java
    package krc.games.sweeper;
    import javax.swing.JLabel;
    import javax.swing.border.LineBorder;
    import java.awt.Color;
    class GameClock extends JLabel
      private static final long serialVersionUID = 0L;
      private volatile boolean isRunning = false;
      private volatile int elapsedTime;
      public GameClock() {
        super("0");
        elapsedTime = 0;
        this.setBorder(new LineBorder(Color.black));
      public void start() {
        if(isRunning) return;
        isRunning = true;
        new Thread() {
          public void run() {
            while (isRunning) {
              setText(""+(elapsedTime++));
              try{Thread.sleep(1000);}catch(InterruptedException eaten){}
        }.start();
      public void stop() {
        this.isRunning = false;
      public void skip(int seconds) {
        elapsedTime+=seconds;
      public void reset() {
        elapsedTime = 0;
        super.setText("0");
    MineSweeperGame.properties
    #MineSweeperGame.properties
    #Sat Dec 29 18:56:47 GMT+10:00 2007
    level=expert
    beginner_rows=9
    beginner_cols=9
    beginner_bombs=10
    intermediate_rows=16
    intermediate_cols=16
    intermediate_bombs=40
    expert_rows=16
    expert_cols=30
    expert_bombs=99
    custom_rows=30
    custom_cols=50
    custom_bombs=299-----
    BTW... I gave up on the whole refactor thing... I just couldn't work out how to cleanly separate the view from the model... and my design was getting mighty complicated.... bigger than ben hurr... So I decided to revert to the "hack" version, and do a little refactoring to try to split out the more-easily-split-out sections, and tada - I (mostly) got through the TODO list.
    Also... can anyone point me at a good serialization tutorial... sun's is a bit how's your dad.
    Thanx all.

  • MouseEvents are not triggered for JMenu

    I would like to listen for MouseEvents but i'm not sure if it is a bug in java or some lack of knowledge on my side concerning event handling.
    I have a simple menu with one mouse listener and seems that mouseReleased and mouseClicked events are not triggered always as i would expect.
    if i run the code that has been attached below, than i have the following strange scenarios.
    Menu0 is not opened and click on it once:
    pressed Menu0
    clicked Menu0
    There is no mouseReleased received. why?
    Menu0 is opened and click on it once again:
    pressed Menu0
    released Menu0
    clicked Menu0
    Menu0 is collapsed and i have all the events. ok
    Menu0 is opened and click on Menu1:
    pressed Menu1
    released Menu1
    Menu0 is collapsed and there is no mouseClicked event. why?
    Menu0 is opened and go over Menu2 and click on it:
    pressed Menu2
    clicked Menu2
    There is no mouseReleased event. why?
    Press the mouse over Menu2 and release it over Menu3:
    pressed Menu2
    released Menu2
    why is it 'released Menu2' and not 'released Menu3' if it is pressed and released Menu2 than where is the clicked event anyway.
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    public class MouseEventTest
         public static void main( String[] args )
              JFrame frame;
              JMenuBar menuBar;
              JMenu menu, subMenu;
              JMenuItem menuItem;
              MouseListener mouseListener;
              mouseListener = new MouseAdapter() {
                   public void mouseEntered( MouseEvent e )
                   public void mouseExited( MouseEvent e )
                   public void mouseClicked( MouseEvent e )
                        System.err.println( "clicked " + ((JMenuItem) e.getSource()).getText());
                   public void mousePressed( MouseEvent e )
                        System.err.println( "pressed " + ((JMenuItem) e.getSource()).getText());
                   public void mouseReleased( MouseEvent e )
                        System.err.println("released " + ((JMenuItem) e.getSource()).getText());
              menuBar = new JMenuBar();
              menu = new JMenu( "Menu0" );
              menu.addMouseListener( mouseListener );
              menuBar.add( menu );
              menuItem = new JMenuItem( "Menu1" );
              menuItem.addMouseListener( mouseListener );
              menu.add( menuItem );
              subMenu = new JMenu( "Menu2" );
              subMenu.addMouseListener( mouseListener );
              menu.add( subMenu );
              menuItem = new JMenuItem( "Menu3" );
              menuItem.addMouseListener( mouseListener );
              subMenu.add( menuItem );
              menuItem = new JMenuItem( "Menu4" );
              menuItem.addMouseListener( mouseListener );               
              subMenu.add( menuItem );
              frame = new JFrame();
              frame.setTitle( "MouseEvent test for JMenu" );
              frame.setBounds( 320, 240, 320, 240 );
              frame.setJMenuBar( menuBar );
              frame.addWindowListener( new WindowAdapter() {
                   public void windowClosing( WindowEvent e ) {
                        System.exit(0);
              frame.setVisible( true );
    }

    Well there are differences across Operating Systems. For example I'm using JDK1.4.2 on XP. When I click on Menu0 I get:
    pressed Menu0
    released Menu0
    clicked Menu0
    It is always better to use a "higher" level event when possible. In this case you should be using an ActionListener, if you want to know when a menu or menuItem is clicked. Or maybe you could use a MenuListener to know when a menu is opened and closed.

  • JMenu - actionListeners

    I have a file formatted like this:
    Google search----www.google.com
    Yahoo!----yahoo.com
    MSN----www.msn.comI'm trying to read file so that each line would be made into a seperate JMenu.
    The string before "---" is jMenuItem's title.
    The string after "---" is an address of that item.
    here is my code:
    while ((strLine = br.readLine()) != null){
    String[] temp = strLine.split("-------");
    JMenuItem mnuItem = new JMenuItem(temp[0]);
    mnuItem.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent evt){
                      goTo(temp[1]); 
                      // local variable temp is accessed from within inner class
                      // needs to be declared final
    }what would be a better way of doing this?

    Athlon1600 wrote:
    in my actual code String[] is outside the loop to keep the garbage low.
    With the String[] inside the loop would work, but i better stick with that setActionCommand suggestions.
    Thank you for helpYou're welcome, but actually if you use actionCommand, then you will not be creating the actionlistener from within the loop and the final business is not necessary, is moot. For instance, my SSCCE:
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Scanner;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    public class TestMenuListeners
      private static final String MENU_DATA_PATH = "MenuListenersData.txt";
      private static final Dimension MAIN_SIZE = new Dimension(500, 300);
      private static final String MENU_TITLE = "Menu";
      private JPanel mainPanel = new JPanel();
      public TestMenuListeners(JFrame frame)
        mainPanel.setPreferredSize(MAIN_SIZE);
        JMenu menu = createMenu();
        JMenuBar menuBar = new JMenuBar();
        menuBar.add(menu);
        frame.setJMenuBar(menuBar);
      private JMenu createMenu()
        Scanner scanner = new Scanner(getClass().getResourceAsStream(MENU_DATA_PATH));
        MenuListener listener = new MenuListener();
        JMenu menu = new JMenu(MENU_TITLE);
        while (scanner.hasNextLine())
          String strLine = scanner.nextLine();
          if (strLine != null && !strLine.isEmpty())
            final String[] temp = strLine.split("----");
            JMenuItem menuItem = new JMenuItem(temp[0].trim());
            menuItem.setActionCommand(temp[1].trim());
            menuItem.addActionListener(listener);
            menu.add(menuItem);
        scanner.close();
        return menu;
      public JComponent getComponent()
        return mainPanel;
      private class MenuListener implements ActionListener
        public void actionPerformed(ActionEvent e)
          System.out.println("Going to site: " + e.getActionCommand());
      private static void createAndShowUI()
        JFrame frame = new JFrame("Menu Listeners");
        frame.getContentPane().add(new TestMenuListeners(frame).getComponent());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main(String[] args)
        java.awt.EventQueue.invokeLater(new Runnable()
          public void run()
            createAndShowUI();
    }This assumes a file called MenuListenersData.txt that is in the same location as this class.

  • Swing setRolloverIcon/setWhateverIcon not working

    I've got a test program here to see if various Icon states actually work in Swing.
    Under windows, the only icon state that seems to work is setIcon()...
    Anyone know what I am doing wrong?
    Here is the code:
    package unittest;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JMenuBar;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.ImageIcon;
    public class MenuTest2
         extends JFrame
         public MenuTest2 () {
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                   System.exit(0);
              JMenuBar menuBar = new JMenuBar();
              JMenu menu = new JMenu("A Menu");
              menuBar.add(menu);
              JMenuItem menuItem = new JMenuItem("A text-only menu item");
              menuItem.setIcon(new ImageIcon("test.gif"));
              menuItem.setRolloverIcon(new ImageIcon("test1.gif"));
              menuItem.setPressedIcon(new ImageIcon("test1.gif"));
              menu.add(menuItem);
              setJMenuBar(menuBar);
         public static void main(String[] args) {
    MenuTest2 window = new MenuTest2();
    window.setTitle("MenuTest");
         window.setSize(300, 200);
              window.setVisible(true);
    }

    cont = new JButton(new ImageIcon("normal.gif"));
    cont.setPressedIcon(new ImageIcon("pressed.gif"));
    cont.setRolloverIcon(new ImageIcon("roll.gif"));
    cont.setFocusPainted(false);
    cont.setBorderPainted(false);
    cont.setContentAreaFilled(false);
    cont.setMargin(new Insets(0,0,0,0));
    this works
    guaranteed :)

  • JMenu closes after checking/unchecking JCheckBoxMenuItems

    I added a JMenu to an existing JPopupMenu, and added a few JCheckBoxMenuItems, followed by a JButton to the JMenu. Currently, when I open the JMenu and check/uncheck a JCheckBoxMenuItem, the JMenu closes.
    So, my question is, how do I get the JPopupMenu, JMenu and all the JCheckBoxMenuItems to stay open while I click multiple JCheckBoxMenuItems? I basically want everything to stay open until I push the JButton. I believe this is possible, but I don't know how to go about it. And I need help ASAP. Thanks!

    Hi, yes actually it is urgent. I'm doing this for work and it took me two days becuz it was the weekend and I didn't have access to code.
    Anyways, I just created this SSCCE, as you had advised. As far as instructions are concerned, after launching the application, you need to right click on the JFrame and go from there. You will see that after selecting/unselecting one of the JCheckBoxMenuItems it goes behind the frame. I'm sorry if my instructions are confusing, all you need to do is right-click on the frame and you'll see what I'm talking about.
    import java.awt.Point;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JButton;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JPopupMenu;
    import javax.swing.SwingUtilities;
    public class MyPopupTest {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              final JFrame frame = new JFrame("My Frame");
              frame.setSize(500,500);
              final JPopupMenu mainPopup = new JPopupMenu();
              final JMenu myMenu = new JMenu("My Menu");
              final JPopupMenu itemsPopupMenu = new JPopupMenu();
              JButton okButton = new JButton("OK");
              JCheckBoxMenuItem item1 = new JCheckBoxMenuItem("item1", true);
              JCheckBoxMenuItem item2 = new JCheckBoxMenuItem("item2", false);
              JCheckBoxMenuItem item3 = new JCheckBoxMenuItem("item3", false);
              frame.getContentPane().add(mainPopup);
              mainPopup.add(myMenu);
              myMenu.add(itemsPopupMenu);
              itemsPopupMenu.add(item1);
              itemsPopupMenu.add(item2);
              itemsPopupMenu.add(item3);
              itemsPopupMenu.add(okButton);
              okButton.addMouseListener(new MouseAdapter()
                   public void mousePressed(MouseEvent e)
                        itemsPopupMenu.setVisible(false);
                        myMenu.setVisible(false);
              myMenu.addMouseListener(new MouseAdapter()
                   public void mouseClicked(MouseEvent e)
                        if(SwingUtilities.isRightMouseButton(e))
                             mainPopup.setLocation(e.getPoint());
                             mainPopup.setVisible(true);
                   public void mouseEntered(MouseEvent e)
                        itemsPopupMenu.setLocation(new Point(myMenu.getLocationOnScreen().x + mainPopup.getWidth(),myMenu.getLocationOnScreen().y));
                        itemsPopupMenu.setVisible(true);
              frame.setVisible(true);  
    }

  • JMenu & ImageIcon, Please Help me !!

    There is a jframe with a jmenubar.
    there is a jmenu in that jmenubar.
    I have created a imageicon from an image.
    I have written.
    JMenu.setIcon (new ImageIcon (String fileName));
    But this icon isn't covering the whole menu. When i click on menu then some back screen visible near its boundary..
    I want to fix this icon over full jmenu.
    how can i do so.. pls help me .. it is very urgent...

    NOOOOOOOOOOOOOOOOOOOOOOOOOO..
    It is not working.... sir........
    I am frustrated with this........
    i have written........
    * AAA.java
    * Created on April 15, 2003, 1:53 PM
    * @author Administrator
    public class AAA extends javax.swing.JFrame
    /** Creates new form AAA */
    public AAA ()
    initComponents ();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents()
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    addWindowListener(new java.awt.event.WindowAdapter()
    public void windowClosing(java.awt.event.WindowEvent evt)
    exitForm(evt);
    jMenu1.setBorder(null);
    jMenu1.setIcon(new javax.swing.ImageIcon("C:\\Documents and Settings\\Administrator\\Desktop\\accept.gif"));
    jMenu1.setMargin(new java.awt.Insets(0, 0, 0, 0));
    jMenuBar1.add(jMenu1);
    setJMenuBar(jMenuBar1);
    pack();
    java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    setSize(new java.awt.Dimension(400, 300));
    setLocation((screenSize.width-400)/2,(screenSize.height-300)/2);
    /** Exit the Application */
    private void exitForm (java.awt.event.WindowEvent evt)
    System.exit (0);
    * @param args the command line arguments
    public static void main (String args[])
    new AAA ().show ();
    // Variables declaration - do not modify
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    // End of variables declaration
    BUT it doesn't work.. still the icon is not covering the full jMenu... we i click on JMenu .. the boundry is seen with different color.
    It looks so bad.. Pls tell me how to do it....
    However thanks for it..
    waiting..
    "anjeev Dhiman"

Maybe you are looking for

  • Pages can´t open files saved in iCloud

    I can´t open any file save to iCloud I tried a workaraound: I couldn´t open a file save to iCloud from my iPad. I opened it from icloud.com and downloaded it to my iMac. Opened the downloaded file, and everything semed ok. I then closed the dokument

  • Whats happened to output in Bridge CC??

    Please tell me that the only way to make a pdf is not via the god awful contact sheet II tool as its slow and much more limited ... its just taken me 20 mins to do something I usually do in 1!! not very happy at the moment as I removed bridge cs6 fro

  • RH9 Search highlighting color won't stick

    When you use the Search feature and select "Highlight search results" the default color is gray. The word or phrase you're searching for displays in gray in all the topics in your search results. From a usability standpoint, gray is a really bad colo

  • Adding Count and Max

    I am attempting to query a little Oracle table. I want to get all checks that have a (maximum line number + total discount lines > 0) > 10 In the table there are these fields: discount amount, line number, check number, system date. So say there are

  • Activating and Deactivating

    I had Activated my photoshop twice on other computers before and wanted it on my new computer so I uninstalled it off of one of my old computers without realising that there was a deactivate option. Now I can't install it on my new computer and I don