Adding a JMenuBar

I am trying to create a simple JMenuBar in the application enlosed below.
I keep getting the following error when ever i compile
"Screen.java": Error #: 300 : method setJMenuBar(javax.swing.JMenuBar) not found in class random.Screen at line 67, column 9". Can some one please enlighten me.
Class Screen is the main class. This is where the GUI is set up. it calls class Canvas which in turn calls class Nodes. GUI draws a bus network which holds a minimum of two nodes and a maximum of 10. The node number is under user control. The aim is to allow a user to select the configure menu to update the number of nodes on display in the GUI.
package random;
import javax.swing.JPanel;
import javax.swing.border.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
* <p>Title: Simulation of the random load balancing algorithm </p
public class Screen extends JPanel {
static int screenWidth = (int)(Toolkit.getDefaultToolkit().getScreenSize().width*0.85);
static int screenHeight = (int)(Toolkit.getDefaultToolkit().getScreenSize().height*0.95);
private Container container;
JButton add;
Canvas canvas;
JMenuBar menubar;
JMenu configure;
Thread animatorThread;
RandomApplet RApplet;
public Screen(RandomApplet RApplet){
     this.RApplet = RApplet;
     makeGui();
public Screen(){
     makeGui();
public void makeGui(){
addMenu();
GridBagLayout gridbag = new GridBagLayout();
     setLayout(gridbag);
     GridBagConstraints c = new GridBagConstraints();
     c.insets = new Insets(1,1,1,1);
     //add drawing canvas
     canvas = new Canvas();
     c.gridx = 0;
     c.gridy = 0;
     c.weightx=1.0;
     c.weighty=1.0;
     c.fill=GridBagConstraints.BOTH;
     gridbag.setConstraints(canvas, c);
     add(canvas);
     c.gridx=0;
     c.gridy=1;
     gridbag.setConstraints(canvas,c);
     add(add=addButton("Add"));
private void addMenu(){
     menubar = new JMenuBar();
setJMenuBar(menubar);
     configure = new JMenu("Configure");
     configure.add(new JMenuItem("add"));
     menubar.add(configure);
private JButton addButton(String name) {
          JButton b = new JButton(name);
          ButtonHandler handler=new ButtonHandler();
          b.addActionListener(handler);
          b.setFont(new Font("Dialog", Font.BOLD, 12));
          b.setMargin(new Insets(0,0,0,0));
          return b;
class ButtonHandler implements ActionListener{
     public void actionPerformed(ActionEvent e){
          if (e.getSource()== add){
               if (canvas.addNode()){
               repaint();
public void run(){
     Thread thisThread = Thread.currentThread();
     while (animatorThread == thisThread){
          try {
          Thread.sleep(100);}
          catch (Exception e){
          break;}
public static void main(String[] args) {
JFrame f=new JFrame("Random");
     f.setSize(screenWidth, screenHeight);
     f.getContentPane().add(new Screen());
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
//class Canvas
package random;
import javax.swing.JPanel;
import java.awt.*;
import java.util.*;
import java.awt.Graphics;
import java.awt.image.*;
import javax.swing.*;
public class Canvas extends JPanel{
int width, height;
Dimension size;
Image canvasImage = null;
Graphics canvasGraphics;
Image networkMem;
int NodeWidth, NodeHeight;
Nodes[] n;
int numberOfNodes;
int x1, y1,x2,y2;
public Canvas(){
// canvas a perfect square
     height = 400;
     width = 400;
     size=new Dimension(width,height);
     setBackground(Color.white);
     networkMem=Toolkit.getDefaultToolkit().createImage("images/computer6.gif");
     NodeWidth = networkMem.getWidth(this);
NodeHeight = networkMem.getHeight(this);
     //network must hold a minimum of 2 nodes
     n = new Nodes[11];
     n[0] = new Nodes(0,this);
     n[1] = new Nodes(1,this);
     numberOfNodes = 2;
public void paintComponent(Graphics g)
super.paintComponent(g);
     //create canvas image
     if (canvasImage==null){
          canvasImage=createImage(getSize().width,getSize().height);
          canvasGraphics = canvasImage.getGraphics();
     //adjust above to fit canvas window
if ((canvasImage.getWidth(this) != getSize().width) || (canvasImage.getHeight(this) != getSize().height)){
     canvasImage = createImage(getSize().width,getSize().height);
          if (canvasImage!=null){
          canvasGraphics.dispose();
          canvasGraphics = canvasImage.getGraphics();
     //create a rectangular border outlining canvas area
     canvasGraphics.drawRect(0,0,getSize().width-1,getSize().height-1);
     x1=width-100;
     y1=height-100;
     x2=width-300;
     y2=width-100;
canvasGraphics.drawLine(x1,y1,x2,y2);
//canvasGraphics.drawLine(width-300,height-100,width-300,height-50);
     //canvasGraphics.drawLine(width-100,height-100,width-100,height-50);
     for(int i=0; i<numberOfNodes; i++){
     n.drawNode(canvasGraphics);
     g.drawImage(canvasImage, 0, 0, this);
     super.paintComponent(canvasGraphics);
public int getNumberOfNodes()
     return numberOfNodes;
public boolean addNode(){
     //add a node to network
     if (numberOfNodes < 10) {
     n[numberOfNodes]= new Nodes(numberOfNodes, this);
     numberOfNodes++;
     repaint();
     return true;
     return false;
public boolean removeNode(){
     boolean removed = false;
     if (numberOfNodes >2) {
     numberOfNodes=numberOfNodes - 1;
     removed = true;
     else{
     removed = false;
     repaint();
     return removed;
//class Nodes
package random;
import javax.swing.JPanel;
import javax.swing.*;
import java.awt.*;
import java.awt.Graphics;
public class Nodes{
int nodeNumber;
Canvas canvas;
public Nodes(int number, Canvas c) {
//each node has a number id
     nodeNumber=number;
     canvas=c;
public void drawNode(Graphics g){
     if (nodeNumber%2 == 0){
canvas.x1=canvas.x1-10;
     System.out.println(""+canvas.x1);
     g.drawLine(canvas.x1,canvas.y1,canvas.x1,canvas.y2-50);
     g.drawImage(canvas.networkMem,canvas.x1,canvas.y1-80,canvas);
     else{
     canvas.x1=canvas.x1-30;
     System.out.println(""+canvas.x1);
     g.drawLine(canvas.x1,canvas.y1,canvas.x1,canvas.y2+50);
     g.drawImage(canvas.networkMem,canvas.x1,canvas.y2+50,canvas);

Thanks for the reply but i figured it out in the end.
I can make use of the following commands
setMenuBar(MenuBar mb)
getMenuBar()
to set the main frame menubar to that declared in addmenu() .
if I add the following code to main() in the screen class the menu appears
Screen screen = new Screen(null);
f.setJMenuBar(screen.getMenuBar());

Similar Messages

  • Adding a JMenuBar to my JViewer

    I have a class, JViewer, that extends the JFrame class. When i call the following piece of code, the menubar, mb, should be placed in the JViewer, but it isn't there.
    JViewer viewer = (JViewer) getViewer();
    JMenuBar mb = getMenuBar();
    viewer.setMenuBar(mb);
    The setMenuBar in the JViewer code looks like the following
    public void setMenuBar(JMenuBar menu) {
    this.getContentPane().add(menu);
    I have already tried simply using the JFrame method setJMenuBar, but it also does not work.
    Any ideas???
    Stephen

    i know that the JMenuBar, mb, has all the necessary components in it, but it's just not being added using the line
    viewer.setMenuBar(mb);
    again, setMenuBar is
    public void setMenuBar(JMenuBar menu) {
         this.getContentPane().add(menu);
    and the code for JViewer is (but i don't think it will be of any use that much, except to confirm that i am extending JFrame). I also implement my own Viewer interface, which is also at the bottom.
    package com.bmw.nasa.gui;
    import java.awt.*;
    import java.beans.*;
    import java.awt.event.*;
    import com.bmw.nasa.gui.*;
    import com.bmw.nasa.global.*;
    import com.rsr.swing.UserInterfaceUtilities;
    import javax.swing.*;
    import javax.swing.event.EventListenerList;
    public class JViewer extends JFrame
    implements Viewer {
    JViewerPanel currentPanel;
         Dimension minimumSize = new Dimension(790, 568);
    /** event support*/
    private EventListenerList listenerList = new EventListenerList();
    JDialog aboutbox;
    //Construct the frame
    public JViewer() {
         this.setSize(new Dimension(790, 568));
         addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent e) {
              quit();
              public void windowClosed(WindowEvent e) {
              quit();
         addComponentListener( new ComponentAdapter() {
         public void componentResized(ComponentEvent e) {
              Component component = e.getComponent();
              Dimension currentSize = component.getSize();
              boolean adjust = false;
              if ( minimumSize != null ) {
              if ( currentSize.width < minimumSize.width ) {
                   currentSize.width = minimumSize.width;
                   adjust = true;
              if ( currentSize.height < minimumSize.height ) {
                   currentSize.height = minimumSize.height;
                   adjust = true;
              if ( adjust )
                   component.setSize(currentSize);
              //System.err.println("Rezized: " + currentSize + "," + component);
         // Create keystrokes and assign them
         // (1) F1 anywhere in the window
         this.getRootPane().registerKeyboardAction(
         new ActionListener() {
                   public void actionPerformed(ActionEvent evt) {
                   showVersionWindow();
         KeyStroke.getKeyStroke(KeyEvent.VK_V, Event.CTRL_MASK | Event.ALT_MASK , false),
         JComponent.WHEN_IN_FOCUSED_WINDOW
         try {
         this.getContentPane().setLayout(new BorderLayout());
         this.setTitle("NASA-iX");
         catch (Exception e) {
         e.printStackTrace();
    public void activate() {
         validate();
         if ( currentPanel != null )
         currentPanel.activate();
         setVisible(true);
    public void addViewerListener(ViewerListener l) {
         listenerList.add(ViewerListener.class, l);
    public void expose() {
         setVisible(true);
    public void fireViewerDone(ViewerEvent e) {
         // Guaranteed to return a non-null array
         Object[] listeners = listenerList.getListenerList();
         // Process the listeners last to first, notifying
         // those that are interested in this event
         for (int i = listeners.length-2; i>=0; i-=2) {
              if (listeners==ViewerListener.class) {
                   ((ViewerListener)listeners[i+1]).viewerDone(e);
    public void fireViewerStarted(ViewerEvent e) {
         // Guaranteed to return a non-null array
         Object[] listeners = listenerList.getListenerList();
         // Process the listeners last to first, notifying
         // those that are interested in this event
         for (int i = listeners.length-2; i>=0; i-=2) {
              if (listeners[i]==ViewerListener.class) {
                   ((ViewerListener)listeners[i+1]).viewerStarted(e);
    public Viewer getAnotherViewer() {
         JViewer viewer = new JViewer();
         viewer.setSize(getSize());
         return viewer;
    public void quit() {
         if (currentPanel != null) {
              currentPanel.quit();
         fireViewerDone(new ViewerEvent(this));
    public void removeViewerListener(ViewerListener l) {
         listenerList.remove(ViewerListener.class, l);
    public void setMenuBar(JMenuBar menu) {
         this.getContentPane().add(menu);
    public void setMinimumSize(Dimension minimumSize) {
         Dimension old = this.minimumSize;
         this.minimumSize = minimumSize;
         firePropertyChange("minimumSize", old, minimumSize);
    public void setPanel(JViewerPanel panel) {
         if (currentPanel!=null) {
              this.getContentPane().remove(currentPanel);
              if ( currentPanel instanceof TitleChangedListener )
                   currentPanel.removeTitleChangedListener(this);
         currentPanel = panel;
         this.getContentPane().add(currentPanel, BorderLayout.CENTER);
         String title = panel.getTitle();
         if ( title != null) {
              setTitle(title);          
         if (currentPanel instanceof TitleChangedListener )
              currentPanel.addTitleChangedListener(this);
         validate();
         repaint();
    public void showVersionWindow() {
         if ( aboutbox == null )
         aboutbox = new AboutBox(this,"Info", true);
         aboutbox.show();
    public void showVersionWindow1() {
    JFrame f = new JFrame("Version");
         f.show();
    public void titleChanged(TitleChangedEvent e) {
         this.setTitle(e.getTitle());
         repaint();
    //Viewer
    package com.bmw.nasa.gui;
    import java.awt.*;
    public interface Viewer extends TitleChangedListener {
         public void activate();
         public void addViewerListener(ViewerListener l);
         public void expose();
         public Viewer getAnotherViewer();
         public void quit();
         public void removeViewerListener(ViewerListener l);
         public void setPanel(JViewerPanel panel);
         public void setMenuBar(javax.swing.JMenuBar menu);

  • Adding a Panel to JApplet doesn't work properly

    Hi there,
    I have a class "Editor" extended from JPanel to edit some data. In my JApplet I added a JMenubar with setJMenubar() and registered an ActionListener to the menu items. Everything works fine except the displaying of the EditorPanel after choosing the menu item.
    When I'm adding the Panel in the constructor of the applet it is shown correctly.
    public class EditorApplet extends JApplet implements ActionListener
      public void init()
        setJMenuBar(createJMenuBar());
        Editor e = new Editor();
        getContentPane().add(e); // works perfectly
        e.load(2); // load data into editor
      public void actionPerformed(ActionEvent e)
        if (e.getActionCommand().equals("..."))
          Editor e = new Editor();
          e.loadObjects(1);
          getContentPane().removeAll();
          getContentPane().add(e); // nothing happens!?
          getContentPane().repaint(); // ???
          repaint(); // ???
        }What else needs to be done to display the 'new' Editor?

    Wait. You're adding an ActionEvent to your panel.
    I think you want to do "add(this.e)".

  • Need help with project

    Hi all I'm working on a project and need help.
    I want the "New" button to clear all the fields.
    Any help?
    =======================================================
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Message extends JFrame implements ActionListener {
         public Message() {
         super("Write a Message - by Kieran Hannigan");
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setSize(370,270);
         FlowLayout flo = new FlowLayout(FlowLayout.RIGHT);
         setLayout(flo);
         //Make the bar
         JMenuBar bar = new JMenuBar();
         //Make "File" on Menu
         JMenu File = new JMenu("File");
         JMenuItem f1 = new JMenuItem("New");
         JMenuItem f2 = new JMenuItem("Open");
         JMenuItem f3 = new JMenuItem("Save");
         JMenuItem f4 = new JMenuItem("Save As");
         JMenuItem f5 = new JMenuItem("Exit");
         File.add(f1);
         File.add(f2);
         File.add(f3);
         File.add(f4);
         File.add(f5);
         bar.add(File);
         //Make "Edit" on menu
         JMenu Edit = new JMenu("Edit");
         JMenuItem e1 = new JMenuItem("Cut");
         JMenuItem e2 = new JMenuItem("Paste");
         JMenuItem e3 = new JMenuItem("Copy");
         JMenuItem e4 = new JMenuItem("Repeat");
         JMenuItem e5 = new JMenuItem("Undo");
         Edit.add(e5);
         Edit.add(e4);
         Edit.add(e1);
         Edit.add(e3);
         Edit.add(e2);
         bar.add(Edit);
         //Make "View" on menu
         JMenu View = new JMenu("View");
         JMenuItem v1 = new JMenuItem("Bold");
         JMenuItem v2 = new JMenuItem("Italic");
         JMenuItem v3 = new JMenuItem("Normal");
         JMenuItem v4 = new JMenuItem("Bold-Italic");
         View.add(v1);
         View.add(v2);
         View.add(v3);
         View.addSeparator();
         View.add(v4);
         bar.add(View);
         //Make "Help" on menu
         JMenu Help = new JMenu("Help");
         JMenuItem h1 = new JMenuItem("Help Online");
         JMenuItem h2 = new JMenuItem("E-mail Programmer");
         Help.add(h1);
         Help.add(h2);
         bar.add(Help);
         setJMenuBar(bar);
         //Make Contents of window.
         //Make "Subject" text field
         JPanel row2 = new JPanel();
         JLabel sublabel = new JLabel("Subject:");
         row2.add(sublabel);
         JTextField text2 = new JTextField("RE:",24);
         row2.add(text2);
         //Make "To" text field
         JPanel row1 = new JPanel();
         JLabel tolabel = new JLabel("To:");
         row1.add(tolabel);
         JTextField text1 = new JTextField(24);
         row1.add(text1);
         //Make "Message" text area
         JPanel row3 = new JPanel();
         JLabel Meslabel = new JLabel("Message:");
         row3.add(Meslabel);
         JTextArea text3 = new JTextArea(6,22);
         messagearea.setLineWrap(true);
         messagearea.setWrapStyleWord(true);
         JScrollPane scroll = new JScrollPane(text3,
                                  JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                  JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
         row3.add(scroll);
         add(row1);
         add(row2);
         add(row3);
         setVisible(true);
         public static void main(String[] arguments)  {
         Message Message = new Message();
    }

    Ok, given that I may have not been the kindest to you on the other thread (and I'm still annoyed that you went and cross-posted this), and that you did actually use code tags, I'm going to post some code here:
    Please take the following advice onboard though.
    1. When you are naming your artifacts, please use the java coding standard as your guide. So if you are naming a class you use a capital letter first, and use camel case thereafter. All method names begin with a lower case letter, and all variable names begin with a lower case letter (and again camel case after that)
    2. Please use self explanitory names (for everything), so no more row1, row2, or text1, text2, etc.
    3. The example I am giving below makes use of a single class to handle all actions, this is not really the best way to do this, and a better way would be to have a class to handle each action (that would remove the massive if() else if() in the action handler class.
    4. When you are using class variables they should be private (no exceptions, ever!), if you need to access them from other classes use accessors (eclipse and other IDE tools can generate these methods for you in seconds)
    5. Notice the naming convention for my constants (final statics), they are all upper case (again from the java coding standards document, which you are going to look for with google right?)
    6. I have hived some of the creation work to helper methods (the getSubjectTextField() etc), although it isn't advisable to be calling other methods from the constructor, since this is a GUI, and you want it to appear as soon as you create the class, we won't worry about this, but perhaps as an execrise you could work out a better way to do this?
    7. Personally, I don't like classes that implement listeners, unless they are specifically designed to do that job. So a Frame that is set up as an action listener is fine, provided the actions it listens for are associated with the frame, not its contents. If the actions are related to its contents, then a dedicated class is better.
    8. Another personal opinion, but I feel it makes code clearer, but others may disagree. If you are creating a variable solely to hold the result of a calculation, to be passed to a method in the very next line, then don't create the variable, just pass the method as the argument to the method (feel free to ignore this advice if the method call is extremely long, and a local would make it easier to read)
    Anyway, here is the code. I have removed most of the menu items, and leave this as an exercise for you. Also I have only created 2 methods (new and exit), I'll again leave it as an exercise for you to complete this.
    package jdc;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import javax.swing.AbstractAction;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.ScrollPaneConstants;
    public class Message extends JFrame {
        /** Constant for the new action command. */
        private static final String NEW_COMMAND = "New";
        /** Constant for the exit action command. */
        private static final String EXIT_COMMAND = "Exit";
        /** Subject text field. */
        private JTextField subjectTextField;
        /** Recipient text field. */
        private JTextField toTextField;
        /** Message text area. */
        private JTextArea messageTextArea;
        public Message() {
            super("Write a Message - by Kieran Hannigan");
            setSize(370, 270);
            FlowLayout flo = new FlowLayout(FlowLayout.RIGHT);
            setLayout(flo);
            setJMenuBar(createMenuBar());
            // Add "Subject" text field
            JPanel subjectRow = new JPanel();
            subjectRow.add(new JLabel("Subject:"));
            subjectRow.add(getSubjectTextField());
            // Add "To" text field
            JPanel toRow = new JPanel();
            toRow.add(new JLabel("To:"));
            toRow.add(getToTextField());
            // Make "Message" text area
            JPanel messageRow = new JPanel();
            JScrollPane scroll = new JScrollPane(getMessageTextArea(), ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            messageRow.add(scroll);
            add(toRow);
            add(subjectRow);
            add(messageRow);
            setVisible(true);
         * Clear all the fields.
        public void createNewMessage() {
            getSubjectTextField().setText("");
            getToTextField().setText("");
            getMessageTextArea().setText("");
         * Exit the application.
        public void exitApplication() {
            if (JOptionPane.showConfirmDialog(this, "Are you sure you would like to exit now?", "Exit",
                    JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                System.exit(0);
         * @return The subject text field, (creates a new one if it doesn't already exist)
        private JTextField getSubjectTextField() {
            if (this.subjectTextField == null) {
                this.subjectTextField = new JTextField("RE:", 24);
            return this.subjectTextField;
         * @return The to text field, (creates a new one if it doesn't already exist)
        private JTextField getToTextField() {
            if (this.toTextField == null) {
                this.toTextField = new JTextField(24);
            return this.toTextField;
         * @return The message text area, (creates a new one if it doesn't already exist
        private JTextArea getMessageTextArea() {
            if (this.messageTextArea == null) {
                this.messageTextArea = new JTextArea(6, 22);
                this.messageTextArea.setLineWrap(true);
                this.messageTextArea.setWrapStyleWord(true);
            return this.messageTextArea;
         * Helper method to create the menu bar.
         * @return Menu bar with all menus and menu items added
        private JMenuBar createMenuBar() {
            JMenuBar bar = new JMenuBar();
            JMenu fileMenu = new JMenu("File");
            fileMenu.add(new JMenuItem(new MenuItemAction(this, NEW_COMMAND)));
            fileMenu.add(new JMenuItem(new MenuItemAction(this, EXIT_COMMAND)));
            bar.add(fileMenu);
            // TODO add all other menu's and menu items here....
            return bar;
         * Private static class to handle all menu item actions.
        private static class MenuItemAction extends AbstractAction {
            /** Instance of the message class. */
            private Message message;
             * @param actionName
            public MenuItemAction(Message messageFrame, String actionName) {
                super(actionName);
                this.message = messageFrame;
             * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
            public void actionPerformed(ActionEvent e) {
                if (e.getActionCommand().equals(NEW_COMMAND)) {
                    this.message.createNewMessage();
                } else if (e.getActionCommand().equals(EXIT_COMMAND)) {
                    this.message.exitApplication();
                // TODO Add the other event handlers here
        public static void main(String[] arguments) {
            Message messageFrame = new Message();
            messageFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }If you have any questions, please let me know, as there are a number of new areas introduced that you may not have come across before.

  • Help with JRadioButton

    Could someone help me with trying to have an image rather than text on a radio button. I can make a radio button with text, but when I try to use an Icon rather than text for a label there is no button created. My code is below. Thanks.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class appTag extends JApplet
         JLabel     serviceInfoL,
              welcomeLabel,
              nameLabel,
              addressLabel,
              cityLabel,
              stateLabel,
              zipLabel,
              emailLabel,
              phoneNoLabel,
              cctypeLabel1,
              cctypeLabel2,
              cctypeLabel3,
              cctypeLabel4,
              ccNoLabel,
              ccExpLabel,
         ConnectL,
                   sIconL1,
                   sIconL2,
         sIconL3;
    JTextField nameTf,
                   addressTf,
                        cityTf,
                        stateTf,
                        zipTf,
                        emailTf,
                        phoneNoTf;
         JPasswordField ccNo,
                        expDate;
         JButton orderButton,
                        clearButton;
         JCheckBox service1,
                        service2,
                        service3;
         ButtonGroup radioGroup;
         JRadioButton Discovertype,
                        Visatype,
                        MCtype,
                        AEtype;
         JComboBox compTypePC,
                        compTypeApple,
                        compTypeLinux;
    Icon          EagleNet,
                   service1Icon,
                   service2Icon,
                   service3Icon,
                   ccIcon1,
                   ccIcon2,
                   ccIcon3,
                   ccIcon4;
    //Icon Connect;
    public void init ()
         // define GUI components
         JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.BOTTOM);
         JPanel pane = new JPanel ();
         JPanel secondPane = new JPanel();
         JPanel thirdPane = new JPanel();
         JPanel fourthPane = new JPanel();
         EagleNet = new ImageIcon("hosting2.jpg");
         service1Icon = new ImageIcon("connect.gif");
         service2Icon = new ImageIcon("2_computers.gif");
         service3Icon = new ImageIcon("WWW.gif");
         ccIcon1 = new ImageIcon("visa.jpg");
         ccIcon2 = new ImageIcon("mastercard.jpg");
         ccIcon3 = new ImageIcon("americanexpress.jpg");
         ccIcon4 = new ImageIcon("discovernovus.jpg");
         //needs to be resized to fit applet
         nameTf = new JTextField(12);
         addressTf = new JTextField(12);
         cityTf = new JTextField(12);
         stateTf = new JTextField(2);
         zipTf = new JTextField(5);
         emailTf = new JTextField(15);
         phoneNoTf = new JTextField(10);
         ccNo = new JPasswordField(16);
         expDate = new JPasswordField(4);
         ccNo.setEchoChar('#');
         expDate.setEchoChar('#');
         Discovertype = new JRadioButton(ccIcon1,false);
         Visatype = new JRadioButton(ccIcon2,false);
         MCtype = new JRadioButton(ccIcon3,false);
         AEtype = new JRadioButton(ccIcon4,false);
         radioGroup = new ButtonGroup ();
         radioGroup.add(Discovertype);
         radioGroup.add(Visatype);
         radioGroup.add(MCtype);
         radioGroup.add(AEtype);
         cctypeLabel1 = new JLabel(ccIcon1);
         cctypeLabel2 = new JLabel(ccIcon2 );
         cctypeLabel3 = new JLabel(ccIcon3);
         cctypeLabel4 = new JLabel(ccIcon4);
         sIconL1 = new JLabel(service1Icon);
         sIconL2 = new JLabel(service2Icon);
         sIconL3 = new JLabel(service3Icon);
         ConnectL = new JLabel(EagleNet);
         welcomeLabel = new JLabel("We are located @ 9A N. Zetterowe Avenue Statesboro, GA 30458");
         serviceInfoL = new JLabel("Please pick the service(s) you are interested in purchasing.");
         // build the GUI layout
         pane.add(ConnectL);
         pane.add(welcomeLabel);
         //pane.add (Connect);
         //build second Pane
         tabbedPane.add("Welcome to EagleNet",pane);
         tabbedPane.add("Services", secondPane);
         tabbedPane.add("Customer Info", thirdPane);
         tabbedPane.add("Receipt", fourthPane);
         this.setContentPane (tabbedPane);
         //adding menubar
         JMenuBar menuBar = new JMenuBar();
         JMenu fileMenu = new JMenu("File");
         JMenu editMenu = new JMenu("Edit");
         JMenu toolMenu = new JMenu("Tool");
         JMenu helpMenu = new JMenu("Help");
         JMenuItem openItem = new JMenuItem("Open");
         JMenuItem saveItem = new JMenuItem("Save");
         JMenuItem quitItem = new JMenuItem("Quit");
         JMenuItem clearItem = new JMenuItem("Clear");
         JMenuItem versionItem = new JMenuItem("Version");
         fileMenu.add(openItem);
         fileMenu.add(saveItem);
         fileMenu.add(quitItem);
         editMenu.add(clearItem);
         helpMenu.add(versionItem);
         menuBar.add(fileMenu);
         menuBar.add(editMenu);
         menuBar.add(toolMenu);
         menuBar.add(helpMenu);
         setJMenuBar(menuBar);
         //make secondPane
         secondPane.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 20));
         secondPane.add(serviceInfoL);
         //secondPane.
         secondPane.add(sIconL1);
         secondPane.add(service1 = new JCheckBox("Internet Access @ $18.95/month"));
         secondPane.add(sIconL2);
         secondPane.add(service2 = new JCheckBox("Wireless Network @ $150.00"));
    secondPane.add(sIconL3);
         secondPane.add(service3 = new JCheckBox("Web_Hosting @ $50.00/month"));
         //make third pane
         thirdPane.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 20));
         //thirdPane.setLayout(new BorderLayout(5,10));
         thirdPane.add(welcomeLabel);
         thirdPane.add(addressTf);
         thirdPane.add(cityTf);
         thirdPane.add(stateTf);
         thirdPane.add(zipTf);
         thirdPane.add(emailTf);
         thirdPane.add(phoneNoTf);
         thirdPane.add(ccNo);
         thirdPane.add(expDate);
         thirdPane.add(Discovertype);
         thirdPane.add(Visatype);
         thirdPane.add(MCtype);
         thirdPane.add(AEtype);
    }

    A button is actually getting created, just not the way you would assume. The documentation isn't very clear on this matter. A JRadioButton (and JCheckBox too) actually consist of two (optional) parts: an icon and text. The icon is the little cirle that is either selected or unselected, depending on the state of the button and the text is whatever text you wish to accompany the button describing its purpose. So, when you specify an Icon, you are actually replacing the default unselected icon (the little unselected circle). If you do this, you also need to call setSelectedIcon() and specify an icon to replace the default selected icon (the little selected circle). This is a bit silly, but that's the API.
    To accomplish what you want, I'd suggest placing a JRadioButton and a JLabel (containing the Icon) next to one another.
    HTHs,
    Jamie

  • Adding a JButton when there's a paint method

    I'm creating a game application, sort of like a maze, and I want to add buttons to the levelOne panel to be able to move around the maze. When I add the buttons to the panel they don't appear, I assume the paint method is the reason for this. here's my code, I have 3 files, ill post the user_interface, and the levels class, where the level is created and where i tried to add the button. I tried putting the buttons in a JOptionPane, but then my JMenu wouldn't work at the same time the OptionPane was opened. If anyone knows a way around this instead, please let me know. I also tried using a separate class with a paintComponent method in it, and then adding the button (saw on a forum, not sure if it was this one), but that didn't work either. Also, if there is a way just to simply have the user press the directional keys on the keyboard and have the program perform a certain function when certain keys are pressed, I'd like to know, as that would solve my whole problem. Thanks.
    //Libraries
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    public class User_Interface extends JFrame
    static Levels l = new Levels ();
    static Delay d = new Delay ();
    private Container contentPane = getContentPane ();
    private JPanel main, levelOne;
    private String level;
    private CardLayout cc = new CardLayout ();
    private GridBagConstraints gbc = new GridBagConstraints ();
    private JPanel c = new JPanel ();
    private String label = "MainMenu";
    public User_Interface ()
    //Generates the User-Interface
    super ("Trapped");
    main = new JPanel ();
    GridBagLayout gbl = new GridBagLayout ();
    main.setLayout (gbl);
    c.setLayout (cc);
    // set_gbc (gbc, 2, 2, 5, 5, GridBagConstraints.NONE);
    c.add (main, "Main Page");
    contentPane.add (c, BorderLayout.CENTER);
    cc.show (c, "Main Page");
    levelOne = new JPanel ();
    levelOne.setLayout (new GridBagLayout ());
    levelOne.setBackground (Color.black);
    c.add (levelOne, "LevelOne");
    JMenuBar menu = new JMenuBar ();
    JMenu file = new JMenu ("File");
    JMenu help = new JMenu ("Help");
    JMenuItem about = new JMenuItem ("About");
    JMenuItem mainmenu = new JMenuItem ("Main Menu");
    mainmenu.addActionListener (
    new ActionListener ()
    public void actionPerformed (ActionEvent event)
    cc.show (c, "Main Page");
    label = "MainMenu";
    JMenuItem newGame = new JMenuItem ("New Game");
    newGame.addActionListener (
    new ActionListener ()
    public void actionPerformed (ActionEvent event)
    l.xCord = 2;
    l.yCord = 2;
    l.xLoc = 140;
    l.yLoc = 140;
    JPanel entrance = new JPanel ();
    entrance.setLayout (new FlowLayout ());
    c.add (entrance, "Entrance");
    label = "Entrance";
    level = "ONE";
    cc.show (c, "Entrance");
    JMenuItem loadgame = new JMenuItem ("Load Game");
    JMenuItem savegame = new JMenuItem ("Save Game");
    JMenuItem exit = new JMenuItem ("Exit");
    exit.addActionListener (
    new ActionListener ()
    public void actionPerformed (ActionEvent event)
    JFrame frame = new JFrame ();
    frame.setLocation (10, 10);
    JOptionPane.showMessageDialog (frame, "Come Back Soon!", "TRAPPED", JOptionPane.INFORMATION_MESSAGE);
    System.exit (0);
    file.add (about);
    file.add (mainmenu);
    file.add (newGame);
    file.add (loadgame);
    file.add (savegame);
    file.add (exit);
    menu.add (file);
    menu.add (help);
    setJMenuBar (menu);
    //Sets the size of the container (columns by rows)
    setSize (750, 550);
    //Sets the location of the container
    setLocation (10, 10);
    //Sets the background colour to a dark blue colour
    main.setBackground (Color.black);
    //Makes the container visible
    setVisible (true);
    public void paint (Graphics g)
    super.paint (g);
    g.setColor (Color.white);
    if (label == "MainMenu")
    for (int x = 0 ; x <= 50 ; ++x)
    g.setColor (Color.white);
    g.setFont (new Font ("Arial", Font.BOLD, x));
    g.drawString ("T R A P P E D", 100, 125);
    d.delay (10);
    if (x != 50)
    g.setColor (Color.black);
    g.drawString ("T R A P P E D", 100, 125);
    if (label == "Entrance")
    l.Entrance ("ONE", g);
    label = "LevelOne";
    if (label == "LevelOne")
    l.LevelOne (g, levelOne, gbc);
    label = "";
    public static void main (String[] args)
    // calls the program
    User_Interface application = new User_Interface ();
    application.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    } //End of Main Method
    //Libraries
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Levels extends Objects
    private JFrame frame = new JFrame ();
    //Sets location, size, and visiblity to the frame where the JOptionPane
    //will be placed
    frame.setLocation (600, 600);
    frame.setSize (1, 1);
    frame.setVisible (false);
    public int xCord = 2;
    public int yCord = 2;
    public void LevelOne (Graphics g, JPanel one, GridBagConstraints gbc)
    ***Trying to add the button, doesn't appear. Tried adding to the container, and any JPanel i had created***
    JButton button1 = new JButton ("TEST");
    one.add (button1);
    g.setColor (Color.white);
    g.fillRect (500, 100, 200, 300);
    g.setColor (Color.black);
    g.drawRect (500, 100, 200, 300);
    g.setFont (new Font ("Verdana", Font.BOLD, 25));
    g.setColor (Color.black);
    g.drawString ("LEVEL ONE", 525, 80);
    //ROW ONE
    counter = -80;
    counter2 = 200;
    for (int a = 1 ; a <= 7 ; ++a)
    if (xCord < a && yCord == 0)
    g.setColor (darkGray);
    g.fillRect (xLoc + counter, yLoc - 80, 40, 40);
    g.setColor (Color.black);
    g.drawRect (xLoc + counter, yLoc - 80, 40, 40);
    if (xCord > a - 1 && yCord == 0)
    g.setColor (darkGray);
    g.fillRect (xLoc + counter2, yLoc - 80, 40, 40);
    g.setColor (Color.black);
    g.drawRect (xLoc + counter2, yLoc - 80, 40, 40);
    counter += 40;
    counter2 += 40;
    *****Theres 9 more rows, just edited out to save space****
    int y = 100;
    int x = 100;
    for (int a = 0 ; a < 20 ; ++a)
    g.setColor (Color.white);
    g.fillRoundRect (x, y, 40, 40, 5, 5);
    g.setColor (Color.black);
    g.drawRoundRect (x, y, 40, 40, 5, 5);
    y += 40;
    if (a == 9)
    x += 320;
    y = 100;
    x = 140;
    y = 100;
    for (int a = 0 ; a < 14 ; ++a)
    g.setColor (Color.white);
    g.fillRoundRect (x, y, 40, 40, 5, 5);
    g.setColor (Color.black);
    g.drawRoundRect (x, y, 40, 40, 5, 5);
    x += 40;
    if (a == 6)
    x = 140;
    y += 360;
    g.setColor (Color.black);
    g.drawRect (100, 100, 360, 400);
    ImageIcon[] images = new ImageIcon [4];
    images [0] = new ImageIcon ("arrow_left.gif");
    images [1] = new ImageIcon ("arrow_up.gif");
    images [2] = new ImageIcon ("arrow_down.gif");
    images [3] = new ImageIcon ("arrow_right.gif");
    int direction = -1;
    *****This is where I tried to have the OptionPane show the directional buttons******
    //frame.setVisible (true);
    // direction = JOptionPane.showOptionDialog (frame, "Choose Your Path:", "Trapped", JOptionPane.YES_NO_CANCEL_OPTION,
    // JOptionPane.QUESTION_MESSAGE,
    // null,
    // images,
    // images [3]);
    // if (direction == 0)
    // if (xCord - 1 > 0)
    // xCord -= 1;
    // xLoc += 40;
    // if (direction == 1)
    // if (yCord - 1 > 0)
    // yCord -= 1;
    // yLoc += 40;
    // if (direction == 2)
    // if (yCord + 1 < 9)
    // yCord += 1;
    // yLoc -= 40;
    // if (direction == 3)
    // if (xCord + 1 < 13)
    // xCord += 1;
    // xLoc -= 40;
    //LevelOne (g, one, gbc);
    }

    i tried adding a keylistener, that didn't work too well, i had tried to add it to a button and a textarea which i added to the 'one' frame, it didn't show up, and it didn't work. How would i go about changing the paint method so that it doesn't contain any logic? That's the only way I could think of getting the program to move forward in the game. Thanks.
    //Libraries
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    public class User_Interface extends JFrame
        static Levels l = new Levels ();
        static Delay d = new Delay ();
        private Container contentPane = getContentPane ();
        private JPanel main, levelOne;
        private String level;
        private CardLayout cc = new CardLayout ();
        private GridBagConstraints gbc = new GridBagConstraints ();
        private JPanel c = new JPanel ();
        private String label = "MainMenu";
        public User_Interface ()
            //Generates the User-Interface
            super ("Trapped");
            main = new JPanel ();
            GridBagLayout gbl = new GridBagLayout ();
            main.setLayout (gbl);
            c.setLayout (cc);
            // set_gbc (gbc, 2, 2, 5, 5, GridBagConstraints.NONE);
            c.add (main, "Main Page");
            contentPane.add (c, BorderLayout.CENTER);
            cc.show (c, "Main Page");
            levelOne = new JPanel ();
            levelOne.setLayout (new GridBagLayout ());
            levelOne.setBackground (Color.black);
            c.add (levelOne, "LevelOne");
            JMenuBar menu = new JMenuBar ();
            JMenu file = new JMenu ("File");
            JMenu help = new JMenu ("Help");
            JMenuItem about = new JMenuItem ("About");
            JMenuItem mainmenu = new JMenuItem ("Main Menu");
            mainmenu.addActionListener (
                    new ActionListener ()
                public void actionPerformed (ActionEvent event)
                    cc.show (c, "Main Page");
                    label = "MainMenu";
            JMenuItem newGame = new JMenuItem ("New Game");
            newGame.addActionListener (
                    new ActionListener ()
                public void actionPerformed (ActionEvent event)
                    l.xCord = 2;
                    l.yCord = 2;
                    l.xLoc = 140;
                    l.yLoc = 140;
                    JPanel entrance = new JPanel ();
                    entrance.setLayout (new FlowLayout ());
                    c.add (entrance, "Entrance");
                    label = "Entrance";
                    level = "ONE";
                    cc.show (c, "Entrance");
            JMenuItem loadgame = new JMenuItem ("Load Game");
            JMenuItem savegame = new JMenuItem ("Save Game");
            JMenuItem exit = new JMenuItem ("Exit");
            exit.addActionListener (
                    new ActionListener ()
                public void actionPerformed (ActionEvent event)
                    JFrame frame = new JFrame ();
                    frame.setLocation (10, 10);
                    JOptionPane.showMessageDialog (frame, "Come Back Soon!", "TRAPPED", JOptionPane.INFORMATION_MESSAGE);
                    System.exit (0);
            file.add (about);
            file.add (mainmenu);
            file.add (newGame);
            file.add (loadgame);
            file.add (savegame);
            file.add (exit);
            menu.add (file);
            menu.add (help);
            setJMenuBar (menu);
            //Sets the size of the container (columns by rows)
            setSize (750, 550);
            //Sets the location of the container
            setLocation (10, 10);
            //Sets the background colour to a dark blue colour
            main.setBackground (Color.black);
            //Makes the container visible
            setVisible (true);
        public void paint (Graphics g)
            super.paint (g);
            g.setColor (Color.white);
            if (label == "MainMenu")
                for (int x = 0 ; x <= 50 ; ++x)
                    g.setColor (Color.white);
                    g.setFont (new Font ("Arial", Font.BOLD, x));
                    g.drawString ("T    R    A    P    P    E    D", 100, 125);
                    d.delay (10);
                    if (x != 50)
                        g.setColor (Color.black);
                        g.drawString ("T    R    A    P    P    E    D", 100, 125);
            if (label == "Entrance")
                l.Entrance ("ONE", g);
                label = "LevelOne";
            if (label == "LevelOne")
                l.LevelOne (g, levelOne, gbc);
                label = "";
            //g.setColor (new Color
        public static void main (String[] args)
            // calls the program
            User_Interface application = new User_Interface ();
            application.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        } //End of Main Method
    //Libraries
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.ActionMap;
    import javax.swing.plaf.*;
    public class Levels extends Objects
        implements KeyListener
        //static final String newline = System.getProperty ("line.separator");
        JButton button;
        private JFrame frame = new JFrame ();
            //Sets location, size, and visiblity to the frame where the JOptionPane
            //will be placed
            frame.setLocation (600, 600);
            frame.setSize (1, 1);
            frame.setVisible (false);
        JButton button1;
        public int xCord = 2;
        public int yCord = 2;
        public void LevelOne (Graphics g, JPanel one, GridBagConstraints gbc)
        //    button = new JButton ("TEST");
        //    ButtonHandler handler = new ButtonHandler ();
         //   button.addActionListener (handler);
          //  one.add (button);
            g.setColor (Color.white);
            g.fillRect (500, 100, 200, 300);
            g.setColor (Color.black);
            g.drawRect (500, 100, 200, 300);
            g.setFont (new Font ("Verdana", Font.BOLD, 25));
            g.setColor (Color.black);
            g.drawString ("LEVEL ONE", 525, 80);
            //ROW ONE
            counter = -80;
            counter2 = 200;
            for (int a = 1 ; a <= 7 ; ++a)
                if (xCord < a && yCord == 0)
                    g.setColor (darkGray);
                    g.fillRect (xLoc + counter, yLoc - 80, 40, 40);
                    g.setColor (Color.black);
                    g.drawRect (xLoc + counter, yLoc - 80, 40, 40);
                if (xCord > a - 1 && yCord == 0)
                    g.setColor (darkGray);
                    g.fillRect (xLoc + counter2, yLoc - 80, 40, 40);
                    g.setColor (Color.black);
                    g.drawRect (xLoc + counter2, yLoc - 80, 40, 40);
                counter += 40;
                counter2 += 40;
            int y = 100;
            int x = 100;
            for (int a = 0 ; a < 20 ; ++a)
                g.setColor (Color.white);
                g.fillRoundRect (x, y, 40, 40, 5, 5);
                g.setColor (Color.black);
                g.drawRoundRect (x, y, 40, 40, 5, 5);
                y += 40;
                if (a == 9)
                    x += 320;
                    y = 100;
            x = 140;
            y = 100;
            for (int a = 0 ; a < 14 ; ++a)
                g.setColor (Color.white);
                g.fillRoundRect (x, y, 40, 40, 5, 5);
                g.setColor (Color.black);
                g.drawRoundRect (x, y, 40, 40, 5, 5);
                x += 40;
                if (a == 6)
                    x = 140;
                    y += 360;
            g.setColor (Color.black);
            g.drawRect (100, 100, 360, 400);
            ImageIcon[] images = new ImageIcon [4];
            images [0] = new ImageIcon ("arrow_left.gif");
            images [1] = new ImageIcon ("arrow_up.gif");
            images [2] = new ImageIcon ("arrow_down.gif");
            images [3] = new ImageIcon ("arrow_right.gif");
            int direction = -1;
            //frame.setVisible (true);
            // direction = JOptionPane.showOptionDialog (frame, "Choose Your //\Path:", "Trapped", JOptionPane.YES_NO_CANCEL_OPTION,
            //         JOptionPane.QUESTION_MESSAGE,
            //         null,
            //         images,
            //         images [3]);
            // if (direction == 0)
            //     if (xCord - 1 > 0)
            //         xCord -= 1;
            //         xLoc += 40;
            // if (direction == 1)
            //     if (yCord - 1 > 0)
            //         yCord -= 1;
            //         yLoc += 40;
            // if (direction == 2)
            //     if (yCord + 1 < 9)
            //         yCord += 1;
            //         yLoc -= 40;
            // if (direction == 3)
            //     if (xCord + 1 < 13)
            //         xCord += 1;
            //         xLoc -= 40;
            one.addKeyListener (this);
            // one.add (button1);
            if (xCord == 1)
                LevelOne (g, one, gbc);
        /** Handle the key typed event from the text field. */
        public void keyTyped (KeyEvent e)
        /** Handle the key pressed event from the text field. */
        public void keyPressed (KeyEvent e)
            if (e.getSource () == "Up")
                JOptionPane.showMessageDialog (null, "Hi", "Hi", 0, null);
        /** Handle the key released event from the text field. */
        public void keyReleased (KeyEvent e)
            // displayInfo (e, "KEY RELEASED: ");
    }

  • Adding JMenu directly to a JPanel

    I am trying to add a JMenu directly to a JPanel, but it isn't functioning properly. It shows up, and looks the way I expect (with an arrow, like a sub-menu), but it doesn't display its popup menu when clicked. If I add the menu to a JMenuBar, and add that to the panel, it works, but the popup drops down below the button instead of to the right, and the arrow disappears. JMenuBar appears to be adding its own actions to every menu that it contains. JMenu is a descendant of AbstractButton, so I figured it would behave like one, but no luck.
    Any help would be appreciated. By the way, I have thought of using a JButton and a JPopupMenu together, but that is not a very elegant solution. I am looking for a way to make the JMenu behave as if it were in a JMenuBar.

    Hello Vijesh
    See the code below and tell me whether it is useful ?
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class SwingA implements ActionListener
    JPopupMenu pop;
    JFrame frame;
    JPanel panel;
    JButton cmdPop;
         public static void main(String[] args)
         SwingA A=new SwingA();
         SwingA()
                   frame=new JFrame("PopUp");
                   frame.setSize(600,480);
                   frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
                   pop=new JPopupMenu();
                   cmdPop=new JButton("Click");
                   cmdPop.addActionListener(this);
    JMenuItem item = new JMenuItem("First");
    JMenuItem item1 = new JMenuItem("Second");
    pop.add(item);
    pop.add(item1);
                   panel=new JPanel();
                   panel.add(cmdPop);
                   frame.getContentPane().add(panel);
                   frame.setVisible(true);
         public void actionPerformed(ActionEvent source)
    pop.show(cmdPop, cmdPop.getWidth(), 0);
    kanad

  • JMenuBar setFont problem.

    Hi, I'm trying to change font for my menu bar, but it takes no effect.
    Actually, my purpose is to set normal(not bold) font for menu.
    Code:
    JMenuBar menu=new JMenuBar();
    menu.setFont(new Font("Serif", Font.PLAIN, 12));
    //Adding menu items to the menubar.
    I have tried to change font of menu items but it took no effect either.
    Can anybody help me?
    Thanks.

    Setting the font on the individual menu items should hve worked unless you don't have the specified font installed on your sytem.
    However, if you want to change the font globally, use
    UIManager.put(MenuItem.font, yourFont);
    UIManager.put(Menu.font, yourFont);
    This will change the fonts for all menus and menu items to whatever font you specify.
    Sai Pullabhotla

  • Adding a panel to a frame

    Hi! All,
    I'm new to java and i have a little problem here. I have created a frame and i want to put two panels inside it. well, i managed to put the first one, but i'm having problems with the second one. I want this second one to be added when I click on a button.
    The button that I will click is the new JButton i have defined. it is called draw. I really do not know what the problem is. I will apprecite any help. Below is my code.
    // My Code.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.util.*;
    public class Main extends JFrame {
    //all components I'll need
    public JButton draw;
    public JButton addFormula;
    public JButton modelCheck;
    /** Creates a new instance of Main */
    public Main () {
    super("Graphical Model Checker for Knowledge");
    //content pane is the main panel where i'll put everything
    JPanel contentPane = new JPanel();
    draw = new JButton("Draw");
    draw.addActionListener(
    new ActionListener() {         
    public void actionPerformed(ActionEvent event) {
    if(event.getActionComman().equals"Draw")) {               
    JPanel drawing = new JPanel();
    drawing.setBackground(Color.BLUE);
    drawing.setSize(100, 100);
    drawing.setLayout(new FlowLayout
    FlowLayout.CENTER));
    add("North", drawing);
    drawing.setVisible(true);
    contentPane.add(draw);
    addFormula = new JButton("Add Formula");
    contentPane.add(addFormula);
    modelCheck = new JButton("Model Check");
    contentPane.add(modelCheck);
    Canvas canvas = new Canvas();
    canvas.setSize(40, 40);
    canvas.setBackground(Color.white);
    contentPane.add(canvas);
    repaint();
    //add panel to the frame
    add("South", contentPane);
    //colours for window
    contentPane.setBackground(Color.yellow);
    //set layout manager
    contentPane.setLayout(new FlowLayout(FlowLayout.LEFT));
    addWindowListener(new CloseWindow());
    pack();
    setVisible(true);
    String [] fileItems = {"Open", "Save", "Rename"};
    String [] editItems = {"Copy", "Cut", "Paste"};
    //instantiate a menu bar object
    JMenuBar bar = new JMenuBar();
    JMenu file = new JMenu("File");
    for (int index=0; index != fileItems.length; index++)
    file.add(fileItems[index]);
    bar.add(file);
    setJMenuBar(bar);
    JMenu edit = new JMenu("Edit Graph");
    for (int index=0; index != editItems.length; index++)
    edit.add(editItems[index]);
    bar.add(edit);
    setJMenuBar(bar);
    public static void main(String args []) {
    JFrame window = new Main();
    }

    Don't forget to use the "Code Formatting Tags",
    see http://forum.java.sun.com/help.jspa?sec=formatting,
    so the posted code retains its original formatting.
    add("North", drawing); The "North" means nothing when adding a component to a panel using a FlowLayout. You should just be using:
    add( drawing );After you add the component to the container you need to use:
    frame.validate();

  • Re: adding canvas to applet

    Hi
    I am trying to add a canvas to an applet. I am successful in doing so. There is a JMenuBar added to the applet. when I click on the file menu The contents are being displayed behind the canvas and as a result I am neither able to see the buttons nor select them. Could some one help me with this.
    Note: Once you compile the code you wouldn't be able to see the contents right away. Click on left top,immidiately below the applet menu. This will repaint the contentpane. This is some thing I am working on.
    applet class
    package aple;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Shape;
    import java.awt.geom.AffineTransform;
    import java.util.ArrayList;
    import javax.swing.JApplet;
    public class NewJApplet extends JApplet{
        public Graphics2D g2;
        AffineTransform atf = new AffineTransform();
        sketch sk = new sketch();   
            @Override
        public void init() {      
            getContentPane().add(sk);
           Gui gui = new Gui();
            // menubar
            this.setJMenuBar(gui.Gui());     
        @Override
    gui class
    package aple;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    public class Gui {
        JMenuBar menuBar;
        JMenu file,edit,insert,view,draw,circle;
        JMenuItem nu,close,saveAs,open,centreandradius,line,rectangle,point,arc;
        public JMenuBar Gui(){
            //Menubar
            menuBar = new JMenuBar();
            //Menus
            file = new JMenu("File");
            menuBar.add(file);
            edit = new JMenu("Edit");
            menuBar.add(edit);
            view = new JMenu("View");
            menuBar.add(view);
            insert = new JMenu("Insert");       
            draw = new JMenu("Draw");
            circle = new JMenu("Circle");
            draw.add(circle);
            insert.add(draw);       
            menuBar.add(insert);
            //MenuItems
            nu = new JMenuItem("New");
            file.add(nu);
            open = new JMenuItem("Open");
            file.add(open);
            saveAs = new JMenuItem("SaveAs");
            file.add(saveAs);
            close = new JMenuItem("Close");
            file.add(close);
            line = new JMenuItem("Line");
            draw.add(line);
            centreandradius = new JMenuItem("Centre and Radius");
            circle.add(centreandradius);
            rectangle = new JMenuItem("Rectangle");
            draw.add(rectangle);
            point = new JMenuItem("Point");
            draw.add(point);
            arc = new JMenuItem("arc");
            draw.add("Arc");
            return(menuBar);
    sketch class
    package aple;
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Graphics;
    public class sketch extends Canvas{
        public void sketch(){
            this.setBackground(Color.green);
        @Override
        public void paint(Graphics g){
         // g.fillRect(50,50, 50, 50); 
    }

    When you were using JPanel, your "setBackground" didn't work because you were overriding its paint(Graphics) method without calling "super.paint(g);". If you don't do this, the panel won't paint its background.
    You should also override "protected void paintComponent(Graphics g)" in any JComponent, such as JPanel, instead of just "paint(Graphics)". (And don't forget to call super.paintComponent(g) FIRST in your subclass's overridden method, if you want the background painted):
    class MyJPanelSubclass extends JPanel {
       protected void paintComponent(Graphics g) {
          super.paintComponent(g); // Paints background and any other stuff normally painted.
          // Do your custom painting here.
    }

  • JMenuBar is hidden by Canvas

    Hi,
    I have a class that extends JFrame, this has a JMenuBar set to it (set with setJMenuBar method of JFrame) and is displayed fine until i try to add a java.awt.Canvas object to the center of the JFrame(using a BorderLayout) . When this canvas has been added then you can still click on the JMenu names in the JMenuBar but the JMenu itself is no hidden behind the canvas. Here is some of the code
    Class that extends JFrame's constructor
    //call the super constructor
              super("My Image Viewer");
              //get the content pane
              c = getContentPane();
              //set the layout of the frame
              c.setLayout(new BorderLayout());
              //create a new MenuHandler
              menuHandler = new MenuHandler();
              //create a new JFileChooser
              fileChooser = new JFileChooser("C:/Documents and Settings/"
                        + "Irene Stephanie/My Documents");
              //create a new file filter
              filter = new ImgFilter();
              //assign the file filter
              fileChooser.setFileFilter(filter);
              //create a new window canvas
              canvas = new WindowCanvas();
              add("Center", canvas);
              //set up the menus
              initMenu();
              //set the JMenuBar
              setJMenuBar(menuBar);
              //Set the window size
              setSize(640, 480);
              //make the window visible
              setVisible(true);Class that extends Canvas
    public class WindowCanvas extends Canvas{
         public WindowCanvas(){
              super();
         public void paint(Graphics g){
         }Please not that it works if you add the JMenuBar to the South position, and that you can draw in the canvas, but you cannot see the JMenu's.
    Any help will be greatly apreciated
    Andy

    A Canvas is a heavyweight component. By default, Swing menus are lightweight components. You need to call
    JPopupMenu.setDefaultLightWeightPopupEnabled(false);before creating your menus.

  • JMenuBar Event Handling

    I am customizing my own menu bar, I would like to create some event handling, for the top most level, it is not a problem, but when I try to implement some event handling for the drop-down list/menu, nothing happens.
    The following is the whole class:
    package diagramillustrator;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class DIM extends JMenuBar implements MouseListener
         * Creates a new instance of DIM
        public DIM()
            configFileMenu();
            configOptionsMenu();
            configAllItems();
            configMenuBar();
        //Creation and Initialization of objects
        //<editor-fold>    
        //file and options menus to be added to the menubar
        JMenu fileMenu =  new JMenu("File");
        JMenu optionsMenu = new JMenu("Options");
        //file items
        JMenuItem newItem = new JMenuItem("New");
        JMenuItem openItem = new JMenuItem("Open");
        JMenuItem saveItem = new JMenuItem("Save");
        JMenuItem printItem = new JMenuItem("Print");
        JMenuItem exitItem = new JMenuItem("Exit");
        //options items
        JMenuItem createFileItem = new JMenuItem("Create properties file");
        JMenuItem propertiesItem = new JMenuItem("Properties");
        //</editor-fold>
        //adds mouse listener to every item
        private void configAllItems()
            this.addMouseListener(this);
            fileMenu.addMouseListener(this);
            optionsMenu.addMouseListener(this);
            newItem.addMouseListener(this);
            openItem.addMouseListener(this);
            saveItem.addMouseListener(this);
            printItem.addMouseListener(this);
            exitItem.addMouseListener(this);
            createFileItem.addMouseListener(this);
            propertiesItem.addMouseListener(this);
        //creats the file menu
        private void configFileMenu()
            fileMenu.add(newItem);
            fileMenu.addSeparator();
            fileMenu.add(saveItem);
            fileMenu.add(openItem);
            fileMenu.add(printItem);
            fileMenu.addSeparator();
            fileMenu.add(exitItem);
        //creats the options menu
        private void configOptionsMenu()
            optionsMenu.add(createFileItem);
            optionsMenu.add(propertiesItem);
        //configures the menubar, adds all items to it etc
        private void configMenuBar()
            this.setLayout(new FlowLayout(FlowLayout.LEFT));
            this.add(fileMenu);
            this.add(new JSeparator(SwingConstants.VERTICAL));
            this.add(new JSeparator(SwingConstants.VERTICAL));
            this.add(optionsMenu);
            this.setToolTipText("Menu Bar");
        //event handling
        //<editor-fold>
        public void mouseClicked(MouseEvent e)
            //works
            //if(e.getSource().equals(fileMenu))this.setBackground(Color.yellow);
            //else this.setBackground(Color.black);
            //dowsn't work
            if(e.getSource().equals(newItem))this.setBackground(Color.yellow);
        public void mousePressed(MouseEvent e)
        public void mouseReleased(MouseEvent e)
        public void mouseEntered(MouseEvent e)
        public void mouseExited(MouseEvent e)
        //</editor-fold>
        //main method to test class
        public static void main(String[] args)
            JFrame f= new JFrame("Testing menu");
            f.setSize(400,400);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setJMenuBar(new DIM());
            f.show();
    } This is the troubling part:
    public void mouseClicked(MouseEvent e)
            //works
            //if(e.getSource().equals(fileMenu))this.setBackground(Color.yellow);
            //else this.setBackground(Color.black);
            //dowsn't work
            if(e.getSource().equals(newItem))this.setBackground(Color.yellow);
        } The first two lines work perfectly fine as they apply to the top most level, the rest doesn't do anything at all.
    Can anyone help me to handle events for the drop-down please?
    AndXer

    Sorry posted the prvious by mistake.
    Oh, I usually used MouseListener for buttons...I tried using ActionListener and it worked great, the only flaw is that any mouse button clicked triggers an event, I want the event to be triggered only when BUTTON_1 is clicked (like in MouseListener).
    Can that be done as I found nothing in the API. If yes, a code sample would be greatly appreciated.
    The current code for handling it is:
        if(e.getSource().equals(newItem))
             this.setBackground(Color.green);
    }Thanks,
    AndXer

  • Adding "window to a container:illegal argument exception".error plz help

    Thanks to Mr.Andrew and sun for developing the following code for a
    mediaplayer which is implemented in jmf.This is working in core java. But
    when i have converted it to Applet it compiles but an error adding "window
    to a container:illegal argument exception".code is given below plz point
    me where is the error;
    import javax.media.*;
    import java.text.DecimalFormat;
    import java.awt.*;
    import java.awt.FileDialog;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    class nwa extends WindowAdapter{
    frameclass frame;
    public nwa(frameclass frame){
    this.frame=frame;
    public void windowClosing (WindowEvent e)
    //User selected close from System menu.
    //Call dispose to invoke windowClosed.
    frame.dispose ();
    public void windowClosed (WindowEvent e)
    //if (player != null)
    //player.close ();
    System.exit (0);
    class frameclass extends JFrame
    frameclass(){
    nwa n=new nwa(this);
    this.addWindowListener(n);                    
    public class PlayerApplet extends JApplet
              implements
    ActionListener,ControllerListener,ItemListener, KeyListener
    frameclass frame=new frameclass();
    Player player;
    Component vc, cc;
    JProgressBar volumeBar;
         JButton fastRewind;
         JButton fastForward;
         JButton play;
    int sizeIncrease = 2;
    boolean invokedStop = false;
         /** Big */
         int progressFontSize=30;
    boolean first = true, loop = false;
    String currentDirectory;
    public void init(){
    JMenu m = new JMenu ("File");
    JMenuItem mi = new JMenuItem ("Open...");
    mi.addActionListener (this);
    m.add (mi);
    m.addSeparator ();
    JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem ("Loop", false);
    cbmi.addItemListener (this);
    m.add (cbmi);
    m.addSeparator ();
    mi = new JMenuItem ("Exit");
    mi.addActionListener (this);
    m.add (mi);
    JMenuBar mb = new JMenuBar ();
    mb.add (m);
    frame.setJMenuBar (mb);
    setSize (200, 200);
         final JPanel p = new JPanel(new GridLayout(1,0,5,5));
              p.setBorder(new EmptyBorder(3,5,5,5) );
              fastRewind = new JButton("<html><body><font size=+"+
    sizeIncrease+ "><<");
              fastRewind.setToolTipText("Fast Rewind");
              fastRewind.addActionListener( new ActionListener(){
                   public void actionPerformed(ActionEvent ae) {
                        if (player!=null) {
                             invokedStop = false;
                             skipBack();
                        } else {
    JOptionPane.showMessageDialog(play,
                             new JLabel("Open a sound file
    first!"));
              fastRewind.addKeyListener(this);
              p.add(fastRewind);
              JButton stop = new JButton("<html><body><font size=+"+
    sizeIncrease+ ">&#9632;");
              stop.setToolTipText("Stop");
              stop.addActionListener( new ActionListener(){
                   public void actionPerformed(ActionEvent ae) {
                        invokedStop = true;
                        //player.stop();
                        sp();
              stop.addKeyListener(this);
              p.add(stop);
              play = new JButton("<html><body><font size=+"+
    sizeIncrease+ ">>");
              play.setToolTipText("Play");
              play.addActionListener( new ActionListener(){
                   public void actionPerformed(ActionEvent ae) {
                        if (player!=null) {
                             invokedStop = false;
                             player.setRate(1);
                             st();
                        } else {
    JOptionPane.showMessageDialog(play,
                             new JLabel("Open a sound file
    first!"));
              play.addKeyListener(this);
              p.add(play);
              fastForward = new JButton("<html><body><font size=+"+
    sizeIncrease+ ">>>");
              fastForward.setToolTipText("Fast Forward");
              fastForward.addActionListener( new ActionListener(){
                   public void actionPerformed(ActionEvent ae) {
                        if (player!=null) {
                             invokedStop = false;
                             skipForward();
                        } else {
    JOptionPane.showMessageDialog(play,
                             new JLabel("Open a sound file
    first!"));
              fastForward.addKeyListener(this);
              p.add(fastForward);
              p.addKeyListener(this);
              frame.add(p,BorderLayout.CENTER);     
              add(frame);
    // pack ();
    setVisible (true);
    public void start(){
    st();
    public void stop(){
    sp();
    public void destroy(){
    player.stop();
    player.deallocate();
    public void actionPerformed (ActionEvent e)
                   if (e.getActionCommand().equals("Exit"))
                   // Call dispose to invoke windowClosed.
                   frame.dispose ();
                        return;
         FileDialog fd = new FileDialog (frame, "Open File",
    FileDialog.LOAD);
         fd.setDirectory (currentDirectory);
         fd.show ();
         // If user cancelled, exit.
              if (fd.getFile() == null)
         return;
    currentDirectory = fd.getDirectory ();
              if (player != null)
         player.close ();
         try
         player = Manager.createPlayer (new MediaLocator
    ("file:" +
    fd.getDirectory() +
    fd.getFile()));
         catch (java.io.IOException e2)
    System.out.println (e2);
    return;
         catch (NoPlayerException e2)
    System.out.println ("Could not find a player.");
    return;
              if (player == null)
         System.out.println ("Trouble creating a player.");
         return;
    first = false;
    frame.setTitle (fd.getFile ().toString());
    player.addControllerListener (this);
    player.prefetch ();
    public void controllerUpdate (ControllerEvent e)
    if (e instanceof ControllerClosedEvent)
    if (vc != null)
    remove (vc);
    vc = null;
    if (cc != null)
    remove (cc);
    cc = null;
    return;
    if (e instanceof EndOfMediaEvent)
    if (loop)
    player.setMediaTime (new Time (0));
    player.start ();
    return;
    if (e instanceof PrefetchCompleteEvent)
    player.start ();
    return;
    if (e instanceof RealizeCompleteEvent)
    vc = player.getVisualComponent ();
    if (vc != null)
    add (vc);
    cc = player.getControlPanelComponent ();
    if (cc != null){
         this.add (cc, BorderLayout.SOUTH);
                        this.show();
    public void keyReleased(KeyEvent ke) {
    int keycode = ke.getKeyCode();
              if (keycode==KeyEvent.VK_LEFT) {
                   skipBack();
              } else if (keycode==KeyEvent.VK_RIGHT) {
                   skipForward();
         public void keyTyped(KeyEvent ke) {
         int keycode = ke.getKeyCode();
              if (keycode==KeyEvent.VK_LEFT) {
                   skipBack();
              } else if (keycode==KeyEvent.VK_RIGHT) {
                   skipForward();
         public void keyPressed(KeyEvent ke) {
              int keycode = ke.getKeyCode();
              if (keycode==KeyEvent.VK_LEFT) {
                   skipBack();
              } else if (keycode==KeyEvent.VK_RIGHT) {
                   skipForward();
              }else if (keycode==KeyEvent.VK_UP) {
                   st();
              }else if (keycode==KeyEvent.VK_DOWN) {
                   sp();
    public void skipForward() {
    double secs=5;
    double playersecs = player.getMediaTime().getSeconds();
    Time settime = new javax.media.Time(playersecs + secs);
    player.setMediaTime(settime);
    public void skipBack() {
              double secs1=5;
    double playersecs1 = player.getMediaTime().getSeconds();
    Time settime1 = new javax.media.Time(playersecs1 - secs1);
    player.setMediaTime(settime1);
         public void st() {
         player.start();
         public void sp() {
         player.stop();
    public void itemStateChanged (ItemEvent e)
    loop = !loop;
    When i comment add(frame) this error goes but i got a null poiter
    exception
    Plz help
    manu

    Hi Andrew,
    Thanks for ur reply.Sorrry that my code not included in the code block.
    My problem have been solved partly.Now playerapplet is working properly.It can play files from local machine(through open menuitem from file menu) as well as local network (through url menuitem from file menu).
    There is no requirement to play file from internet at present.
    I have given arrow keys to forward/backward/open/close.
    I have now completed my first part of project.Now i have to start the second part ie Controlling arrow keys using a joystick like instrument.The instrument and driver will be provided by my co. and the user is using only this device.Plz help me how to do that.
    The code is given below
    import javax.media.*;
    import java.text.DecimalFormat;
    import java.awt.*;
    import java.awt.FileDialog;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    <APPLET CODE=PlayerApplet.class
    WIDTH=320 HEIGHT=300>
    </APPLET>
    class nwa extends WindowAdapter
         frameclass frame;
         Player player;
         public nwa(frameclass frame,Player player)
          this.player=player;
          this.frame=frame;
         public void windowClosing (WindowEvent e)
          //User selected close from System menu.
          //Call dispose to invoke windowClosed.
          frame.dispose ();
          public void windowClosed (WindowEvent e)
              if (player != null)
                   player.stop();
                player.close ();
                   player.deallocate();
          System.exit (0);
    class frameclass extends JFrame
    Player player;
         frameclass(Player player)
         nwa n=new nwa(this,player);
         this.addWindowListener(n);                    
    public class PlayerApplet extends JApplet
               implements ActionListener,ControllerListener,ItemListener, KeyListener
               Player player=null;
               frameclass frame=new frameclass(player);
                 Component vc, cc;
                 Container f;
                 JProgressBar volumeBar;
                 JButton fastRewind;
              JButton fastForward;
              JButton play;
              int sizeIncrease = 2;
              boolean invokedStop = false;
              /** Big */
              int progressFontSize=30;
                 boolean first = true, loop = false;
                 String currentDirectory;
                 public void init()
                          f=frame.getContentPane();
                         JMenu m = new JMenu ("File");
                         JMenuItem mi = new JMenuItem ("Open...");
                         mi.addActionListener (this);
                         m.add (mi);
                         m.addSeparator ();
                         mi = new JMenuItem ("URL");
                         mi.addActionListener (this);
                         m.add (mi);
                         m.addSeparator ();
                         JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem ("Loop", false);
                         cbmi.addItemListener (this);
                         m.add (cbmi);
                         m.addSeparator ();
                         mi = new JMenuItem ("Exit");
                         mi.addActionListener (this);
                         m.add (mi);
                         JMenuBar mb = new JMenuBar ();
                         mb.add (m);
                         frame.setJMenuBar (mb);
                         setSize (500, 500);
                           JPanel p = new JPanel(new GridLayout(1,0,5,5));
                        p.setBorder(new EmptyBorder(3,5,5,5) );
                        fastRewind = new JButton("<html><body><font size=+"+ sizeIncrease+ "><<");
                        fastRewind.setToolTipText("Fast Rewind");
                        fastRewind.addActionListener( new ActionListener(){
                             public void actionPerformed(ActionEvent ae) {
                                  if (player!=null) {
                                       invokedStop = false;
                                       skipBack();
                                  } else {
                                       JOptionPane.showMessageDialog(play,
                                       new JLabel("Open a sound file first!"));
                        fastRewind.addKeyListener(this);
                        p.add(fastRewind);
                        JButton stop = new JButton("<html><body><font size=+"+ sizeIncrease+ ">&#9632;");
                        stop.setToolTipText("Stop");
                        stop.addActionListener( new ActionListener(){
                                  public void actionPerformed(ActionEvent ae) {
                                       invokedStop = true;
                                       sp();
                        stop.addKeyListener(this);
                        p.add(stop);
                        play = new JButton("<html><body><font size=+"+ sizeIncrease+ ">>");
                        play.setToolTipText("Play");
                        play.addActionListener( new ActionListener()
                                  public void actionPerformed(ActionEvent ae) {
                                       if (player!=null) {
                                            invokedStop = false;
                                            player.setRate(1);
                                            st();
                                       } else {
                                            JOptionPane.showMessageDialog(play,
                                            new JLabel("Open a sound file first!"));
              play.addKeyListener(this);
              p.add(play);
              fastForward = new JButton("<html><body><font size=+"+ sizeIncrease+ ">>>");
              fastForward.setToolTipText("Fast Forward");
              fastForward.addActionListener( new ActionListener(){
                   public void actionPerformed(ActionEvent ae) {
                        if (player!=null) {
                             invokedStop = false;
                             skipForward();
                        } else {
                             JOptionPane.showMessageDialog(play,
                             new JLabel("Open a sound file first!"));
              fastForward.addKeyListener(this);
              p.add(fastForward);
              frame.getContentPane().add(p,BorderLayout.CENTER);
              frame.setVisible (true);
              frame.pack();
              frame.setResizable(false);
      public void stop(){
      sp();
      public void destroy(){
       player.stop();
        player.deallocate();
      public void actionPerformed (ActionEvent e)
              if (e.getActionCommand().equals("Exit"))
                             // Call dispose to invoke windowClosed.
                             player.stop();
                             player.close();
                             player.deallocate();
                             frame.dispose ();
                                  return;
              if (e.getActionCommand().equals("Open..."))
                             FileDialog fd = new FileDialog (frame, "Open File",
                                         FileDialog.LOAD);
                              fd.setDirectory (currentDirectory);
                              fd.show ();
                              // If user cancelled, exit.
                              if (fd.getFile() == null)
                             return;
                              currentDirectory = fd.getDirectory ();
                                   if (player != null){
                                       player.close ();
                                       player.deallocate();
                         try
                  player = Manager.createPlayer (new MediaLocator
                                               ("file:" +
                                               fd.getDirectory() +
                                               fd.getFile()));
                              catch (java.io.IOException e2)
                            System.out.println ("file not found :"+e2);
                            return;
                              catch (NoPlayerException e2)
                            System.out.println ("Could not find a player.");
                            return;
                    if (player == null)
                   System.out.println ("Trouble creating a player.");
                   return;
                    first = false;
                    frame.setTitle (fd.getFile ().toString());
                    player.addControllerListener (this);
                    player.prefetch ();
                   return;
              if (e.getActionCommand().equals("URL"))
                             FileDialog fd = new FileDialog (frame, "Open File",
                                         FileDialog.LOAD);
                         fd.setDirectory (currentDirectory);
                         fd.show ();
                         // If user cancelled, exit.
                              if (fd.getFile() == null)
                             return;
                         currentDirectory = fd.getDirectory ();
                              if (player != null){
                                       player.close ();
                                       player.deallocate();
                   try
                        URL url = new URL ("file://"+fd.getDirectory()+fd.getFile());
                    MediaLocator mediaLocator = new MediaLocator (url);
                        player = Manager.createPlayer (mediaLocator);
                   catch (java.io.IOException e2)
                  System.out.println ("file not found :"+e2);
                  return;
                    catch (NoPlayerException e2)
                  System.out.println ("Could not find a player.");
                  return;
                    if (player == null)
                   System.out.println ("Trouble creating a player.");
                   return;
          first = false;
          frame.setTitle (fd.getFile ().toString());
          player.addControllerListener (this);
          player.prefetch ();
              return;
       public void controllerUpdate (ControllerEvent e)
          if (e instanceof ControllerClosedEvent)
              if (vc != null)
                  frame.getContentPane().remove (vc);
                  vc = null;
              if (cc != null)
                  frame.getContentPane().remove (cc);
                  cc = null;
              return;
          if (e instanceof EndOfMediaEvent)
              if (loop)
                  player.setMediaTime (new Time (0));
                  player.start ();
              return;
          if (e instanceof PrefetchCompleteEvent)
              player.start();
              return;
          if (e instanceof RealizeCompleteEvent)
            if (vc != null)
                  remove (vc);
                  vc = null;
              if (cc != null)
                  remove (cc);
                  cc = null;
              vc = player.getVisualComponent ();
              if (vc != null)
                  frame.getContentPane().add(vc,BorderLayout.NORTH);
              cc = player.getControlPanelComponent ();
              if (cc != null){
                       frame.getContentPane().add (cc, BorderLayout.SOUTH);
                     frame.setVisible(true);
                     frame.pack();
    public void keyReleased(KeyEvent ke) {
    int keycode = ke.getKeyCode();
              if (keycode==KeyEvent.VK_LEFT) {
                   skipBack();
              } else if (keycode==KeyEvent.VK_RIGHT) {
                   skipForward();
         public void keyTyped(KeyEvent ke) {
         int keycode = ke.getKeyCode();
              if (keycode==KeyEvent.VK_LEFT) {
                   skipBack();
              } else if (keycode==KeyEvent.VK_RIGHT) {
                   skipForward();
         public void keyPressed(KeyEvent ke) {
              int keycode = ke.getKeyCode();
              if (keycode==KeyEvent.VK_LEFT) {
                   skipBack();
              } else if (keycode==KeyEvent.VK_RIGHT) {
                   skipForward();
              }else if (keycode==KeyEvent.VK_UP) {
                   st();
              }else if (keycode==KeyEvent.VK_DOWN) {
                   sp();
    public void skipForward() {
    Time settime;
    double secs=5;
    double playersecs = player.getMediaTime().getSeconds();
    double duration = player.getDuration().getSeconds();
              if((playersecs+secs) < duration){
                      settime = new javax.media.Time(playersecs + secs);
                      player.setMediaTime(settime);
              }else {
                        player.setMediaTime(new Time(duration));
    public void skipBack() {
              double secs1=5;
              double secs2=0;
              double playersecs1 = player.getMediaTime().getSeconds();
              Time settime1;
              if((playersecs1 - secs1) > secs2){
                      settime1 = new javax.media.Time(playersecs1 - secs1);
                      player.setMediaTime(settime1);
              }else {
                        player.setMediaTime(new Time(0));
         public void st() {
         player.start();
         public void sp() {
         player.stop();
       public void itemStateChanged (ItemEvent e)
          loop = !loop;
    With Thanks
    manuEdited by: mm_mm on Nov 27, 2007 11:09 PM

  • Problems adding to database

    I'm making a chat program and I'm trying to use a database for all the users that are connected so the people chatting can see whos connected. Unfortunately, I can't get the usernaes to go into the database. I've tried the same code elsewhere and it works fine but in this program it won't add the names. My database is a MySQL database and has the name 'users' and the table is called 'connected' with 1 column called 'name'. I can get a window to pop up with the column heading at the top but no names will be added. It won't even add the "not good" string in my code... I'm not actually getting any sql errors, it just won't grab the names.
    heres my relevant code:
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
         static final String DATABASE_URL = "jdbc:mysql://localhost/users?user=mike&password=blitz84";
    userName = JOptionPane.showInputDialog(
                ClientGUI.this, "Enter user name:" );
             dUserName = userName;
             dUserName = "Not Good";
                              String input = dUserName;
                        String use = "use users"; 
                        try
                             Class.forName(JDBC_DRIVER);//load database driver class
                             conn = DriverManager.getConnection(DATABASE_URL);//establish connection to database
                             stat = conn.createStatement();//create statement for submitting information to the database
                             stat.executeUpdate(use);//ensures proper database is loaded
                             String query = "insert into connected values('"+input+"')";//string to enter data
                             stat.executeUpdate(query);//submits data to database
                             stat.close();//close connection
                        catch(Exception e)
                             System.out.println("Error at "+e);
                             e.printStackTrace();
                        }//end try and catch             

    I tried it and it still didn't put anything in the database, here's my complete code, maybe that will help:
    package com.deitel.messenger;
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.sql.*;
    public class ClientGUI extends JFrame {
         //setting up the database for users
         static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
         static final String DATABASE_URL = "jdbc:mysql://localhost/users?user=mike&password=blitz84";
         String use = "use users";
         private Statement stat;
         private Connection conn;
       // JMenu for connecting/disconnecting server
       private JMenu serverMenu;
       // JTextAreas for displaying and inputting messages
       private JTextArea messageArea;
       private JTextArea inputArea;
       private JTextArea users;
       // JButtons and JMenuItems for connecting and disconnecting
       private JButton connectButton;
       private JMenuItem connectMenuItem;  
       private JButton disconnectButton;
       private JMenuItem disconnectMenuItem;
       private JMenuItem showUsers;
       // JButton for sending messages
       private JButton sendButton;
       // JLabel for displaying connection status
       private JLabel statusBar;
       // userName to add to outgoing messages
       private String userName;
       public String dUserName;
       // MessageManager for communicating with server
       private MessageManager messageManager;
       // MessageListener for receiving incoming messages
       private MessageListener messageListener;
       // ClientGUI constructor
       public ClientGUI(MessageManager manager)
          super( "Chat program of Splendor" );
          // set the MessageManager
          messageManager = manager;
          // create MyMessageListener for receiving messages
          messageListener = new MyMessageListener();
          // create Server JMenu     
          serverMenu = new JMenu ( "Server" );  
          serverMenu.setMnemonic( 'S' );
          JMenuBar menuBar = new JMenuBar();
          menuBar.add( serverMenu );
          setJMenuBar( menuBar ); 
          // create ImageIcon for connect buttons
          Icon connectIcon = new ImageIcon(
             getClass().getResource( "images/Connect.gif" ) );
          // create connectButton and connectMenuItem
          connectButton = new JButton( "Connect", connectIcon );
          connectMenuItem = new JMenuItem( "Connect", connectIcon ); 
          connectMenuItem.setMnemonic( 'C' );
          showUsers = new JMenuItem( "Show Users");
          showUsers.setMnemonic('U');
          // create ConnectListener for connect buttons
          ActionListener connectListener = new ConnectListener();
          connectButton.addActionListener( connectListener );
          connectMenuItem.addActionListener( connectListener );
          // create ImageIcon for disconnect buttons
          Icon disconnectIcon = new ImageIcon(
             getClass().getResource( "images/Disconnect.gif" ) );
          // create disconnectButton and disconnectMenuItem
          disconnectButton = new JButton( "Disconnect", disconnectIcon );
          disconnectMenuItem = new JMenuItem( "Disconnect", disconnectIcon );     
          disconnectMenuItem.setMnemonic( 'D' );
          // disable disconnect buttons
          disconnectButton.setEnabled( false );
          disconnectMenuItem.setEnabled( false );
          // create DisconnectListener for disconnect buttons
          ActionListener disconnectListener = new DisconnectListener();
          disconnectButton.addActionListener( disconnectListener );
          disconnectMenuItem.addActionListener( disconnectListener );
          // add connect and disconnect JMenuItems to fileMenu
          serverMenu.add( connectMenuItem );
          serverMenu.add( disconnectMenuItem );
          serverMenu.add(showUsers);          
          // add connect and disconnect JButtons to buttonPanel
          JPanel buttonPanel = new JPanel();
          buttonPanel.add( connectButton );
          buttonPanel.add( disconnectButton );
          // create JTextArea for displaying messages and users
          messageArea = new JTextArea();
          users = new JTextArea();
          // disable editing and wrap words at end of line
          messageArea.setEditable( false );
          messageArea.setWrapStyleWord( true );
          messageArea.setLineWrap( true );
          // put messageArea and users in JScrollPane to enable scrolling
          JPanel messagePanel = new JPanel();
          messagePanel.setLayout( new BorderLayout( 10, 10 ) );
          messagePanel.add( new JScrollPane( messageArea ),
             BorderLayout.CENTER );
          messagePanel.add( new JScrollPane( users ),
             BorderLayout.WEST );
          // create JTextArea for entering new messages
          inputArea = new JTextArea( 4, 20 );
          inputArea.setWrapStyleWord( true );
          inputArea.setLineWrap( true );
          inputArea.setEditable( false );
          // create Icon for sendButton
          Icon sendIcon = new ImageIcon(
             getClass().getResource( "images/Send.gif" ) );
          // create sendButton and disable it
          sendButton = new JButton( "Send", sendIcon );
          sendButton.setEnabled( false );
          sendButton.addActionListener(
             new ActionListener() {
                // send new message when user activates sendButton
                public void actionPerformed( ActionEvent event )
                   messageManager.sendMessage( userName,
                      inputArea.getText());
                   // clear inputArea
                   inputArea.setText("");
          // lay out inputArea and sendButton in BoxLayout and
          // add Box to messagePanel
          Box box = new Box( BoxLayout.X_AXIS );
          box.add( new JScrollPane( inputArea ) );
          box.add( sendButton );
          messagePanel.add( box, BorderLayout.SOUTH );
          // create JLabel for statusBar with a recessed border
          statusBar = new JLabel( "Not Connected" );
          statusBar.setBorder( new BevelBorder( BevelBorder.LOWERED ) );
          // lay out components in JFrame
          Container container = getContentPane();
          container.add( buttonPanel, BorderLayout.NORTH );
          container.add( messagePanel, BorderLayout.CENTER );
          container.add( statusBar, BorderLayout.SOUTH );
          // add WindowListener to disconnect when user quits
          addWindowListener (
             new WindowAdapter () {
                // disconnect from server and exit application
                public void windowClosing ( WindowEvent event )
                   messageManager.disconnect( messageListener );
                   System.exit( 0 );
       } // end ClientGUI constructor
       // ConnectListener listens for user requests to connect to server
       private class ConnectListener implements ActionListener {
          // connect to server and enable/disable GUI components
          public void actionPerformed( ActionEvent event )
             // connect to server and route messages to messageListener
             messageManager.connect( messageListener );
             // prompt for userName
             userName = JOptionPane.showInputDialog(
                ClientGUI.this, "Enter user name:" );
             dUserName = userName;
             dUserName = "Not Good";
                              String input = dUserName;
                        Connection foo = null;
                        PreparedStatement stmt = null;
                        try
                             foo = DriverManager.getConnection("jdbc:mysql://localhost/users?user=mike&password=blitz84");
                             stmt = foo.prepareStatement("INSERT INTO connections VALUES (?)");
                             stmt.setString(1, dUserName); // input is the name of the user as a String
                             stmt.executeUpdate();
                        catch (SQLException e)
                             foo.rollback();
                             e.printStackTrace();
                        finally
                             if (stmt != null) stmt.close();
                             if (foo != null) foo.close();
             // clear messageArea
             messageArea.setText( "" );
             // update GUI components
             connectButton.setEnabled( false );
             connectMenuItem.setEnabled( false );
             disconnectButton.setEnabled( true );
             disconnectMenuItem.setEnabled( true );
             sendButton.setEnabled( true );
             inputArea.setEditable( true );
             inputArea.requestFocus(); 
             statusBar.setText( "Connected: " + userName );
       } // end ConnectListener inner class
       // DisconnectListener listens for user requests to disconnect
       // from DeitelMessengerServer
       private class DisconnectListener implements ActionListener {
          // disconnect from server and enable/disable GUI components
          public void actionPerformed( ActionEvent event )
             // disconnect from server and stop routing messages
             // to messageListener
             messageManager.disconnect( messageListener );
             // update GUI components
             sendButton.setEnabled( false );
             disconnectButton.setEnabled( false );
             disconnectMenuItem.setEnabled( false );
             inputArea.setEditable( false );
             connectButton.setEnabled( true );        
             connectMenuItem.setEnabled( true );
             statusBar.setText( "Not Connected" );        
       } // end DisconnectListener inner class
       // MyMessageListener listens for new messages from MessageManager and
       // displays messages in messageArea using MessageDisplayer.
       private class MyMessageListener implements MessageListener {
          // when received, display new messages in messageArea
          public void messageReceived( String from, String message )
             // append message using MessageDisplayer and
             // invokeLater, ensuring thread-safe access messageArea
             SwingUtilities.invokeLater(
                new MessageDisplayer( from, message ) );
       // MessageDisplayer displays a new message by appending the message to
       // the messageArea JTextArea. This Runnable object should be executed
       // only on the Event thread, because it modifies a live Swing component
       private class MessageDisplayer implements Runnable {
          private String fromUser;
          private String messageBody;
          // MessageDisplayer constructor
          public MessageDisplayer( String from, String body )
             fromUser = from;
             messageBody = body;
          // display new message in messageArea
          public void run()
             // append new message
             messageArea.append( "\n" + fromUser + "> " + messageBody );  
             // move caret to end of messageArea to ensure new
             // message is visible on screen
             messageArea.setCaretPosition( messageArea.getText().length() );                         
       }// end MessageDisplayer inner class
    } // end class ClientGUI
    and here is the code that uses the above code:
    package com.deitel.messenger.sockets.client;
    import com.deitel.messenger.*;
    public class DeitelMessenger {
       public static void main( String args[] )
          MessageManager messageManager;
          // create new DeitelMessenger
          if ( args.length == 0 )
             messageManager = new SocketMessageManager( "localhost" );
          else
             messageManager = new SocketMessageManager( args[ 0 ] ); 
          // create GUI for SocketMessageManager
          ClientGUI clientGUI = new ClientGUI( messageManager );
          clientGUI.setSize( 500, 400 );
          clientGUI.setResizable( false );
          clientGUI.setVisible( true );
    } // end class DeitelMessenger

  • JTabbedPane - Adding Tab to the right

    In my program, I am using a JTabbedPane, which shows several settings pages. Now i want to add a "help" screen to it, in a new tab, but I would like to align that tab to the right, the same effect like adding a Box.createHorizontalGlue() to a JMenuBar.
    My question graphically: http://home.arcor.de/sidiousx/tab.gif
    I searched the API and I tried subclassing JTabbedPane and changing the UI (but I'd rather not subclass the UI, because I use different Look and Feels), but it wass all useless. Anyone got an idea?

    Hm and how would you do this?
    I tried to sub-class BasicTabbedPaneUI:
    class TabUI extends BasicTabbedPaneUI
        public Rectangle getTabBounds(int index, Rectangle rect)
            if (index == rects.length - 1) {
                rect = super.getTabBounds(index, rect);
                rect.x += 100;
                return rect;
            } else {
                return super.getTabBounds(index, rect);
    }But:
    1. It doesn't look good in Metal-LookAndFeel
    2. It doesn't work ;) If the last Tab is selected, you can see some kind of shadow, where the tab should be (in this test), but nothing more.

Maybe you are looking for

  • Creating a custom file info panel

    Hi Can anybody help, I have a custom file info panel that works in cs4,but I need to add some further advanced functions that needs to be done in flex builder.I have little Knowledge of flex so I am asking if this can be imported into flex so I don't

  • FCC recordsets per message

    Hi experts, I have the following message: I do not understand why? very thanks,

  • Business number not found

    Hi Girus, When I m tring to run the payroll for Canada I m getting following error. Business number not found Check account and registration number configuration from 1.01.2010 31.01.2010 I m maintaining 0461,0462,0463,0464 tax infotype for canada. P

  • Description of Interactive Activity

    Hi all... I am trying to modify the description of an Interactive activity to show properly in the inbox. I tried in the Argument mapping of the interactive activity to do description = "my string" but it dose not show up correctly in the inbox I get

  • How to set working-dir for precompiled jsp pages to some where under tmp

    If my weblogic application gets exploded into this tmp directory: D:\bea_domains\my_wl_domain\servers\SERVER001\tmp\_WL_user\mywebapp\wxyzzz\war where "wxyzzz" is a random directory name generated by weblogic 9.2, how would I set my working-dir in we