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;

Similar Messages

  • How sholud we call one jframe class from another jframe class

    Hi
    In my application i am calling one jframe class from another jframe clas.
    how sholud we make previous jframe inactve when another jframe is invoked?(user sholud not able to make any changes on on parent jframe window when another jframe is invoked)
    Pls reply.

    Sorry for me it is not possible to change existing code,
    pls suggest me any other solution so that i can inactive parent jframe when child jframe execution is going on.

  • Is there any way to know how much time swing client is on open state?

    Is there any way to know how much time swing client is on open state? My requirement is to show a message some time after the swing client open i.e., 4-5 hours.

    You could also consider using javax.swing.Timer and java.awt.event.ActionListener (or javax.swing.Action) which takes care of running the actionPerformed code on the EDT.
    db

  • JFrame as child of JFrame

    Hi,
    I need to have legacy JFrame's inside other JFrame's. I'm having some problems with the focus though. For example, I can't scroll a table with the mouse midle button, I can't open context menus and there are some other events that seem to be consumed by the parent frame.
    Can you give me advice on how to workaround this?
    Thanks

    Ok, I had to dispacth the events to the right component, by making the translation of the point coordinates.
    Thanks

  • Some times Safari crashes and quits the first time I click a link

    Hello there
    As the title says, some times Safari crashes and quits the first time I click a link on a webpage (after opening one or more bookmarks). Upon reopening Safari, everything is fine.
    Is there a fix?

    Uninstall Rapport

  • Compressor eating CPU time...after quitting

    I've been running Compressor lately for some DVD projects. I set up a batch to encode, but quit after about half the video files were encoded to work on some other things. Performance was pretty darn sluggish. I checked Activity Monitor, and lo and behold, compressord and qmasterd were still running and gobbling up CPU time. I force quit both of them, only to see them crop up again a few seconds later. WHAT? A force quit should absolutely terminate the process, no questions asked. I don't want Compressor running in the background, which is why I quit it and Batch Monitor in the first place. This is not a feature, this is a problem, and an inexcusable one at that. Anyone know how to get rid of this crap without a restart?
    In addition, Compressor will not let any part of my computer sleep while running. The display on my iMac wont even dim, much go into standby. I can understand why it wouldn't let the computer or hard drive sleep, but the display? Come on! I sleep in the same room as this computer, so it's kind of an annoyance when I want to encode a batch overnight.

    Heya Noble,
    Basically, your computer's still compressing.
    Compressor is the application that allows you to prepare your transcoding and/or encoding.
    Once you "submit" the process, Compressor is done.
    Qmaster takes over to transcode or encode the file as submitted by Compressor.
    Batch Monitor merely allows you to view what's happening until Qmaster is done.
    If you force quit Qmaster, then you'll never have a transcoded movie or encoded MPEG2 clip.
    Your machine will probably compress 10 minutes of DV-NTSC source to the MPEG2 60 minute high quality setting in about 7 to 8 minutes. So, if you were encoding an hour of footage, you would have to allow Qmaster about 48 minutes to work. HDV source takes much, much longer. If this seems like "forever", then consider this: a G4/400 takes four hours to encode 10 minutes of DV-NTSC source to MPEG2. At that rate, an hour of footage would take a full day to encode.
    Most importantly, these numbers are based on not using the computer for anything while it's transcoding and/or encoding. Even surfing the web will increase the time it takes to process the file or files that you've submitted.
    If you are frequently submitting jobs to Qmaster, then you might consider getting a second computer so that you can work on one system while the other one encodes. It's not uncommon to have a dedicated box just for encoding. In general, the faster the processor(s), the faster the render.
    If you are submitting jobs that are hours in length, then you might look into distributed network encoding that's now available with Compressor (more processors = more speed).
    If your budget doesn't allow for another machine, you'll want to plan for using your computer at a "lesser" performance level or not using it at all until the job is completed.
    You should be able to put the display to sleep, but not the computer nor the hard drive.
    If you're having trouble with this, perhaps a piece of cardboard set in front of the display may block enough light such that you can sleep. You could also cover the computer with a box, just be sure to provide adequate ventilation. Be careful not to cover the computer with a blanket as it's sure to overheat and you won't be running Compressor at all.
    Of course, if you don't want to put anything in front of the computer: launch Final Cut Pro, make the Viewer window active while a Slug is open, choose View > Digital Cinema Desktop Preview - Main. Then press command F12 to enable it. Your screen will go entirely black! Press escape to return to disable it. Leave iTunes open while playing some soft tunes and you should be counting sheep in no time.
    Hope this helps,
    Warren
      Mac OS X (10.3.9)  

  • My macbook pro will not shut down. It tells me that safari has cancelled shut down and to quit safari and try again, but every time I try to quit safari it won't let me. I need help...I don't know what to do.

    My macbook pro will not shut down. It tells me that safari has cancelled shut down and to quit safari and try again, but every time I try to quit safari it won't let me. I need help...I don't know what to do.

    Have you tried holding the power button down for several seconds? I would try the force quit as mentioned earlier first, or go to the Activity Monitor in Applications>Utilities and try force quit there.

  • My mail won't close no matter how many times I try to quit it. It just makes that noise that signifies NOPE, my mail won't close no matter how many times I try to quit it. It just makes that noise that signifies NOPE

    hey guys I think a trojan was somehow let loose on my computer... And I think it's living in my email because no matter how many times I try to quit Mail, it won't quit. How do I kill this trojan?

    Linc Davis has indicated how to Force Quit out of any application that is frozen.
    For your Mail issue, try the following:
    - Go to Software Update to apply the new update for Mail. Not sure, but there may be bug fixes in the  new version.
    - Go to Disk Utility (In Applications, Utilities) and run a Permissions Repair. Then do a restart of your computer.

  • Quick Time 7.0 Pro (7.7.3) on Win 7 Home Prem 64-bit, Pro paid for, valid registration code, Open Image Sequence (and resulting time-lapse movies) has quit working after several successful operations.  What do?  How fix? Thanks.

    Quick Time 7.0 Pro (7.7.3) on Win 7 Home Prem 64-bit, Pro paid for, valid registration code, Open Image Sequence (and resulting time-lapse movies) has quit working after several successful operations.  What do?  How fix? Thanks.

    This tip is ready for submission.
    It REPLACES the prior version in the Time Machine forum, at: http://discussions.apple.com/thread.jspa?threadID=2057525
    Additions/wording changes to items C3, C4, C5, D4
    New topics C9, C10, C11, and E4

  • JMenu/JFrame issue

    Ok, I can't figure out how to make an option in a menu popup a new JFrame instead of displaying some stupid text in a text box.
    menuItem2 = new JMenuItem("Inventory");
              menuItem2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.ALT_MASK));
              menuItem2.getAccessibleContext().setAccessibleDescription("This does nothing for now");
              menu.add(menuItem2);That's just a tiny part...I need it to open the JFrame Inven if anybody knows how to do that.

    (post #2 - another disappeared into the ether)
    is this what you're trying to do?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Testing extends JFrame
      public Testing()
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocation(400,200);
        setSize(300,200);
        JMenu menu = new JMenu("Window");
        JMenuItem menuItem1 = new JMenuItem("Employees");
        JMenuItem menuItem2 = new JMenuItem("Inventory");
        menu.add(menuItem1);
        menu.add(menuItem2);
        JMenuBar menuBar = new JMenuBar();
        menuBar.add(menu);
        setJMenuBar(menuBar);
        getContentPane().add(new JTextArea(5,20));
        menuItem1.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            JFrame frame = new JFrame("Employee Frame");
            frame.setSize(200,100);
            frame.setLocation(100,500);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setVisible(true);}});
        menuItem2.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            JFrame frame = new JFrame("Inventory Frame");
            frame.setSize(200,100);
            frame.setLocation(500,500);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setVisible(true);}});
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • How to kill the hanged JFrame in swing?

    How to kill the hanged frame in swing?
    I am opening multiple JFrame and working on them.These frames are plcaed in JDesktopPane.
    If one frame is hanged up then i could not work on others .
    I need to kill the hanged frame.
    Assist me.

    am opening multiple JFrame and working on them.These frames are plcaed in JDesktopPaneWell, a JFrame, can't be added to a JDesktopPane, so your question doesn't even make sense.
    As was suggested earlier, if your GUI is unresponsive, then that means you are blocking the GUI EDT and the GUI can't respond to events. Don't do this.
    Read the Swing tutorial on Concurrency to understand why this happens and to learn the proper way to write GUI code so it won't happen.

  • HelloWorld Swing Error -JFrame

    Not sure why this happened. I've made no change to my computer, yet today I am unable to
    compile the following code, when I was able to do it the day before. For some rease JFrame is
    not understood:
    My Code:
    import javax.swing.*;
    import java.awt.*;
    public class HelloWorld extends JApplet {
    SwingHelloWorldPanel m_Panel;
    Create the panel and pass init to it
    public void init() {
    m_Panel = new SwingHelloWorldPanel();
    // NOTE the call to getContentPane - this is important
    getContentPane().add("Center", m_Panel);
    m_Panel.init();
    public void start() {
    m_Panel.start();
    Inner class representing a panel which does all the work
    static class SwingHelloWorldPanel extends JPanel {
    public void paint(Graphics g) {
    super.paint(g);
    Dimension size = getSize();
    g.setColor(Color.lightGray);
    g.fillRect(0,0,size.width,size.height);
    g.setColor(Color.red);
    g.drawString("Hello World",50,50);
    // Override to do more interesting work
    public void init() {
    public void start() { }
    // end inner class SwingHelloWorldPanel
    Standard main for Applet/Application projects
    Note that an inner class is created to to the
    real work. The use of a light weight inner class
    prevents inclusion of a heavyweight JApplet inside
    a heavyweight container
    public static void main(String args[]) {
         JFrame f = new JFrame("SwingHelloWorld");
         // Create the panel and pass init and start to it
         SwingHelloWorldPanel     hello = new SwingHelloWorldPanel();
    // NOTE the call to getContentPane - this is important
         f.getContentPane().add(hello);
         hello.init();
         hello.start();
         f.setSize(300, 300);
         f.show();
    The error:
    C:\java_dev>javac HelloWorld.java
    HelloWorld.java:71: cannot resolve symbol
    symbol : constructor JFrame (java.lang.String)
    location: class JFrame
    JFrame f = new JFrame("SwingHelloWorld");
    ^
    1 error
    Thanks in advance

    EXIT_ON_CLOSE has been in the API since v 1.3. Are you using an earlier version?

  • Undecorated JFrame in Swing editor

    I am creating an application which doesn't require window decorations and I use the appropriate call in the JFrame class to turn them off. The problem is that the swing editor in JDeveloper always has the decorations present so it's hard to get the placement of object and the sizing of the JFrame correct. Is there a setting in JDeveloper to modify this behaviour? As an aside there isn't a property to set or clear the decorations in the properties pane either.
    Any help would be most appreciated.

    dialog works pretty well
    here's a more complete example
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class Logon {
       public static void main(String[] a){
          JFrame f = new JFrame();
          f.setSize(400,400);
          f.show();
          LogonDial ld = new LogonDial(f,true);
          ld.setLocationRelativeTo(null);
          ld.show();
          if(ld.isAccept()){
             JOptionPane.showMessageDialog(null,"you are now logged on");
          else
             JOptionPane.showMessageDialog(null,"logon failed");
          ld.dispose();
          f.dispose();
          System.exit(0);
    import javax.swing.*;
    import java.awt.event.*;
    public class LogonDial extends JDialog{
       private boolean accept = false;
       private JButton logonButton;
       public LogonDial(JFrame f, boolean modal){
          super(f,modal);
          init();
       private void init(){
          setSize(200,200);
          logonButton = new JButton("logon");
          logonButton.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent ae){
                   //if logon is correct
                   accept = true;
                   hide();
          getContentPane().add(logonButton);
          addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent we){
                   accept = false;
                   hide();
       public boolean isAccept(){
          return accept;
    }you should run it and see if it works for you.

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

  • Closing One JFrame instead of All JFrames?

    Hello everyone,
    I am developing a program using Sun's Forte community edition V3.0, this is for an assignment and I have chosen Java and Swing instead of the Recommended MS Access. Grin (You got to love a challenge.)
    I have a menu class that allows users to create instances of other classes by clicking various buttons representing options.
    When the user clicks a button a new class instance is created allowing the user to interact with the system.
    //-- Action in response to a buton click. This calls an instance of a working
    //-- class.
    private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {
            final JFrame fs = new SRemClassEntryFr();
            fs.setBounds(150, 150, 530, 398);
            fs.setVisible(true);
            fs.setTitle("SRemClassEntry");
            fs.setDefaultCloseOperation(HIDE_ON_CLOSE);
            fs.getContentPane().setBackground(java.awt.Color.cyan);
            fs.addWindowListener(new WindowAdapter(){
                public void windowClosed(WindowEvent e){
                    System.exit(0);
    //-- The starting class of the application. A simple class that calls other
    //-- classes based on users selecting menu items represented as buttons
    public static void main(String args[]) {
            //-- new AdminMainMenuFr().show();
            final JFrame f = new AdminMainMenuFr();
            //f.setContentPane(f.getContentPane());
            f.setBounds(150, 150, 620, 560);
            f.setVisible(true);
            f.setTitle("Admininistrator Main Menu");
            f.getContentPane().setBackground(java.awt.Color.cyan);
            f.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            f.addWindowListener(new WindowAdapter(){
                public void windowClosed(WindowEvent e){
                    System.exit(0);
        }My application is behaving itself as intended, it does have a major problem and that is...
    On selecting an operation from the Administrator menu, I am able to use and interact with that specified object instance. Unfortunately when I close the open object, it not only closes the said object but the underlying Administrator menu object also.
    Does anyone have any ideas on how I should be doing this?
    Thanks in advance
    Mark.

    fs.setTitle("SRemClassEntry");
    fs.setDefaultCloseOperation(HIDE_ON_CLOSE);
    fs.getContentPane().setBackground(java.awt.Color.cyan);
    fs.addWindowListener(new WindowAdapter(){ 
    public void windowClosed(WindowEvent e){
    System.exit(0); /// here is the problem
    });you say when the SRemClassEntry is closed, "exit the program" , (System.exit(0);)
    hope that helps

Maybe you are looking for