Jmenu bar

I have created a jmenu bar but ho do i get the drop down list to select element is it done in the sae way as a normal list.
private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

Shall i post this in a different forum

Similar Messages

  • Dynamic jmenu bar

    i have a dynamic JMenu on a jframe. The menu is populated by looking up database entries and ptting them into the right place. This is done by a method 'menus()'.
    I also have an addingredients class which adds new ingredient entries into the database, problem is when it does this, the JMenu has to be repopulated. The following code shows the main frame
    // Recipe Creation GUI
    // Written by Michael Emett
    // Monday 15th Decemeber 2003
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JFrame.*;
    import java.sql.*;
    import java.util.*;
    public class TextAreaDemo extends JFrame     {
    private static JTextArea part1;
    private JButton Browse, Enter, Preview, Remove;
    public static JList printList, newList;
    private JCheckBox pic;
    private JLabel namePrompt, title1, title2, title3;
    private static JTextField nameInput;
    private JPanel jp, jp1, jp2, jp3, jp4, jp5;
    private Connection con;
    private Statement stmt;
    public static JMenu fileMenu;
    private static JMenuBar bar;
    // additions /////////////////////////////////////////////////////////////////////////
    //set up GUI
    public TextAreaDemo()     {
    super( "Recipe Entry Sheet" );
    // set up File menu and its menu items
    // Menu and button Initialization ////////////////////////////////////////////////////
    //myMouse = new MyMouseAdapter();
    //final JMenu
    fileMenu = new JMenu( "Ingredients");
             fileMenu.setMnemonic( 'I' );
    fileMenu.add(menus());
    bar = new JMenuBar();
    setJMenuBar( bar );
    JMenu file = new JMenu( "File");
    file.setMnemonic( 'F' );
        bar.add(file);
              JMenuItem Adder = new JMenuItem( "New Ingredient");
             Adder.setMnemonic( 'N' );
    JMenuItem Subber = new JMenuItem( "New subMenu");
             Subber.setMnemonic( 'S' );
             // set up About... menu item
             JMenuItem aboutItem = new JMenuItem( "About..." );
             aboutItem.setMnemonic( 'A' );
    namePrompt = new JLabel( "Recipe Name " );
    nameInput = new JTextField( 20 );
    title1 = new JLabel( "Selected ingredients" );
    title3 = new JLabel( "Please enter the Recipe Instructions" );
    title2 = new JLabel( "Enter The SubMenu Name " );
    pic = new JCheckBox("Add Picture", false);
    file.add( Adder );
         Adder.addActionListener(
              new ActionListener()     {
                    public void actionPerformed( ActionEvent event )
                        getList f = new getList();
    // Add Ingredient menu item //////////////////////////////////////////////////////////
    file.add( Subber );
         Subber.addActionListener(
              new ActionListener()     {
                    public void actionPerformed( ActionEvent event )
                        AddSubMenu f = new AddSubMenu();
    // About menu item ///////////////////////////////////////////////////////////////////
    file.add( aboutItem );
          aboutItem.addActionListener(
             new ActionListener() {  // anonymous inner class
                // display message dialog when user selects About...
                public void actionPerformed( ActionEvent event )
                   JOptionPane.showMessageDialog( TextAreaDemo.this,
                      "Developed by Michael Emett, 2004",
                      "About", JOptionPane.PLAIN_MESSAGE );
              }     // end anonymous inner class
         );  // end call to addActionListener
    // Exit menu item ////////////////////////////////////////////////////////////////////
         JMenuItem exitItem = new JMenuItem( "Exit" );
         exitItem.setMnemonic( 'x' );
         file.add( exitItem );
          exitItem.addActionListener(
             new ActionListener() {  // anonymous inner class
                // terminate application when user clicks exitItem
                public void actionPerformed( ActionEvent event )
                   System.exit( 0 );
             }  // end anonymous inner class
          ); // end call to addActionListener
    //create Button Enter
    Enter = new JButton("Enter");
    Enter.addActionListener(
              new ActionListener()     {
                              public void actionPerformed( ActionEvent event )
                        StringBuffer a = new StringBuffer();
                        StringBuffer b = new StringBuffer();
                        StringBuffer c = new StringBuffer();
                        for(int i= 0; i< victor.size(); i++){
                        b.append(victor.elementAt(i));
                        b.append("; ");
                        a.append(nameInput.getText());
                        c.append(part1.getText());
                        //System.out.println(a);
                        //System.out.println(b);
                        //System.out.println(c);
                        InsertRecipe f = new InsertRecipe(a,b,c);
                        //invalidate();
                //fileMenu.updateUI();
               // fileMenu.revalidate();
    //create Button Remove
    Remove = new JButton("Remove");
    //add Actionlistener
    Remove.addActionListener(
              new ActionListener()     {
                    public void actionPerformed( ActionEvent event )
    int[] arr;
    arr = printList.getSelectedIndices();
    int counter = 0;
         for (int i= 0; i< arr.length; i++){
              int n=arr;
              victor.remove(n-counter);
              counter++;
    printList.setListData(victor);
    //create Button Remove
    Browse = new JButton("Browse");
    //create Button Preview
    Preview = new JButton("Clear");
    Preview.addActionListener(
    new ActionListener() {  // anonymous inner class
    // display message dialog when user selects Preview...
    public void actionPerformed( ActionEvent event )
    int result = JOptionPane.showConfirmDialog
                             (null,      "Are you sure to want to clear this form", "Clear?",      JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
                             if(result == JOptionPane.YES_OPTION)
                             {TextAreaDemo.clear();
                                  //System.out.println("Recipe Entered");
              }//end of joptionpane
    printList = new JList();
    printList.setVisibleRowCount(9);
    printList.setFixedCellWidth(150);
    printList.setFixedCellHeight(15);
    printList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
    newList = new JList();
    newList.setVisibleRowCount(9);
    newList.setFixedCellWidth(150);
    newList.setFixedCellHeight(15);
    newList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION );
    // Initialise Text Areas //
    part1 = new JTextArea( 25, 50);
    part1.setFont(new Font("Courier", Font.BOLD, 12));
    part1.setLineWrap(true);
    part1.setWrapStyleWord(true);
    // JPanels for Layout //
    jp = new JPanel();
    jp1 = new JPanel();
    jp2 = new JPanel();
    jp3 = new JPanel();
    jp4 = new JPanel();
    jp5 = new JPanel();
    final Container c = getContentPane();
    GridBagLayout gbl = new GridBagLayout();
    GridBagConstraints gbc = new GridBagConstraints();
         c.setLayout(gbl);
         gbc.weightx = 0.1;
         gbc.weighty = 0.5;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.NORTHWEST;
    add(jp1, gbc, 0, 0, 1, 1);
    gbc.fill = GridBagConstraints.NONE;
    add(jp2, gbc, 0, 1, 1, 1);
    add(jp3, gbc, 1, 0, 2, 2);
    jp1.add(jp4, BorderLayout.CENTER);
    jp2.add(jp, BorderLayout.CENTER);
    bar.add( namePrompt );
    bar.add( nameInput);
    bar.add( fileMenu );
    jp4.setLayout(new BorderLayout());
    jp4.add(title1, BorderLayout.NORTH);
    jp4.add(new JScrollPane( printList), BorderLayout.CENTER);
    jp4.add(Remove, BorderLayout.SOUTH);
    jp.setLayout(new BorderLayout());
    jp.add(pic, BorderLayout.NORTH);
    jp.add(new JScrollPane (newList), BorderLayout.CENTER);
    jp.add(Browse, BorderLayout.SOUTH);
    jp3.setLayout(new BorderLayout());
    jp3.add (title3, BorderLayout.NORTH);
    jp3.add (new JScrollPane(part1), BorderLayout.CENTER);
    //c.addMouseListener(myMouse);
    gbc.anchor = GridBagConstraints.LAST_LINE_END;
    add(jp5, gbc, 2, 3, 1, 1);
    jp5.setLayout(new FlowLayout());
    jp5.add(Preview);
    jp5.add(Enter);
    setSize(770, 620);
         pack();
         setVisible(true);
         setResizable(false);
    private static Vector victor = new Vector();
    public static void printListset(String t) {
         victor.add(t);
    for(int i = 0; i<victor.size(); i++)
    printList.setListData(victor);
    public void add(Component ce, GridBagConstraints constraints, int x, int y, int w, int h) {
                   constraints.gridx = x;
                   constraints.gridy = y;
                   constraints.gridwidth = w;
                   constraints.gridheight = h;
                   getContentPane().add(ce, constraints);
    public static JMenu menus()     {
         // Map Created to Handle JMenuItem Addition //
              Map labelToMenu = new HashMap();
              Map labelToMenu2 = new HashMap();
              Map labelToMenu3 = new HashMap();
              String url = "jdbc:odbc:database";
              Connection con;
              Statement stmt;
                        try     {
                             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        catch(ClassNotFoundException e)     {
                        System.err.print("Class Not found");
                        String query = "select baseIngred.IngredientType, baseIngred.PrimaryKey FROM baseIngred";
                        String query2 = "select baseIngred.IngredientType, baseIngred.PrimaryKey,"
                        + "subMenu.menuNumber, subMenu.subMenu FROM baseIngred, "
                        + "subMenu WHERE baseIngred.PrimaryKey = subMenu.menuNumber ORDER BY submenu";
                                  String query3 = "select subMenu.subMenu, subMenu.PrimaryNumber,"
                                       + "Ingredient.Ingredient, Ingredient.MenuNumber FROM subMenu, Ingredient"
                        + " WHERE Ingredient.MenuNumber = subMenu.PrimaryNumber ORDER BY PrimaryNumber";
         String query4 = "select Ingredient.Ingredient, Ingredient.MenuNumber FROM Ingredient";
                             try     {
                                       con = DriverManager.getConnection(url, "myLogin", "myPassword");
                                       stmt = con.createStatement();
         // Initial Jmenu added ///////////////////////////////////////////////////////////////
                   ResultSet rs = stmt.executeQuery(query);
                   String[] arr = new String[100];
                   int[] num = new int[200];
                   int[] num2 = new int[200];
                   int counter = 0;
                   int counter2 = 0;
                   while     (rs.next())     {
                                  //String t is set to the value contained in ingredient type
                                  String t = rs.getString("IngredientType");
                                  //map labelToMenu has String t and a new JMenu with the menu
                                  //name contained in t stored in it
                                  labelToMenu.put(t, fileMenu.add(new JMenu(t)));
                                  //an array containing values of the priamry key is produced
                                  num[counter] = rs.getInt("PrimaryKey");
                                  //a counter is incremeted so that upon further
                                  //interations it is stored in a new array field
                                  counter++;
         // Second Jmenu added ////////////////////////////////////////////////////////////////
                   ResultSet rs2 = stmt.executeQuery(query2);
                   while     (rs2.next()) {
                                  //String first is set to the value contained in ingredient type
                                  String first = rs2.getString("IngredientType");
                                  //String second is set to the value contained in subMenu
                                  String second = rs2.getString("subMenu");
                                  //firstlevel looks up item t in the map, and creates a jmenu name as it.
                                  JMenu firstLevel = (JMenu)labelToMenu.get(first);
                                  //handles menu placement by comparing PrimaryKeys with MenuNumbers
                                  // f = rs2.getInt("menuNumber");
                                  num2[counter2] = rs2.getInt("menuNumber");
         for (int nm = 0; nm<num.length; nm++){
                   if (num[nm] == num2[counter2]
                                            //adds the second value to the jmenu with th name stored in t.
                                            labelToMenu2.put(second, (firstLevel.add(new JMenu (second))));
                                       }counter2++;
         // Third JMenu added /////////////////////////////////////////////////////////////////
         ResultSet rs3 = stmt.executeQuery(query3);
              while     (rs3.next()) {
                                  //String next is set to the value contained in subMenu
                                  String next = rs3.getString("subMenu");
                                  //String third is set to the value contained in ingredient
                                  String third = rs3.getString("Ingredient");
                                  JMenu secondLevel = (JMenu)labelToMenu2.get(next);
                                  int f2 = rs3.getInt("MenuNumber");
                                  //System.out.println(f2);
                                  int f3 = rs3.getInt("PrimaryNumber");
                   if (f3 == f2){
                             labelToMenu3.put(third, secondLevel.add(new JMenuItem(third)));
         // Add AtionListeners ////////////////////////////////////////////////////////////////
         ResultSet rs4 = stmt.executeQuery(query4);
              while     (rs4.next()) {
                   String third2 = rs4.getString("Ingredient");
         JMenuItem thirdLevel = (JMenuItem)labelToMenu3.get(third2);
         thirdLevel.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   JMenuItem source = (JMenuItem)(e.getSource());
                   String actionText = source.getText();
                   PopUp pop = new PopUp(actionText);
                        stmt.close();
                        con.close();
                             }catch(SQLException ex)     {
                        System.err.println(ex);
    return (fileMenu);
         //                                        End Of Connection                                             //
         // Add subMenu menu item /////////////////////////////////////////////////////////////
    public static void clear()     {
    nameInput.setText("");
    victor.removeAllElements();
    printList.setListData(victor);
    part1.setText("");
    public static void rebuild()     {
    fileMenu.removeAll();
    fileMenu.add(menus());
    bar.add( fileMenu );
    public static void main(String args[])     {
         TextAreaDemo t = new TextAreaDemo();
         t.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
    the code inside the method 'rebuild()' will work from inside the main JFrame body if assigned to a button (such as the example position denoted by HERE in the code), but that is undesirable as it requires the user to refresh manually every time they add a new ingredient. what i need is a method that can be called from another class/method/whatever.
    thankyou for any help you can offer, it is much appreciated

    The code you offered did not solve my problem. I have since entered the followinginto the actionlistener of a button on the JFrame,
    refreshMenu = new JButton("Refresh Menu");
    refreshMenu.addActionListener(
             new ActionListener() { 
                // display message dialog when user selects Preview...
                public void actionPerformed( ActionEvent event )
    fileMenu.removeAll();
    fileMenu.add(menus());
    bar.add( fileMenu );          
    );This does what i need, but i need these statements to be made from an external class, not a JButton,

  • JMenu Bar does not show unless I resize the window

    Hi, I have just a simple problem. I am trying to just have a blank JFrame with a JMenuBar at the top with the JMenu "File". I have the following code, but once I run the application it is just a blank frame with no Menus. Once I grab the frame and resize it with the mouse, it appears. What do I need to do to have the menu bar be shown once the application runs?
    import javax.swing.*;
    import java.awt.*;
    class ProgramWindow extends JFrame
    private JMenuBar jmb = new JMenuBar();
    private JMenu file = new JMenu("File");
    public ProgramWindow()
    setSize(300, 300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
    setJMenuBar(jmb);
    jmb.add(fileMenu);
    Container c = getContentPane();
    c.setBackground(Color.lightGray);
    c.setLayout(new BorderLayout());
    setConentPane(c);
    public class Program
    public static void main (String[] args)
    ProgramWindow pw = new ProgramWindow();
    }

    Normally you poop up and decorate frames/dialogs before you set them
    visible. Otherwise you have to revalidate() them after you' ve added
    some components to them. (resizing them does that for you as you have
    noticed).
    kind regards,
    Jos

  • JMenu obscured by another component

    Hi all,
    I've inherited about 10k lines of jdk 1.2 code and I'm converting it to swing for the GUI. There's some pretty messing implementation of scroll panes and such (It's essentially a telnet client). So, here is what I am experiencing:
    I changed all Frames to JFrames, Panels to JPanels, and everything to JMenu/Bars/Items. When I switched to JMenus and opened the menu in the running program, they are all obscured behind this cryptic scrolling canvas hybrid class. I have a feeling that updating the weird scrolling component to something more stable will fix it, but what I wanted to know is how the menus are obscured. Would that component's paint have to be called after the Menus were painted by swing? I don't think that has happened (I am not sure), but is there any other way they could be obscured like that?
    Thanks for an insights. At this point, it's a matter of intellectual curiosity, so I'd like to know for future debugging.
    Kate

    If your "cryptic scrolling canvas hybrid class" is a Canvas subclass, change it to subclass JPanel and use paintComponent() instead of paint().
    Or if you can't do that, use call JPopupMenu.setDefaultLightWeightPopupEnabled(true); before creating the menus.

  • Calculating and displaying the Length of the side of a triangle

    Hi everyone. I am currently working on Dragging and Stretching a triangle on screen. Ive got it working to a certain extent but the only problem is that whenever I go to the point from which i have to drag my triangle i.e. the Left hand Corner of the BAse at exactly 300,300 it redraws a new triangle below the existing one and then when i stretch it from the top and the right it leaves a trail of triangles everytime. But when i resize my window it clears the trail only to start agian when I drag or stretch it...
    All my code for wahtever I have done is displayed below. I would appreciate all the help that any one can offer.
    Secondly , as I stretch my triangle I would like to calculate My Length of the hypotenuse and the other 2 sides as they change and display it in System.out.println for now...
    PLEASE HELP
    the code is
    This is my Main Form --- Interactive Geometry.java
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JFrame;
    * InteractiveGeometry.java
    * Created on 30 November 2004, 20:29
    * @author  Kripa Bhojwani
    public class InteractiveGeometry extends javax.swing.JFrame {
        public EastPanel eastpanel;
        public Container container;
        public GeomPanel gp;
        public boolean pressed = false;
        public boolean pressT = false;
        public boolean pressR = false;
        /** Creates new form InteractiveGeometry */
        public InteractiveGeometry() {
            initComponents();
            eastpanel = new EastPanel();
            container = new Container();
            Model model = new Model(300,150,450,300,300,300);
            gp = new GeomPanel(model);
            container = getContentPane();
            container.add(eastpanel,BorderLayout.EAST);
            container.add(gp,BorderLayout.CENTER);
            setSize(1400,9950);
            gp.addMouseMotionListener(
            new MouseMotionListener() { //anonymous inner class
                //handle mouse drag event
                public void mouseDragged(MouseEvent me) {
                    setTitle("Dragging: x=" + me.getX() + "; y=" + me.getY());
                public void mouseMoved(MouseEvent me) {
                    setTitle("Moving: x=" + me.getX() + "; y=" + me.getY());
        /** 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() {
            jMenuBar2 = new javax.swing.JMenuBar();
            jMenu2 = new javax.swing.JMenu();
            jMenuItem1 = new javax.swing.JMenuItem();
            jMenu1 = new javax.swing.JMenu();
            jMenuItem2 = new javax.swing.JMenuItem();
            addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
                public void mouseDragged(java.awt.event.MouseEvent evt) {
                    formMouseDragged(evt);
                public void mouseMoved(java.awt.event.MouseEvent evt) {
                    formMouseMoved(evt);
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            jMenuBar2.setBackground(new java.awt.Color(0, 102, 204));
            jMenu2.setBackground(new java.awt.Color(222, 222, 238));
            jMenu2.setText("File");
            jMenu2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jMenu2ActionPerformed(evt);
            jMenuItem1.setBackground(new java.awt.Color(204, 255, 255));
            jMenuItem1.setText("Exit");
            jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jMenuItem1ActionPerformed(evt);
            jMenu2.add(jMenuItem1);
            jMenuBar2.add(jMenu2);
            jMenu1.setBackground(new java.awt.Color(199, 215, 255));
            jMenu1.setText("Theorem ");
            jMenuItem2.setText("Pythagoras Theorem");
            jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jMenuItem2ActionPerformed(evt);
            jMenu1.add(jMenuItem2);
            jMenuBar2.add(jMenu1);
            setJMenuBar(jMenuBar2);
            pack();
        private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        private void formMouseDragged(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
        private void formMouseMoved(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
        public void mouseDragged(MouseEvent me) {
            setTitle("Dragging: x=" + me.getX() + "; y=" + me.getY());
        private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            System.exit(0);
        /** 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[]) {
            InteractiveGeometry ig = new InteractiveGeometry();
            ig.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            ig.show();
            // new InteractiveGeometry().show();
        // Variables declaration - do not modify
        private javax.swing.JMenu jMenu1;
        private javax.swing.JMenu jMenu2;
        private javax.swing.JMenuBar jMenuBar2;
        private javax.swing.JMenuItem jMenuItem1;
        private javax.swing.JMenuItem jMenuItem2;
        // End of variables declaration
    This is my Panel -- GeomPanel.java which draws everything -- /*
    * GeomPanel.java
    * Created on 30 November 2004, 20:29
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.Graphics.*;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.geom.Line2D;
    import java.awt.geom.Point2D;
    import java.awt.event.*;
    import java.awt.Graphics2D;
    import java.awt.geom.Ellipse2D;
    import javax.swing.event.TableModelListener;
    import javax.swing.JScrollPane;
    import javax.swing.event.*;
    import java.awt.Dimension;
    import java.awt.Container.*;
    * @author Kripa Bhojwani
    public class GeomPanel extends javax.swing.JPanel implements Observer, MouseMotionListener, MouseListener {
    private Model model;
    private boolean pressed = false;
    private boolean pressT = false;
    private boolean pressR = false;
    /** Creates new form GeomPanel */
    public GeomPanel(Model model) {
    this.model = model;
    model.addObserver(this);
    addMouseListener(this);
    addMouseMotionListener(this);
    initComponents();
    setBackground(Color.getHSBColor(6,600,660));
    public void paintComponent(Graphics gfx) {
    Graphics2D g = (Graphics2D) gfx;
    Point tc = model.getTop();
    Point lc = model.getLeft();
    Point rc = model.getRight();
    Point2D.Double p1 = new Point2D.Double(tc.getX(),tc.getY());
    Point2D.Double p2 = new Point2D.Double(lc.getX(),lc.getY());
    Point2D.Double p3 = new Point2D.Double(rc.getX(),rc.getY());
    Line2D.Double line = new Line2D.Double(p1, p2);
    Line2D.Double line1 = new Line2D.Double(p2, p3);
    Line2D.Double line2 = new Line2D.Double(p1, p3);
    g.setColor(Color.BLACK);
    g.draw(line);
    g.draw(line2);
    g.draw(line1);
    /** 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() {
    setLayout(new java.awt.BorderLayout());
    addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
    public void mouseDragged(java.awt.event.MouseEvent evt) {
    formMouseDragged(evt);
    private void formMouseDragged(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:
    public void mouseClicked(MouseEvent e) {
    public void mouseDragged(MouseEvent e) {
    System.out.println("Dragged at "+ e.getX()+ "," + e.getY());
    if(pressed == true){
    model.setLeft(e.getX() , e.getY());
    else if(pressT == true){
    model.setTop(e.getX() , e.getY());
    else if (pressR == true){
    model.setRight(e.getX(), e.getY());
    else{
    pressed = false;
    pressT= false;
    pressR=false;
    repaint();
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    public void mouseMoved(MouseEvent e) {
    System.out.println("Mouse at " + e.getX() +"," + e.getY());
    public void mousePressed(MouseEvent e) {
    if (model.getLeft().getX()== e.getX() && model.getLeft().getY()== e.getY()){
    pressed = true;
    else if (model.getTop().getX()==e.getX() && model.getTop().getY()==e.getY()){
    pressT = true;
    else if(model.getRight().getX() == e.getX() && model.getRight().getY()==e.getY()){
    pressR = true;
    // else if(model.getCircle().getX() == e.getX() && model.getCircle().getY() == e.getY()){
    // inoval = true;
    else {
    pressed =false;
    pressT = false;
    pressR = false;
    } repaint();
    public void mouseReleased(MouseEvent e) {
    if(pressed == true){
    model.setLeft(e.getX(),e.getY());
    else if (pressT ==true ){
    model.setTop(e.getX(), e.getY());
    else if(pressR ==true){
    model.setRight(e.getX(),e.getY());
    else {
    pressed = false;
    pressT = false;
    pressR = false;
    repaint();
    public void update(Observable o, Object arg) {
    repaint();
    // Variables declaration - do not modify
    // End of variables declaration
    This is my Model class called Model.java which Holds all teh data for my triangle
    import java.awt.Point;
    import java.util.Observable;
    * Model.java
    * Created on 05 December 2004, 14:11
    * @author  Kripa Bhojwani
    public class Model extends Observable{
        private int  x1,x2,x3, y1,y2,y3;
        private int _transx;
        private int _transy;
        private int _c;
        private int _d;
        /** Creates a new instance of Model */
        public Model(int x1, int y1, int x2, int y2, int x3, int y3) {
            this.x1 = x1;
            this.y1 = y1;
            this.x2 = x2;
            this.y2 = y2;
            this.x3 = x3;
            this.y3 = y3;
            setChanged();
            notifyObservers();
        public void setTop(int x1, int y1){
            //this.x1 =x1;
            this.y1= y1;
            setChanged();
            notifyObservers();
        public void setRight(int x2, int y2){
            this.x2 = x2;
            // this.y2 =y2;
            setChanged();
            notifyObservers();
        public void setLeft(int x3, int y3){
            _transx = x3 - this.x3;
            _transy = y3 - this.y3;
            this.x3 += _transx;
            this.y3 += _transy;
            this.y2 += _transy;
            this.x2 += _transx;
            this.x1 += _transx;
            this.y1 += _transy;
            setChanged();
            notifyObservers();
        public Point getTop(){
            Point p = new Point(x1,y1);
            return p;
        public Point getRight(){
            Point p1 = new Point(x2,y2);
            return p1;
        public Point getLeft(){
            Point p3 = new Point(x3,y3);
            return p3;
        public void update() {
            setChanged();
            notifyObservers();
    This is my TableModel which is the JTable to display all the Cordinates and Lengths and other Measurements like angles etc./*
    * TableModel.java
    * Created on 03 December 2004, 15:08
    import javax.swing.JTable;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Observer;
    import javax.swing.event.TableModelEvent;
    import javax.swing.table.AbstractTableModel;
    * @author Kripa Bhojwani
    public class TableModel extends AbstractTableModel implements Observer{
    private String[] columnNames = {"Point", "X Coordinate", "Y Coordinate"};
    private Object[][] data = {};
    private int rowCount;
    private int columnCount;
    /** Creates a new instance of TableModel */
    public TableModel() {
    rowCount = 0;
    columnCount = 3;
    public int getColumnCount() {
    return columnCount;
    public int getRowCount() {
    return rowCount;
    public String getColumnName(int col) {
    return columnNames[col];
    public void setColumnName (String[] name){
    columnNames = name;
    public void setValueAt(Object obj, int row, int col) {
    data[row][col] = obj;
    fireTableCellUpdated(row, col);
    TableModelEvent tme = new TableModelEvent(this);
    fireTableChanged(tme);
    public Object getValueAt(int row, int col) {
    return data[row][col];
    public void update(java.util.Observable o, Object arg) {
    This is the Panel on the east side of My Main application form which will display all the measurements and Cordinates ---EastPanel.java
    import java.awt.BorderLayout;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.event.TableModelListener;
    import java.awt.Dimension;
    * EastPanel.java
    * Created on 04 December 2004, 23:07
    * @author  Kripa Bhojwani
    public class EastPanel extends javax.swing.JPanel implements TableModelListener{
        private TableModel tm;
        /** Creates new form EastPanel */
        public EastPanel() {   
          initComponents();
            tm = new TableModel();
            JTable table1 = new JTable(tm);
            table1.setPreferredScrollableViewportSize(new Dimension(250,264));
            table1.getModel().addTableModelListener(this);
            JScrollPane sp = new JScrollPane(table1);
            add(sp,BorderLayout.EAST);
        /** 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() {
            setLayout(new java.awt.BorderLayout());
        public void tableChanged(javax.swing.event.TableModelEvent e) {
        // Variables declaration - do not modify
        // End of variables declaration
    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.DefaultTableCellRenderer;
    public class G
    public G()
    TriangleModel tri = new
    ri = new TriangleModel(175,100,175,250,325,250);
    TriangleView view = new TriangleView(tri);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(view.getUIPanel(),
    Panel(), "North");
    f.getContentPane().add(view);
    f.getContentPane().add(view.getTablePanel(),
    Panel(), "South");
    f.setSize(500,500);
    f.setLocation(200,200);
    f.setVisible(true);
    public static void main(String[] args)
    new G();
    class TriangleModel // (x1,
    y1)
    {                                         //      |\
    static final int SIDES = 3; // | \
    private int cx, cy; // |
    | \
    Polygon triangle; // |_
    |_ _\ (x3, y3)
    int selectedIndex; // (x2,
    (x2, y2)
    NumberFormat nf;
    Line2D[] medians;
    Point2D centroid;
    public TriangleModel(int x1, int y1, int x2, int
    int y2, int x3, int y3)
    int[] x = new int[] { x1, x2, x3 };
    int[] y = new int[] { y1, y2, y3 };
    triangle = new Polygon(x, y, SIDES);
    nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(1);
    public boolean contains(Point p)
    // Polygon.contains doesn't work well enough
    return (new Area(triangle)).contains(p);
    public boolean isLineSelected(Rectangle r)
    Line2D line = new Line2D.Double();
    for(int j = 0; j < SIDES; j++)
    int[] x = triangle.xpoints;
    int[] y = triangle.ypoints;
    int x1 = x[j];
    int y1 = y[j];
    int x2 = x[(j + 1) % SIDES];
    int y2 = y[(j + 1) % SIDES];
    line.setLine(x1, y1, x2, y2);
    if(line.intersects(r))
    selectedIndex = j;
    return true;
    selectedIndex = -1;
    return false;
    * Only works for right triangle with right angle
    angle at (x2, y2)
    public void moveSide(int dx, int dy, Point p)
    int[] x = triangle.xpoints;
    int[] y = triangle.ypoints;
    switch(selectedIndex)
    case 0:
    x[0] += dx;
    x[1] += dx;
    break;
    case 1:
    y[1] += dy;
    y[2] += dy;
    break;
    case 2:
    double rise = y[2] - y[0];
    double run = x[2] - x[0];
    double slope = rise/run;
    // rise / run == (y[2] - p.y) / (x[2]
    ] - p.y) / (x[2] - p.x)
    x[2] = p.x + (int)((y[2] - p.y) /
    )((y[2] - p.y) / slope);
    // rise / run == (p.y - y[0]) / (p.x
    y - y[0]) / (p.x - x[0])
    y[0] = p.y - (int)((p.x - x[0]) *
    )((p.x - x[0]) * slope);
    public void translate(int dx, int dy)
    triangle.translate(dx, dy);
    public Polygon getTriangle()
    return triangle;
    public String findCentroid()
    int[] x = triangle.xpoints;
    int[] y = triangle.ypoints;
    // construct the medians defined as the line
    the line from
    // any vertex to the midpoint of the opposite
    opposite line
    medians = new Line2D[x.length];
    for(int j = 0; j < x.length; j++)
    int next = (j + 1) % x.length;
    int last = (j + 2) % x.length;
    Point2D vertex = new Point2D.Double(x[j],
    Double(x[j], y[j]);
    // get midpoint of line opposite vertex
    double dx = ((double)x[last] -
    le)x[last] - x[next])/2;
    double dy = ((double)y[last] -
    le)y[last] - y[next])/2;
    Point2D oppLineCenter = new
    Center = new Point2D.Double(x[next] + dx,
    y[next]
    y[next] + dy);
    medians[j] = new Line2D.Double(vertex,
    uble(vertex, oppLineCenter);
    // centroid is located on any median 2/3 the
    2/3 the way from the
    // vertex (P1) to the midpoint (P2) on the
    ) on the opposite side
    double[] lengths = getSideLengths();
    double dx = (medians[0].getX2() -
    etX2() - medians[0].getX1())*2/3;
    double dy = (medians[0].getY2() -
    etY2() - medians[0].getY1())*2/3;
    double px = medians[0].getX1() + dx;
    double py = medians[0].getY1() + dy;
    //System.out.println("px = " + nf.format(px)
    rmat(px) +
    // "\tpy = " +
    py = " + nf.format(py));
    centroid = new Point2D.Double(px, py);
    return "(" + nf.format(px) + ", " +
    ", " + nf.format(py) + ")";
    public String[] getAngles()
    double[] lengths = getSideLengths();
    String[] vertices = new
    es = new String[lengths.length];
    for(int j = 0; j < lengths.length; j++)
    int opp = (j + 1) % lengths.length;
    int last = (j + 2) % lengths.length;
    double top = lengths[j] * lengths[j] +
    lengths[last] *
    lengths[last] * lengths[last] -
    lengths[opp] *
    lengths[opp] * lengths[opp];
    double divisor = 2 * lengths[j] *
    lengths[j] * lengths[last];
    double vertex = Math.acos(top /
    h.acos(top / divisor);
    vertices[j] =
    ertices[j] = nf.format(Math.toDegrees(vertex));
    return vertices;
    public String[] getLengths()
    double[] lengths = getSideLengths();
    String[] lengthStrs = new
    rs = new String[lengths.length];
    for(int j = 0; j < lengthStrs.length; j++)
    lengthStrs[j] = nf.format(lengths[j]);
    return lengthStrs;
    public String[] getSquares()
    double[] lengths = getSideLengths();
    String[] squareStrs = new
    rs = new String[lengths.length];
    for(int j = 0; j < squareStrs.length; j++)
    squareStrs[j] = nf.format(lengths[j] *
    lengths[j] * lengths[j]);
    return squareStrs;
    private double[] getSideLengths()
    int[] x = triangle.xpoints;
    int[] y = triangle.ypoints;
    double[] lengths = new double[SIDES];
    for(int j = 0; j < SIDES; j++)
    int next = (j + 1) % SIDES;
    lengths[j] = Point.distance(x[j], y[j],
    (x[j], y[j], x[next], y[next]);
    return lengths;
    class TriangleView extends JPanel
    private TriangleModel model;
    private Polygon triangle;
    private JTable table;
    private JLabel centroidLabel;
    private boolean showConstruction;
    TriangleControl control;
    public TriangleView(TriangleModel model)
    this.model = model;
    triangle = model.getTriangle();
    showConstruction = false;
    control = new TriangleControl(this);
    addMouseListener(control);
    addMouseMotionListener(control);
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    g2.draw(triangle);
    if(model.medians == null)
    centroidLabel.setText("centroid location:
    id location: " + model.findCentroid());
    // draw medians and centroid point
    if(showConstruction && !control.dragging)
    g2.setPaint(Color.red);
    for(int j = 0; j < 3; j++)
    g2.draw(model.medians[j]);
    g2.setPaint(Color.blue);
    g2.fill(new
    g2.fill(new Ellipse2D.Double(model.centroid.getX() -
    2,
    model.centroid.getY()
    model.centroid.getY() - 2, 4, 4));
    public TriangleModel getModel()
    return model;
    public JTable getTable()
    return table;
    public JLabel getCentroidLabel()
    return centroidLabel;
    public JPanel getUIPanel()
    JCheckBox showCon = new JCheckBox("show
    ox("show construction");
    showCon.addActionListener(new
    ener(new ActionListener()
    public void actionPerformed(ActionEvent
    (ActionEvent e)
    boolean state =
    boolean state =
    ((JCheckBox)e.getSource()).isSelected();
    showConstruction = state;
    repaint();
    JPanel panel = new JPanel();
    panel.add(showCon);
    return panel;
    public JPanel getTablePanel()
    String[] headers = new String[] { "", "", "",
    // row and column data labels
    String[] rowHeaders = {
    "sides", "lengths", "squares", "angles",
    ", "angles", "degrees"
    String[] sidesRow = { "vertical",
    rtical", "horizontal", "hypotenuse" };
    String[] anglesRow = { "hyp to ver", "ver to
    "ver to hor", "hor to hyp" };
    // collect data from model
    String[] angles = model.getAngles();
    String[] lengths = model.getLengths();
    String[] squares = model.getSquares();
    String[][] allData = { sidesRow, lengths,
    lengths, squares, anglesRow, angles };
    int rows = 5;
    int cols = 4;
    Object[][] data = new Object[rows][cols];
    for(int row = 0; row < rows; row++)
    data[row][0] = rowHeaders[row];
    for(int col = 1; col < cols; col++)
    data[row][col] = allData[row][col -
    lData[row][col - 1];
    table = new JTable(data, headers)
    public boolean isCellEditable(int row,
    ble(int row, int col)
    return false;
    DefaultTableCellRenderer renderer =
    (DefaultTableCellRenderer)table.getDefaultRenderer(St
    ring.class);
    renderer.setHorizontalAlignment(JLabel.CENTER);
    centroidLabel = new JLabel("centroid
    centroid location: ", JLabel.CENTER);
    Dimension d =
    sion d = centroidLabel.getPreferredSize();
    d.height = table.getRowHeight();
    centroidLabel.setPreferredSize(d);
    JPanel panel = new JPanel(new
    anel(new BorderLayout());
    panel.setBorder(BorderFactory.createTitledBorder("tri
    angle data"));
    panel.add(table);
    panel.add(centroidLabel, "South");
    return panel;
    class TriangleControl extends MouseInputAdapter
    TriangleView view;
    TriangleModel model;
    Point start;
    boolean dragging, altering;
    Rectangle lineLens; // used for line
    line selection
    public TriangleControl(TriangleView tv)
    view = tv;
    model = view.getModel();
    dragging = altering = false;
    lineLens = new Rectangle(0, 0, 6, 6);
    public void mousePressed(MouseEvent e)
    Point p = e.getPoint();
    lineLens.setLocation(p.x - 3, p.y - 3);
    // are we over a line
    if(model.isLineSelected(lineLens))
    start = p;
    altering = true;
    // or are we within the triangle
    else if(model.contains(p))
    start = p;
    dragging = true;
    public void mouseReleased(MouseEvent e)
    altering = false;
    dragging = false;
    view.getCentroidLabel().setText("centroid
    centroid location: " +
    model.findCentroid());
    view.repaint(); // for the construction
    truction lines
    public void mouseDragged(MouseEvent e)
    Point p = e.getPoint();
    if(altering)
    int x = p.x - start.x;
    int y = p.y - start.y;
    model.moveSide(x, y, p);
    updateTable();
    view.repaint();
    start = p;
    else if(dragging)
    int x = p.x - start.x;
    int y = p.y - start.y;
    model.translate(x, y);
    view.repaint();
    start = p;
    private void updateTable()
    String[] lengths = model.getLengths();
    String[] squares = model.getSquares();
    String[] angles = model.getAngles();
    JTable table = view.getTable();
    for(int j = 0; j < angles.length; j++)
    table.setValueAt(lengths[j], 1, j + 1);
    table.setValueAt(squares[j], 2, j + 1);
    table.setValueAt(angles[j], 4, j + 1);
    view.getCentroidLabel().setText("centroid
    centroid location: " +
    model.findCentroid());
    Hey sorry mate.. ive got a nother problem.
    I need to add loads of theorems to this tool. so i need a JMenu Bar called File with all the normal things. then another Menu called Theorems where i can have a list of JMenuItems with the theorem names --- Like when they click on Pythagoras Theorem it opens up all the triangle and the traingle data that u helped me with.
    The thing is im using netbeans and in netbeans i can do it coz its there and all you got to do is put the components together.
    Please Help
    Thanks...
    Sharan

  • ..is not abstract and does not override abstract method..

    Hello,
    I've been creating a GUI from scratch, up to now, i have managed to successfully compile the code which forms the window, and a JMenu bar. I now need to add buttons, and for this i need to use an ActionListener, but when i put "implements ActionListener" at the end of "public class TestCode extends JFrame", i recieve the above error message (abstract..). I've looked at recent posts and have come across a post that says adding "actionPerformed(java.awt.event.ActionEvent e)" to the class will resolve the issue. When i add that, i recieve a compile error message saying to add '{' after actionPerformed. I've done this however it still does not compile. Can anyone point me in the right direction please?
    Thanks
    George
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JMenu;
    import javax.swing.JLabel;
    import javax.swing.JMenuItem;
    import javax.swing.JButton;
    import javax.swing.JMenuBar;
    import javax.swing.JPanel;
    import javax.swing.ImageIcon;
    import javax.swing.AbstractButton;
    import javax.swing.JFrame;
    import java.awt.event.KeyEvent;
    import java.util.*;
    public class TestCode extends JFrame  {
        private static void createAndShowGUI() {
         JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame("Robot Control Station");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         JMenuBar menuBar = new JMenuBar();
         JMenu fileMenu = new JMenu("Exit");
         fileMenu.setMnemonic(KeyEvent.VK_F);
         menuBar.add(fileMenu);
            JLabel emptyLabel = new JLabel("");
            emptyLabel.setPreferredSize(new Dimension(750, 750));
            frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
         JMenuItem newMenuItem = new JMenuItem("Exit Program", KeyEvent.VK_N);
         fileMenu.add(newMenuItem);
         frame.setJMenuBar(menuBar);
         frame.setVisible(true);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
           //forward button
         JButton forward = new JButton("Forward");
         forward.setMnemonic(KeyEvent.VK_D);
            forward.setActionCommand("disable");
         forward.setToolTipText("Click this button to make the robot go forward.");
         forward.add(forward);
         frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
         

    thanks for the help,
    i read the tutorial, and have starte dto understand how to use action listeners, but i seem to have stumbled to another problem, it seems that i dont fully undertsand how to use ActioListeners, and i cant see mto see what i'm doing wrong.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JMenu;
    import javax.swing.JLabel;
    import javax.swing.JMenuItem;
    import javax.swing.JButton;
    import javax.swing.JMenuBar;
    import javax.swing.JPanel;
    import javax.swing.ImageIcon;
    import javax.swing.AbstractButton;
    import javax.swing.JFrame;
    import java.awt.event.KeyEvent;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.*;
    public class TestCode extends JFrame implements WindowListener,ActionListener {
         public void actionPerformed(ActionEvent e) {
         forward = new JButton("Forward");
         frame.setLayout(null);
         forward.setMnemonic(KeyEvent.VK_D);
         forward.setActionCommand("Forward");
         forward.setToolTipText("Click this button to make the robot go forward!");
         add(forward);
         addActionListener(this);
         frame.add(forward);     
         JFrame frame;
         JButton forward;
         frame.addActionListener(this);
         private static void createAndShowGUI() {
         JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame("Robot Control Station");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.addWindowListener(this);
         frame.pack();
            frame.setVisible(true);
         //JMenuBar createMenuBar;
         JMenuBar menuBar = new JMenuBar();
         JMenu fileMenu = new JMenu("Exit");
         fileMenu.setMnemonic(KeyEvent.VK_F);
         menuBar.add(fileMenu);
            JLabel emptyLabel = new JLabel("");
            emptyLabel.setPreferredSize(new Dimension(750, 750));
            frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
         JMenuItem newMenuItem = new JMenuItem("Exit Program", KeyEvent.VK_N);
         fileMenu.add(newMenuItem);
         frame.setJMenuBar(menuBar);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
         it points me to line 22 which is frame.addActionListener(this); , it tells me that an identifier is expected, and it is an illegal start of type. I can't get my head round it. Can anyone turn me to the right direction again please?

  • How to active menu item by press Alt key

    Hi everyone,
    I don't know how can i active jmenu bar by pressing Alt key first, and press another key ( for exp. press 'F' go to File menu), they are not at the same by holding Alt key.
    Thanks for help in advance.

    I still didn't get it, would you like give me some details.
    How do i make the ALT key select it (but not open it).
    By pressing the "F' key, the "File "menu selected should be opened.

  • What's best for caling business methods ?

    Hi,
    I developped a swing app with the JMenu Bar. This bar contains the edit, quit, usual options.
    I implemented a MVC pattern with a business object whose responsibility is being called by the controllar to do what the user asked through the view.
    For instance, if he clicks in the "rename" option, th model renames the selected element. (I go quickly on this part since this is not the interesting point :) )
    So to the point.
    I got a handler command which receives all commands sendable by the menus. this handler command does this :
    private void commonHandler(ComponentEvent e)
              JMenuItem __source = (JMenuItem) (e.getSource());
              Method __method = delegatesList.get(_source);
              if (__source != null)
    // do stuff
    etc ...
    I created the delegatesList which is this :
    _delegatesList.put(addNewCdSubMenu, Catalogue.class.getMethod("methodName", null));
    _delegatesList.put(addNewCdSubMenu, Catalogue.class.getMethod("othermethodName", null));
    So using the JMenuItem as a source, I then retrieve the method and invoke it with reflection.
    Question : I think that using plain switch cases with the __source.getName for instance would be simpler.
    My question is the following : what is the standard in this kind of stuff : use if/else, switch or delegates like I did or some simpler and more elegant solution ?
    Many thanks for your help !

    Hi,
    I considered that after some thought, the delegates stuff didn't bring any advantage so I hard coded the calls and dropped the reflection part.
    I would have loved some insight from a senior developer though :)
    bye

  • Trouble with components and JTables

    hey everyone i have a question. i created a gui that has 2 panels each containing a table. each table contains a certain amount of default data. i have a jmenu bar also and when one of the menus is clicked a dialog is presented that returns a new sql statement to place into the table. that all works fine i get the sql statement i search the database and all is good.
    here is my problem
    when i try to remove the table from the panel an add a new table to the same panel nothing is presented but a blank panel.(ie the table doesnt show up). but if i add the new table to a seperate frame the new table shows up fine. any suggestions
    matt
    [email protected]

    use java.awt.CardLayout

  • The JPanel did not show when the menu is selected

    My program consists a JMenu bar with sub menu items. When the user select on the menu items a panel with the gridbag layout will show with all the labels.but the panel did not show. Can anyone show the problem for me ?
    AdminFrameMain.java
    public class AdminFrameMain
         private DisplayMenuBar menubar;
         private DisplayToolBar toolbar;
         private DisplayStatusBar statusbar;     
         public AdminFrameMain()
              JFrame frame = new JFrame("S-League Administration Management System");
              Toolkit kit = frame.getToolkit();
              Dimension windowsize =kit.getScreenSize();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Container content = frame.getContentPane();
              content.setLayout(new BorderLayout());
              menubar = new DisplayMenuBar(frame,content);
              toolbar = new DisplayToolBar(content);
              statusbar = new DisplayStatusBar(content);
              frame.setSize(800,600);
              frame.setVisible(true);
         public static void main(String [] args){
              AdminFrameMain tm = new AdminFrameMain();
    DisplayMenuBar.java
    public class DisplayMenuBar
         private JMenu addMenu,addTeamMenu;
         private JMenuBar bar = new JMenuBar();
         private JToolBar toolbar = new JToolBar();
         private JMenuItem addTeamItem;
         private JFrame setFrame;
         private Container setContent;
         private AddTeamManagement addTeamMang;
         public DisplayMenuBar(JFrame frame,Container c)
              setFrame = frame;
              setContent = c;
              SetMenuBar();
         public void SetMenuBar()
         setFrame.setJMenuBar(bar);
         addMenu = new JMenu("Add");
         //file menu items list
         //Add sub menu
         addTeamMenu = new JMenu("Team Management");
         addMenu.add(addTeamMenu);
         //Add sub menu items
         addTeamMenu.add(addTeamItem = new JMenuItem("Add Team"));
         addTeamMenu.setMnemonic('T');     
         addTeamItem.setMnemonic('T');
         //team items listener
         //addTeamItem.addActionListener(taskcommand);          
         addTeamItem.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                   AddTeamManagement addTeamMang = new AddTeamManagement(setFrame,setContent);
         bar.add(addMenu);
    AddTeamManagement.java
    public class AddTeamManagement
         private JPanel addTeamPanel;
         private JFrame frame;
         private JButton createTeamBt,resetTeamBt;
         private Container addTeamContent;
         private JTextArea teamDescTextArea,teamIndpTextArea;
         private JTextField teamNameField;
         private JLabel teamID,teamDesc,teamInfo,numOfPlayers,teamZone,playersNum;
         private GridBagLayout gridBag;
         private GridBagConstraints constraints;
         public AddTeamManagement(JFrame f,Container c)
              System.out.println("add team mg");
              addTeamPanel = new JPanel();
              frame = f;
              addTeamContent = c;
              gridBag = new GridBagLayout();
              addTeamPanel.setLayout(gridBag);
              addTeamPanel.setBackground(Color.pink);
              constraints = new GridBagConstraints();
              teamID = new JLabel("Team ID:");
              teamDesc = new JLabel("Team Description:");
              teamInfo = new JLabel("Team Info:");
              numOfPlayers = new JLabel("No Of Players:");
              playersNum = new JLabel("15 Maximun");
              teamZone = new JLabel("Team Zone:");
              constraints.fill = constraints.VERTICAL;
              constraints.weightx = 1;
              constraints.weighty = 0;
              addComponent(teamID,0,0,1,1);
              constraints.fill = constraints.VERTICAL;
              constraints.weightx = 1;
              constraints.weighty = 0;
              addComponent(teamDesc,1,0,1,1);
              constraints.fill = constraints.VERTICAL;
              constraints.weightx = 1;
              constraints.weighty = 0;
              addComponent(teamInfo,2,0,1,1);
              constraints.fill = constraints.VERTICAL;
              constraints.weightx = 1;
              constraints.weighty = 0;
              addComponent(numOfPlayers,3,0,1,1);
              constraints.fill = constraints.VERTICAL;
              constraints.weightx = 1;
              constraints.weighty = 0;
              addComponent(teamZone,4,0,1,1);
              System.out.println("showing");
              addTeamContent.add(addTeamPanel,BorderLayout.CENTER);
         public void addComponent(Component component,int row,int column,int width,int height)
              System.out.println("adding c");
              constraints.gridx = column;
              constraints.gridy = row;
              constraints.gridwidth = width;
              constraints.gridheight = height;
              gridBag.setConstraints(component,constraints);
              addTeamPanel.add(component);
              addTeamPanel.setVisible(true);
    }

    Hello,
    you are missing only one link, just add following line to your actionPerformed method of DisplayMenuBar class and all problem will be solved
    setContent.validate();
    Actually, Swing component does not updated automatically. when you do any changes to the component layout it will set that component as invalidated component. To update the view you need to call validate() method defined in JComponent class.
    Virus

  • JTabbedPane Error

    I have the following error generated
    java.lang.NullPointerException
         at ButtonPanel.<init>(Toolbars.java:30)
         at IRCWindow.<init>(IRCWindow.java:29)
         at IRCApplet.panelFinished(IRCApplet.java:161)
         at InitScreen.actionPerformed(IRCApplet.java:929)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1764)
         at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1817)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:419)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:245)
         at java.awt.Component.processMouseEvent(Component.java:5093)
         at java.awt.Component.processEvent(Component.java:4890)
         at java.awt.Container.processEvent(Container.java:1566)
         at java.awt.Component.dispatchEventImpl(Component.java:3598)
         at java.awt.Container.dispatchEventImpl(Container.java:1623)
         at java.awt.Component.dispatchEvent(Component.java:3439)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
         at java.awt.Container.dispatchEventImpl(Container.java:1609)
         at java.awt.Component.dispatchEvent(Component.java:3439)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    The code that generates it is a subclass that is created. It is created when I create the IRCWindow main so this is the function that deals with the JTabbedPane in the main component and then the constructer of the panel with the problem. In the constructer of the ButtonPanel parent.parent is the applet whos code is first shown.
    JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.BOTTOM, JTabbedPane.SCROLL_TAB_LAYOUT);
    public void panelFinished(String[] info) {
              if(info == null) System.exit(0);     //If the cancel button was pressed on InitPanel the program exits
              pane.removeAll();                         //Removes teh temporary panel then adds the permanent tabbedPane
              addFocusListener(new FocusAdapter() {               //This makes it so that whenever focus is gained applet wide
                   public void focusGained(FocusEvent e) {          //the input field will get the keyboard focus
                        ((IRCWindow) tabbedPane.getSelectedComponent()).input.requestFocus();
              network = info[0];                              //The following pulls the values that are returned from the initScreen
              port = new Integer(info[1]).intValue();
              nickName = info[2];
              password = nickName + " " + new Random().nextInt();     //Creates the password from nickName and a random integer
              main = new IRCWindow(network, me);                    //This creates the main window and puts it into the first index of the arrayList
              channels.add(0, main);                                   //Then customize the main to the lack of need fro managment
              main.remove(main.nickScroller);
              main.remove(main.toolbar);
              tabbedPane.addTab(network, null, main, network + " main window");
              pane.add(tabbedPane);
              pane.validate();
              StringTokenizer tok = new StringTokenizer(info[3], " ;,");          //Creates a string of arrays that contain the different
              chan = new String[tok.countTokens()];                              //starting commands and below the starting channels
              for(int i = 0; tok.hasMoreTokens(); i++)
                   chan[i] = tok.nextToken();
              tok = new StringTokenizer(info[4], ";,");
              commands = new String[tok.countTokens()];
              for(int i = 0; tok.hasMoreTokens(); i++)
                   commands[i] = tok.nextToken();
              try {
                   //This part of the function creates a new socket that connects to the server.  I/O is then established with the
                   //server and the commands that the server needs to validate the connection are sent.  Exceptions are caught and
                   //End in the termination of the code.
                   connection = new Socket(network , port);
                   myReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                   myWriter = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
                   write("PASS " + password);
                   write("NICK " + nickName);
                   write("USER " + nickName + " " + connection.getLocalAddress().getHostName() + " " + network + " :" + nickName);
              }catch(IOException e) {System.exit(0);}
              run();
              setJMenuBar(myBar);     //Adds the JMenu bar once connected.  not done before to reduce confusion
         }//end of panelFinished(String[] info)
    ButtonPanel(IRCWindow parent) {
              this.parent = parent;                         //Obtains basic information
              applet = parent.parent;
              tabbedPane = applet.tabbedPane;
              setLayout(gbl);
              for(int i = 0; i < 6; i++) {                         //Goes through the different mode buttons.  They are then assigned the corresponing text in the names[]
                   modes[i] = new JToggleButton(names);          //They are also made no togable by user but the JVM takes care of that, also button size is set. The
                   modes[i].setFocusable(false);                    //action listener is also added. They are added in sequential order. This is the same for everything
                   modes[i].setMargin(new Insets(0,0,0,0));     //else except topic.
                   modes[i].setMaximumSize(buttonSize);
                   modes[i].setMinimumSize(buttonSize);
                   modes[i].setPreferredSize(buttonSize);
                   modes[i].addActionListener(this);
                   add(modes[i], new GridBagConstraints(i,0,1,1,0,0,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0,0,0,0), 4, 0));
              topic.setMaximumSize(new Dimension(2147483647,20));     //This is the only class that differs. It takes up all aditional available space.
              topic.setMinimumSize(new Dimension(50,20));
              topic.addActionListener(this);
              add(topic, new GridBagConstraints(6,0,1,1,14,0,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0,0,0,0), 4, 0));
              limitButton = new JToggleButton("L");               //See Top
              limitButton.setFocusable(false);
              limitButton.setMargin(new Insets(0,0,0,0));
              limitButton.setMaximumSize(buttonSize);
              limitButton.setMinimumSize(buttonSize);
              limitButton.setPreferredSize(buttonSize);
              limitButton.addActionListener(this);
              limit.setMaximumSize(textFieldSize);
              limit.setMinimumSize(textFieldSize);
              limit.setPreferredSize(textFieldSize);
              limit.addActionListener(this);
              add(limitButton, new GridBagConstraints(7,0,1,1,0,0,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0,0,0,0), 4, 0));
              add(limit, new GridBagConstraints(8,0,1,1,0,0,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0,0,0,0), 4, 0));
              keyButton = new JToggleButton("K");                    //See Top
              keyButton.setFocusable(false);
              keyButton.setMargin(new Insets(0,0,0,0));
              keyButton.setMaximumSize(buttonSize);
              keyButton.setMinimumSize(buttonSize);
              keyButton.setPreferredSize(buttonSize);
              keyButton.addActionListener(this);
              key.setMaximumSize(textFieldSize);
              key.setMinimumSize(textFieldSize);
              key.setPreferredSize(textFieldSize);
              key.addActionListener(this);
              add(keyButton, new GridBagConstraints(9,0,1,1,0,0,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0,0,0,0), 4, 0));
              add(key, new GridBagConstraints(10,0,1,1,0,0,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0,0,0,0), 4, 0));
              for(int i = 0; i < 3; i++) {                         //See Top
                   window[i] = new JButton(names[i+6]);
                   window[i].setFocusable(false);
                   window[i].setMargin(new Insets(0,0,0,0));
                   window[i].setMaximumSize(buttonSize);
                   window[i].setMinimumSize(buttonSize);
                   window[i].setPreferredSize(buttonSize);
                   window[i].addActionListener(this);
                   add(window[i], new GridBagConstraints(i + 11,0,1,1,0,0,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0,0,0,0), 4, 0));

    According to your stack trace:
    java.lang.NullPointerException
    at ButtonPanel.<init>(Toolbars.java:30)
    which line is line 30 in Toolbars.java? It should be somewhere inside the constructor of the ButtonPanel class. This should give you some hint on what caused the NullPointerException. If it still can't be solved, post back and show us the source near that line.

  • Architectural approach

    Hi java gurus,
    i'm designing a sales tracking application, which has a gui client (not web based), which will connect to an SQL server database. I've written the gui in swing and thats fine and dandy. My question how should i approach developing the middle tier. Should i do a straigh sql connection on the clinet side (using a db access thread) or should i connect it to some middleware, e.g. connect to a jboss or resin server which will handle the connection / sql requests to the db server. If so how should i approach this? Use DAO or session facade? Some insight here would be great! Thanks again.

    hi all,
    thanks for the rapid resposne. The reason i wrote
    e iton swing is i use a JDesktop frame, and the have
    a jmenu bar etc. So the gui is quite complex. not
    something that can be easily developed in a html ,
    dhtml etc (you can imagine the code on that!!). Actually I've seen browser based JSP UIs that are very complex and attractive. Unless your users are demanding drag & drop, a browser might be an alternative. But you see fixated on your Swing app, so that's fine.
    the
    number of users would be a min of 15. Min is no problem. What about the max?
    originally i
    coded the sql queries and connection on the client,
    through a separate thread, so that way atleast the
    requests do not block the paint methods of the gui
    (so you don't get that funny dragging on your
    windows!). I've compiled the application as an EXE
    file, and this exe is on a shared network drive.
    Users just have a link to the shortcut. I guess my
    y main question is regardless if i use session
    facade or dao, how will i get my gui to retrieve the
    results? The UI Listener class that handles the query request will instantiate the DAO, call its finder method, and work with the List of objects that come back. It's all in memory, so there's no worries there.
    i've developed a jsp, servlet, ejb
    application before, and normaly i would use a servlet
    to query the ejbs, based on a jsp request. But
    through a downloaded swing based client i'm not quite
    sure. You're going to have to have your Swing client make a remote request to get results back.
    If you talk directly to an EJB, you'll do the JNDI lookup in the Listener that handles the query event to get the EJB remote interface, make the call, and deal with the data structure of objects that comes back. Your UI won't deal with ResultSets or anything like that anymore. It'll just be a data structure or object that will then be displayed.
    The DAO will be hidden behind the session facade in this case. All the database specific stuff will be in the DAO and out of the UI. The session bean can handle any transactional needs you have, too. Connections are pooled. Must more scalable.
    %

  • Making elements dimensions relative to other elements

    Attached is a picture of, roughly, what I want my app to look like. I did do it in paint, but I tried to make it look as nice as I could for you all. The red line is for reference only; it won't be in the app itself. Basically, the lower areas should be fully expanded vertically from the bottom of the app to the bottom of the {color:#0000ff}upper area (which remains unchanged most of the time, but the dimensions of that area never change) {color}and horizontally from the [left/right] edge of the app to the red line and the user should be able to move that red line.
    So far I have:
    {color:#0000ff}
    {color}JFrame
        JMenu(Bar?)
        JPanel (Upper Area)
    ...lost...
        JPanel (lower left)
            scroll bars
        JPanel (lower right)
            scroll barsI am totally new to this swing stuff so feel free to take me by the hand and slap me around with it if I'm too far off. Thank you.
    {color}
    Edited by: tenmiles on Jan 27, 2009 8:15 PM
    Edited by: tenmiles on Jan 27, 2009 8:45 PM
    Actually attached the picture this time.... http://xs135.xs.to/xs135/09052/appgui724.jpg

    tenmiles wrote:
    Thanks to both of you. I had played around with jSplitPane, but my IDE made both sides buttons by default and didn't really make it clear how to customize it further.If you're serious about learning, drop the visual designer like a hot potato. It can only hamper, not help, your learning.
    The visual designer can be a productive tool in the hands of someone who has already learned Swing coding.
    I also really like that link as it helped explain layouts beyond "don't try this at home, kids". Much appreciated.So click arounf a bit, you would have found [How to Use Split Panes|http://java.sun.com/docs/books/tutorial/uiswing/components/splitpane.html]
    db

  • I want to have JMenu on a Side bar(JPanel) with sub menu.

    I want to have the JMenu on the sidebar(which is a
    JPanel placed at WEST). This JMenu shall have the sub
    menu with it. I got the JMenu on the Sidebar but when
    i take mouse over(or click) the MenuItem it is
    displaying the sub Menu. I am attaching the my code.
    Can anyone please let me know why it is not displaying
    the sub menu and what should be added to my code to
    work?
    Thanks in Advance(see below for code)
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class SideBarMenu extends JFrame {
         JMenuItem menuItem1,menuItem2;
         JMenu books, softwares, tools;
         JSeparator horizontal1, horizontal2,horizontal3;
         JPanel p1, p2;
          public static void main(String[] args) {
           SideBarMenu vAR =  new SideBarMenu();
         public SideBarMenu() {
              super("Side Bar");
              setSize(500,500);
              setLocation(150,100);
              setResizable(true);     
              Container content = getContentPane();
              p1 = new JPanel(new BorderLayout());
              p2 = new JPanel();
              p2.setLayout(new GridLayout(20,1));
              p2.setBorder(BorderFactory.createLineBorder(Color.black,1));
              books = new JMenu("Books");
              horizontal1 = new JSeparator( JSeparator.HORIZONTAL );
              softwares = new JMenu("Softwares");
              horizontal2 = new JSeparator( JSeparator.HORIZONTAL );
              tools = new JMenu("Tools");
                                    horizontal3 = new JSeparator( JSeparator.HORIZONTAL );
              //sub Menu for menu "books"     
              menuItem1 = new JMenuItem("Java");
              books.add(menuItem1);
              menuItem2 = new JMenuItem(".Net");
              books.add(menuItem2);
              //sub Menu for menu "Softwares"          
              menuItem1 = new JMenuItem("Java");
              softwares.add(menuItem1);
              menuItem2 = new JMenuItem(".Net");
              softwares.add(menuItem2);
              //sub Menu for menu "tools"          
              menuItem1 = new JMenuItem("Java");
              tools.add(menuItem1);
              menuItem2 = new JMenuItem(".Net");
              tools.add(menuItem2);
              p2.add(books);
              p2.add(horizontal1);
              p2.add(softwares);
              p2.add(horizontal2);
              p2.add(tools);
              p2.add(horizontal3);
              p1.add(p2,BorderLayout.WEST );
              content.add(p1);
              setVisible(true);
    }

    Hi Ashwin,
    I saw the above code which is approaching my requirement... Thats cool man. Taking that as reference i modified it to make it what i want. The code i have modified and which is very closer to my requirement is attached below. I have set the Windows Look and Feel, because its easy to track my problems with it. The problems am having are:
    1) When the mouse is removed from the menu its submenu is not disappearing.
    2) When i take the mouse over the menu its making the name(Books/softwares/tools) of the menu invisible.
    3) When i take the mouse over the sub menu items they are not getting highlighted, which means they are not listening
    I hope u will solve these issues for me...
    Also make the menu items work ie., just make them print when i click submenus like "Clicked books->java" and "clicked softwares->.Net" so that i get an idea of events....
    Many Thanks .
    Here we go,
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.GridLayout;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JSeparator;
    import javax.swing.UIManager;
    public class SideBarMenu4 extends JFrame
        JMenuBar menuBar;
        JPopupMenu popup = new JPopupMenu();
        JMenuItem menuItem1, menuItem2;
        JMenu books, softwares, tools;
        JLabel mainMenu = new JLabel("Main Menu");
        JMenu subMenu;
        JSeparator horizontal1, horizontal2, horizontal3;
        JPanel p1, p2;
        public static void main(String[] args)
            SideBarMenu4 vAR = new SideBarMenu4();
        public SideBarMenu4()
            super("Side Bar");
            setSize(500, 500);
            setLocation(150, 100);
            setResizable(true);
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            Container content = getContentPane();
            p1 = new JPanel(new BorderLayout());
                        try {
              //MetalLookAndFeel.setCurrentTheme(new MacMetricsTheme());
                 UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");            
            } catch(Exception e) {}
            p2 = new JPanel();
            p2.setLayout(new GridLayout(30, 1));
            p2.setBorder(BorderFactory.createLineBorder(Color.black, 1));
            books = new JMenu("Books");
            horizontal1 = new JSeparator(JSeparator.HORIZONTAL);
            softwares = new JMenu("Softwares");
            horizontal2 = new JSeparator(JSeparator.HORIZONTAL);
            tools = new JMenu("Tools");
            horizontal3 = new JSeparator(JSeparator.HORIZONTAL);
            // sub Menu for menu "books"
            menuItem1 = new JMenuItem("Java");
              popup.add(menuItem1);
            //books.add(menuItem1);
            menuItem2 = new JMenuItem(".Net");
              popup.add(menuItem2);
              popup.setPopupSize(100,50);
            menuBar = new JMenuBar();
            menuBar.setLayout(new GridLayout(0, 1, 5, 5));
            books.add(popup);
              books.setComponentPopupMenu(popup);
            books.addMouseMotionListener(new MouseMotionAdapter(){
                public void mouseMoved(MouseEvent e)
                     popup.show(books, 88, 0);
              softwares.add(popup);
              softwares.setComponentPopupMenu(popup);
            softwares.addMouseMotionListener(new MouseMotionAdapter(){
                public void mouseMoved(MouseEvent e)
                     popup.show(softwares, 88, 0);
              tools.add(popup);
              tools.setComponentPopupMenu(popup);
            tools.addMouseMotionListener(new MouseMotionAdapter(){
                public void mouseMoved(MouseEvent e)
                     popup.show(tools, 88, 0);
            // p2.add(menuBar);
            p2.add(books);
              p2.add(horizontal1);
              p2.add(softwares);
              p2.add(horizontal2);
              p2.add(tools);
              p2.add(horizontal3);
            p1.add(p2, BorderLayout.WEST);
            content.add(p1);
            setVisible(true);
    }

  • Validating enabled and disabled menu bar in JInternalFrame

    hi,
    everybody.
    i have created a main window using JInternalFrame and JDesktopPane. The window has a menu bar in which document menu is used for closing the main window, while employee menu is used for adding new frame for the employee. while the login frame is displayed when the application is executed.
    my problem is, i want to validate that before login process, employee menu should be disabled, and after login is performed employee menu is enabled.
    the following is my code.
    please reply me as i am stucked with it.
    waiting for the reply
    thanks in advance.
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    public class InternalFrameDemo extends JFrame implements ActionListener
    JDesktopPane desktop;
    public InternalFrameDemo()
    super("InternalFrameDemo");
    int inset = 50;
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    setBounds(inset, inset, screenSize.width - inset*2, screenSize.height - inset*2);
    desktop = new JDesktopPane();
    setContentPane(desktop);
    desktop.setBackground(Color.white);
    setJMenuBar(createMenuBar());
    desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    createLogin();
    public JMenuBar createMenuBar()
    JMenuBar menuBar = new JMenuBar();
    JMenu menu = new JMenu("Document");
    menu.setMnemonic(KeyEvent.VK_D);
    menuBar.add(menu);
    JMenuItem menuItem = new JMenuItem("Quit");
    menuItem.setMnemonic(KeyEvent.VK_Q);
    menuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_Q, ActionEvent.ALT_MASK));
    menuItem.setActionCommand("quit");
    menuItem.addActionListener(this);
    menu.add(menuItem);
    JMenu employee = new JMenu("Employee");
    employee.setMnemonic(KeyEvent.VK_E);
    employee.setActionCommand("employee");
    menuBar.add(employee);
    JMenuItem additem = new JMenuItem("Add");
    additem.setMnemonic(KeyEvent.VK_A);
    additem.setActionCommand("add");
    additem.addActionListener(this);
    employee.add(additem);
    return menuBar;
    public void actionPerformed(ActionEvent ae)
    String str = ae.getActionCommand();
    if(str.equals("add"))
    System.out.println("Employee Form Invoked");
    createEmployee();
    else if(str.equals("quit"))
    quit();
    public void createEmployee()
    MyEmployeeFrame employeeframe = new MyEmployeeFrame();
    employeeframe.setVisible(true);
    desktop.add(employeeframe);
    try
    employeeframe.setSelected(true);
    catch(Exception e)
    public void createLogin()
    MyLogin loginframe = new MyLogin();
    loginframe.setVisible(true);
    desktop.add(loginframe);
    try
    loginframe.setSelected(true);
    catch(Exception e){}
    public void quit()
    System.exit(0);
    private static void createAndShowGUI()
    JFrame.setDefaultLookAndFeelDecorated(true);
    InternalFrameDemo frame = new InternalFrameDemo();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(800,600);
    frame.setVisible(true);
    public static void main(String a[])
    createAndShowGUI();
    class MyEmployeeFrame extends JInternalFrame implements ActionListener
    JFrame employeeframe;
    JLabel labelfirstname;
    JLabel labellastname;
    JLabel labelage;
    JLabel labeladdress;
    JLabel labelcity;
    JLabel labelstate;
    JTextField textfirstname;
    JTextField textlastname;
    JTextField textage;
    JTextField textaddress;
    JTextField textcity;
    JTextField textstate;
    JButton buttonsave;
    FileOutputStream out;
    PrintStream p;
    String strfirstname,strlastname,strage,straddress,strcity,strstate;
    GridBagLayout gl;
    GridBagConstraints gbc;
    public MyEmployeeFrame()
    super("Employee Details",true,true,true,true);
    setSize(500,400);
    labelfirstname = new JLabel("First Name");
    labellastname = new JLabel("Last Name");
    labelage = new JLabel("Age");
    labeladdress = new JLabel("Address");
    labelcity = new JLabel("City");
    labelstate = new JLabel("State");
    textfirstname = new JTextField(10);
    textlastname = new JTextField(10);
    textage = new JTextField(5);
    textaddress = new JTextField(15);
    textcity = new JTextField(10);
    textstate = new JTextField(10);
    buttonsave = new JButton("Save");
    gl = new GridBagLayout();
    gbc = new GridBagConstraints();
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.gridx = 1;
    gbc.gridy = 3;
    gl.setConstraints(labelfirstname,gbc);
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.gridx = 3;
    gbc.gridy = 3;
    gl.setConstraints(textfirstname,gbc);
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.gridx = 1;
    gbc.gridy = 5;
    gl.setConstraints(labellastname,gbc);
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.gridx = 3;
    gbc.gridy = 5;
    gl.setConstraints(textlastname,gbc);
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.gridx = 1;
    gbc.gridy = 7;
    gl.setConstraints(labelage,gbc);
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.gridx = 3;
    gbc.gridy = 7;
    gl.setConstraints(textage,gbc);
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.gridx = 1;
    gbc.gridy = 9;
    gl.setConstraints(labeladdress,gbc);
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.gridx = 3;
    gbc.gridy = 9;
    gl.setConstraints(textaddress,gbc);
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.gridx = 1;
    gbc.gridy = 11;
    gl.setConstraints(labelcity,gbc);
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.gridx = 3;
    gbc.gridy = 11;
    gl.setConstraints(textcity,gbc);
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.gridx = 1;
    gbc.gridy = 13;
    gl.setConstraints(labelstate,gbc);
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.gridx = 3;
    gbc.gridy = 13;
    gl.setConstraints(textstate,gbc);
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.gridx = 3;
    gbc.gridy = 17;
    gl.setConstraints(buttonsave,gbc);
    Container contentpane = getContentPane();
    contentpane.setLayout(gl);
    contentpane.add(labelfirstname);
    contentpane.add(textfirstname);
    contentpane.add(labellastname);
    contentpane.add(textlastname);
    contentpane.add(labelage);
    contentpane.add(textage);
    contentpane.add(labeladdress);
    contentpane.add(textaddress);
    contentpane.add(labelcity);
    contentpane.add(textcity);
    contentpane.add(labelstate);
    contentpane.add(textstate);
    contentpane.add(buttonsave);
    buttonsave.addActionListener(this);
    public void reset()
    textfirstname.setText("");
    textlastname.setText("");
    textage.setText("");
    textaddress.setText("");
    textcity.setText("");
    textstate.setText("");
    public void actionPerformed(ActionEvent ae)
    String str = ae.getActionCommand();
    System.out.println(str);
    if(str.equalsIgnoreCase("Save"))
    try
    out = new FileOutputStream("myfile.txt",true);
    p = new PrintStream( out );
    strfirstname = textfirstname.getText();
    strlastname = textlastname.getText();
    strage = textage.getText();
    straddress = textaddress.getText();
    strcity = textcity.getText();
    strstate = textstate.getText();
    p.print(strfirstname+"|");
    p.print(strlastname+"|");
    p.print(strage+"|");
    p.print(straddress+"|");
    p.print(strcity+"|");
    p.println(strstate);
    System.out.println("Record Saved");
    reset();
    p.close();
    catch (Exception e)
    System.err.println ("Error writing to file");
    class MyLogin extends JInternalFrame implements ActionListener
    JFrame loginframe;
    JLabel labelname;
    JLabel labelpassword;
    JTextField textname;
    JPasswordField textpassword;
    JButton okbutton;
    String name = "";
    FileOutputStream out;
    PrintStream p;
    Date date;
    GregorianCalendar gcal;
    GridBagLayout gl;
    GridBagConstraints gbc;
    public MyLogin()
    super("Login",true,true,true,true);
    setSize(400,300);
    gl = new GridBagLayout();
    gbc = new GridBagConstraints();
    labelname = new JLabel("User");
    labelpassword = new JLabel("Password");
    textname = new JTextField("",9);
    textpassword = new JPasswordField(5);
    okbutton = new JButton("OK");
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.gridx = 1;
    gbc.gridy = 5;
    gl.setConstraints(labelname,gbc);
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.gridx = 2;
    gbc.gridy = 5;
    gl.setConstraints(textname,gbc);
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.gridx = 1;
    gbc.gridy = 10;
    gl.setConstraints(labelpassword,gbc);
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.gridx = 2;
    gbc.gridy = 10;
    gl.setConstraints(textpassword,gbc);
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.gridx = 1;
    gbc.gridy = 15;
    gl.setConstraints(okbutton,gbc);
    Container contentpane = getContentPane();
    contentpane.setLayout(gl);
    contentpane.add(labelname);
    contentpane.add(labelpassword);
    contentpane.add(textname);
    contentpane.add(textpassword);
    contentpane.add(okbutton);
    okbutton.addActionListener(this);
    public void reset()
    textname.setText("");
    textpassword.setText("");
    public void run()
    try
    String text = textname.getText();
    String blank="";
    if(text.equals(blank))
    System.out.println("First Enter a UserName");
    else
    if(text != blank)
    date = new Date();
    gcal = new GregorianCalendar();
    gcal.setTime(date);
    out = new FileOutputStream("log.txt",true);
    p = new PrintStream( out );
    name = textname.getText();
    String entry = "UserName:- " + name + " Logged in:- " + gcal.get(Calendar.HOUR) + ":" + gcal.get(Calendar.MINUTE) + " Date:- " + gcal.get(Calendar.DATE) + "/" + gcal.get(Calendar.MONTH) + "/" + gcal.get(Calendar.YEAR);
    p.println(entry);
    System.out.println("Record Saved");
    reset();
    p.close();
    catch (IOException e)
    System.err.println("Error writing to file");
    public void actionPerformed(ActionEvent ae)
    String str = ae.getActionCommand();
    if(str.equals("OK"))
    run();
    loginframe.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    I realize this post is from a few days ago, but if you're still looking for help:
    This is my first thought on how to do this. Unfortunately, it's a bit messy. JMenuItems can be enabled and disabled but JMenus don't have this option...
    public class InternalFrameDemo extends JFrame implements ActionListener
        JDesktopPane desktop;
        JMenuBar menuBar;
        public InternalFrameDemo()
         setJMenuBar(createMenuBar());
         desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
         createLogin();
        public JMenuBar createMenuBar()
         menuBar = new JMenuBar();
         JMenu menu = new JMenu("Document");
         menu.setMnemonic(KeyEvent.VK_D);
         menuBar.add(menu);
         JMenuItem menuItem = new JMenuItem("Quit");
         menuItem.setMnemonic(KeyEvent.VK_Q);
         menuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_Q, ActionEvent.ALT_MASK));
         menuItem.setActionCommand("quit");
         menuItem.addActionListener(this);
         menu.add(menuItem);
         JMenuItem additem = new JMenuItem("Add");
         additem.setMnemonic(KeyEvent.VK_A);
         additem.setActionCommand("add");
         additem.addActionListener(this);
         employee.add(additem);
         return menuBar;
        public void createLogin()
         MyLogin loginframe = new MyLogin( menuBar );
         loginframe.setVisible(true);
         desktop.add(loginframe);
         try
             loginframe.setSelected(true);
         catch(Exception e)
    class MyLogin extends JInternalFrame implements ActionListener
        JMenuBar menuBar;
        public MyLogin( JMenuBar menuBar1 )
         super("Login",true,true,true,true);
         menuBar = menuBar1;
        public void actionPerformed(ActionEvent ae)
         String str = ae.getActionCommand();
         if(str.equals("OK"))
             run();
             JMenu employee = new JMenu("Employee");
             employee.setMnemonic(KeyEvent.VK_E);
             employee.setActionCommand("employee");
             menuBar.add(employee);
             loginframe.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

Maybe you are looking for

  • ERROR WHILE testing WEBSERVICE IN TWO DIFFERENT CLIENTS

    hi all i have developed a proxy and try to test  <b>web service in wsadmin tcode</b> through <b>two</b> DIFFERENT CLIENTS. FROM <b>CLIENT  1</b> IT IS SHOWING THE SUCCESSFULL RESPONSE BUT FROM <b>CLIENT 2</b> IT IS SHOWING THE FOLLOWNG <b>ERROR</b>.

  • Spry XML and image map

    Hi all- I'm new to using spry and xml, but not new to xhtml and layout, having said that. I'm trying to store file paths in my xml and parse that xml to repace <href> tags in an image map. For example (the actual cooridnates in the map are just made

  • Config-Archive Issue on PI 1.3

    Hi Everyone,       Customer has recently installed PI 1.3 software, and then used it to back up  or restore devices' config. However, when imported all devices into PI 1.3 by csv template and set up some setting about schedule daily job of configurat

  • ShowModalDialog in jsf

    I have a view page that shows a list account in a dataTable. When the user clicks on the edit link, a showModal box opens which shows the edit view for the list of accounts. When the user clicks on one of the Add or cancel action buttons, the action

  • Using Component Object Model+ (COM+) in webdynpro

    Dear friends, How can I use Component Object Model+ (COM) in webdynpro? Is it feasible to use COM to access SQL Server 2005 Database. Thanks and Regards, Tarani