JMenuItem/JButton Action

Is it possible to disable the Icon made visible in the JMenuItem after creating it with an new 'Action'(String,Icon) ?
thx.

setIcon(null) ?

Similar Messages

  • Question related to JButton action event

    Hi All,
    In my application a small issue has poppedup i.e. i am giving a JButton with an action and with that action a .bat file is getting generated and immediately i am making it to get executed by using the runtime class.Now my question is if i keep on firing the same button for 20 times same batch file is getting executed for 20 times.SO i want to control that process something like once the execution is done i need to have an acknowledgement so that i will be getting a chance to fire in the next.
    After first click on the JButton second click should not process anything till the first execution is done.
    How is it possoible to implement this??
    Any help appreciated.
    regards,
    Viswanadh

    Hi Camic and Andre,
    Thanks for the replies i will try out in both the ways and get back to you people.
    And camic as you were saying to go through Process class i have seen and immediately got a question.When i disable the JButton is it a right way that me getting the exitValue of the Process soemthing like
    Process p;
    if ( p.exitValue()==0){
    JButton.setEnabled(true) /enabling button
    }Is this the right way to do???
    regards,
    Viswanadh

  • JButton / Action performed

    Hi,
    I have an Interface class which builds an interface.
    On the interface is a Jbutton, and a Jtextarea.
    When this button is pressed the Interface class sends a message to an implementation class which carries out a service.
    The problem is that the program stalls until the implementation class performs all the code.
    The implementation class should send messages back to the text area updating the textArea with info, but instead it only updates at the end when all code in implementation class is performed.
    does anybody have any idea why it is doing this?

    The buttons action listener executes in swing thead whose primary job is to paint the screens.
    It looks like you are executing your "implementation code" in swing thread. If it takes a while to execute, the screen will stall/freeze.
    If my analysis is correct, try executing it in a worker thread..

  • Missing some JButton action events

    I have a GUI with multiple windows and a number of buttons and a JTable and various other things (a nontrivial application). Some button presses (perhaps 10% of the time) appear to be recognized by the OS (Windows XP) because the button color changes briefly, yet no ActionEvent is delivered to my actionPerformed() handler. Things work properly the other 90% of the time.
    This has occurred with Java 1.4 and 1.5.
    Any ideas why some of the events are getting lost?

    For debug, the first thing I do in actionPerformed is "Toolkit.getDefaultToolkit().beep()", so that I know when an event is generated.
    No uncaught exceptions show up on the console, and all of my exception handling-code would also print something, so exceptions are not occurring.

  • JButton - hide text

    I can't believe I'm asking this but I can't see it in the API.
    I'm creating my JButtons with Actions so they get all their settings (Icon, text etc) from them.
    I'm looking for the method that will allow me to hide the text (i.e. only show the Icon).
    I don't just want to delete the value from the Action as it is used with controls (i.e. the menu) too.
    And don't want to delete it from the JButton as I may want to show it again later.
    Isn't there a simple way to do that?

    The Action is used to set the properties of the JMenuItem and JButton, so using setText("") may be the easiest way.
    When I use Actions I have code that looks like this:
         private JMenuItem createMenuItemFromAction(Action action, boolean isDialog)
              JMenuItem menuItem = new JMenuItem( action );
              menuItem.setAccelerator( (KeyStroke)action.getValue(Action.ACCELERATOR_KEY) );
              if ( isDialog )
                   menuItem.setText( menuItem.getText() + "..." );
              return menuItem;
         private JButton createButtonFromAction(Action action)
              JButton button = new JButton();
              button.setRequestFocusEnabled(false);
              button.putClientProperty( "hideActionText", Boolean.TRUE );
              button.setAction( action );
              button.setIcon(     (Icon)action.getValue( "LargeIcon" ) );
              button.setMargin( buttonInsets );
              button.setMnemonic(0);
              return button;
         }Maybe the putClientProperty(...) of the button is what you are looking for, although it doesn't really seem any easier than using setText().

  • JButton and menu

    Do you know how I can add popup menu to a mixed jbutton? I need to create a button like JBuilder or eclips run button. I can create simple buttons which will show a popup menu whenever user click it but I had to create a component which contains 2 button one of them will show a popup menu and another will do the next task (exactly like jbuilder run button).
    Thanks in advance.

    This is a good widget that I found on the web and have been using:// Process Dashboard - Data Automation Tool for high-maturity processes
    // Copyright (C) 2003 Software Process Dashboard Initiative
    // This program is free software; you can redistribute it and/or
    // modify it under the terms of the GNU General Public License
    // as published by the Free Software Foundation; either version 2
    // of the License, or (at your option) any later version.
    // This program is distributed in the hope that it will be useful,
    // but WITHOUT ANY WARRANTY; without even the implied warranty of
    // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    // GNU General Public License for more details.
    // You should have received a copy of the GNU General Public License
    // along with this program; if not, write to the Free Software
    // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
    // The author(s) may be contacted at:
    // Process Dashboard Group
    // c/o Ken Raisor
    // 6137 Wardleigh Road
    // Hill AFB, UT 84056-5843
    // E-Mail POC:  [email protected]
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Insets;
    import java.awt.Shape;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ContainerEvent;
    import java.awt.event.ContainerListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.*;
    import javax.swing.border.Border;
    public class DropDownButton extends Box {
        private JButton mainButton;
        private JButton dropDownButton;
        private boolean dropDownEnabled = false;
        private boolean mainRunsDefaultMenuOption = true;
        private Icon enabledDownArrow, disDownArrow;
        private DropDownMenu menu;
        private MainButtonListener mainButtonListener = new MainButtonListener();
        public DropDownButton(JButton mainButton) {
            super(BoxLayout.X_AXIS);
            menu = new DropDownMenu();
            menu.getPopupMenu().addContainerListener(new MenuContainerListener());
            JMenuBar bar = new JMenuBar();
            bar.add(menu);
            bar.setMaximumSize(new Dimension(0,100));
            bar.setMinimumSize(new Dimension(0,1));
            bar.setPreferredSize(new Dimension(0,1));
            add(bar);
            this.mainButton = mainButton;
            mainButton.addActionListener(mainButtonListener);
            mainButton.setBorder
                (new RightChoppedBorder(mainButton.getBorder(), 2));
            add(mainButton);
            enabledDownArrow = new SmallDownArrow();
            disDownArrow = new SmallDisabledDownArrow();
            dropDownButton = new JButton(disDownArrow);
            dropDownButton.setDisabledIcon(disDownArrow);
            dropDownButton.addMouseListener(new DropDownListener());
            dropDownButton.setMaximumSize(new Dimension(11,100));
            dropDownButton.setMinimumSize(new Dimension(11,10));
            dropDownButton.setPreferredSize(new Dimension(11,10));
            dropDownButton.setFocusPainted(false);
            add(dropDownButton);
            setEnabled(false);
        public DropDownButton()                 { this(new JButton());     }
        public DropDownButton(Action a)         { this(new JButton(a));    }
        public DropDownButton(Icon icon)        { this(new JButton(icon)); }
        public DropDownButton(String text)      { this(new JButton(text)); }
        public DropDownButton(String t, Icon i) { this(new JButton(t, i)); }
        public JButton getButton()         { return mainButton;     }
        //public JButton getDropDownButton() { return dropDownButton; }
        public JMenu   getMenu()           { return menu;           }
        public void setEnabled(boolean enable) {
            mainButton.setEnabled(enable);
            dropDownButton.setEnabled(enable);
        public boolean isEnabled() {
            return mainButton.isEnabled();
        public boolean isEmpty() {
            return (menu.getItemCount() == 0);
        /** Set the behavior of the main button.
         * @param enable if true, a click on the main button will trigger
         *    an actionPerformed() on the first item in the popup menu.
        public void setRunFirstMenuOption(boolean enable) {
            mainButton.removeActionListener(mainButtonListener);
            mainRunsDefaultMenuOption = enable;
            setEnabled(mainRunsDefaultMenuOption == false ||
                       isEmpty() == false);
            if (mainRunsDefaultMenuOption)
                mainButton.addActionListener(mainButtonListener);
        /** @return true if a click on the main button will trigger an
         *    actionPerformed() on the first item in the popup menu.
        public boolean getRunFirstMenuOption() {
            return mainRunsDefaultMenuOption;
        private void setDropDownEnabled(boolean enable) {
            dropDownEnabled = enable;
            dropDownButton.setIcon(enable ? enabledDownArrow : disDownArrow);
            if (mainRunsDefaultMenuOption)
                setEnabled(enable);
        /** This object responds to events on the main button. */
        private class MainButtonListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                if (mainRunsDefaultMenuOption && !isEmpty()) {
                    JMenuItem defaultItem = menu.getItem(0);
                    if (defaultItem != null)
                        defaultItem.doClick(0);
        /** This object responds to events on the drop-down button. */
        private class DropDownListener extends MouseAdapter {
            boolean pressHidPopup = false;
            public void mouseClicked(MouseEvent e) {
                if (dropDownEnabled && !pressHidPopup) menu.doClick(0);
            public void mousePressed(MouseEvent e) {
                if (dropDownEnabled) menu.dispatchMouseEvent(e);
                if (menu.isPopupMenuVisible())
                    pressHidPopup = false;
                else
                    pressHidPopup = true;
            public void mouseReleased(MouseEvent e) { }
        /** This object watches for insertion/deletion of menu items in
         * the popup menu, and disables the drop-down button when the
         * popup menu becomes empty. */
        private class MenuContainerListener implements ContainerListener {
            public void componentAdded(ContainerEvent e) {
                setDropDownEnabled(true);
            public void componentRemoved(ContainerEvent e) {
                setDropDownEnabled(!isEmpty());
        /** An adapter that wraps a border object, and chops some number of
         *  pixels off the right hand side of the border.
        private class RightChoppedBorder implements Border {
            private Border b;
            private int w;
            public RightChoppedBorder(Border b, int width) {
                this.b = b;
                this.w = width;
            public void paintBorder(Component c,
                                    Graphics g,
                                    int x,
                                    int y,
                                    int width,
                                    int height) {
                Shape clipping = g.getClip();
                g.setClip(x, y, width, height);
                b.paintBorder(c, g, x, y, width + w, height);
                g.setClip(clipping);
            public Insets getBorderInsets(Component c) {
                Insets i = b.getBorderInsets(c);
                return new Insets(i.top, i.left, i.bottom, i.right-w);
            public boolean isBorderOpaque() {
                return b.isBorderOpaque();
        private class DropDownMenu extends JMenu {
            public void dispatchMouseEvent(MouseEvent e) {
                processMouseEvent(e);
        /** An icon to draw a small downward-pointing arrow.
        private static class SmallDownArrow implements Icon {
            Color arrowColor = Color.black;
            public void paintIcon(Component c, Graphics g, int x, int y) {
                g.setColor(arrowColor);
                g.drawLine(x, y, x+4, y);
                g.drawLine(x+1, y+1, x+3, y+1);
                g.drawLine(x+2, y+2, x+2, y+2);
            public int getIconWidth() {
                return 6;
            public int getIconHeight() {
                return 4;
        /** An icon to draw a disabled small downward-pointing arrow.
        private static class SmallDisabledDownArrow extends SmallDownArrow {
            public SmallDisabledDownArrow() {
                arrowColor = new Color(140, 140, 140);
            public void paintIcon(Component c, Graphics g, int x, int y) {
                super.paintIcon(c, g, x, y);
                g.setColor(Color.white);
                g.drawLine(x+3, y+2, x+4, y+1);
                g.drawLine(x+3, y+3, x+5, y+1);
    }Test Code Snippet:        JButton button = new JButton("Action");
         DropDownButton b = new DropDownButton(button);
         b.setEnabled(true);
         JMenu m = b.getMenu();
         m.add(new JMenuItem("Item 1")) ;
         m.add(new JMenuItem("Item 2")) ;
            toolbar.add(b);Voila!

  • Adding an Icon to a JButton Component - Not working

    Hi all,
    Please help me by saying, why the below gevon SSCE doesnt work.
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import javax.swing.AbstractAction;
    import javax.swing.AbstractButton;
    import javax.swing.Action;
    import javax.swing.BorderFactory;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.UIManager;
    public class CreateWindow {
        public CreateWindow(String module, String id){
             if(module.equals("mail")){
                  JPanel mail = new JPanel(null);
                  mail.setPreferredSize(new Dimension(500, 350));
                  //Color colr = new Color(222, 236, 255);
                  mail.setBackground(Color.WHITE);
                  JLabel file = new JLabel("File Name:");
                  file.setBounds(18,25,75,50);
                  // Retrieve the icon
                 Icon icon = new ImageIcon("ei0021-48.gif");
                 // Create an action with an icon
                 Action action = new AbstractAction("Button Label", icon) {
                     // This method is called when the button is pressed
                     public void actionPerformed(ActionEvent evt) {
                         // Perform action
                 // Create the button; the icon will appear to the left of the label
                 JButton button = new JButton(action);
                  mail.add(button);
                  buildGUI(mail,500, 350);
        public void buildGUI(JPanel panel, int width, int height)
            JFrame.setDefaultLookAndFeelDecorated(true);
            UIManager.put("activeCaption", new javax.swing.plaf.ColorUIResource(Color.LIGHT_GRAY));
            JFrame f = new JFrame("Propri�t�s:");
            f.setIconImage(new ImageIcon("save.gif").getImage());//need an image file with black background
            changeButtonColor(f.getComponents());
            f.getContentPane().setBackground(Color.WHITE);
            f.getContentPane().add(panel);
            f.getRootPane().setBorder(BorderFactory.createLineBorder(Color.PINK,2));
            f.setSize(width,height);
            f.setLocationRelativeTo(null);
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setVisible(true);
          public void changeButtonColor(Component[] comps)
            for(int x = 0, y = comps.length; x < y; x++)
              if(comps[x] instanceof AbstractButton)
                ((AbstractButton)comps[x]).setBackground(Color.LIGHT_GRAY);
                ((AbstractButton)comps[x]).setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
              else if (comps[x] instanceof Container)
                changeButtonColor(((Container)comps[x]).getComponents());
    }I call the above given class constructor as given
    public class Test {
         public static void main(String args[]){
              CreateWindow cw = new CreateWindow("mail","Test.doc");
    }Rony

    RonyFederer wrote:
    I have the images and class files inside
    F:\Testing3\Application\src\booodrive
    Do you have the class files or java files here?
    You should put the gif where the .class files are located, and use getResource as Encephalopathic wrote, or:
    Icon icon = new ImageIcon(ClassLoader.getSystemResource("ei0021-48.gif"));
    When I did as you said using System.out.println(new File("ei0021-48.gif").getAbsolutePath());, I got the following output.
    F:\Testing3\Application\ei0021-48.gif
    That's the current running directory.

  • How to Fire an Action

    Im looking for a programmatic way to fire an Action.
    So far ive tried binding it to a JButton with new JButton(action)
    and then trying to fake fire it with button.doClick().
    Ive also tried throwing a fake actionPerformed() by firing a real
    event and copying all the filed (except time).
    actionPerformed(new ActionEvent(button1, 1001, "COPY", System.currentTimeMillis(), 16));Im really a little confused as to how Action works.
    I just need a way to have the Action do its work without having
    to activate it through a gui.

    No it doesnt work.
    Im thinking maybe you have to throw the ActionEvent higher in the chain like to the EventQueue?
    Because, even without adActionListener the Action is already bound to the button.
    This is my testing class. It looks messy but its super simple and
    easy to follow.
    This all started with looking for a way to get around the stupid applet
    "security" restriction that doesnt let you copy to the system clipboard.
    The jtextcomponent already has a copy Action that DOES work, lol.
    So I just search the components Actions and steal the copy Action.
    I now want to fire this programmatically - WITHOUT being dependent
    on a GUI component (like a button press) to do it...
    because i want one button to do a series of things - ending with the copy.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.datatransfer.*;
    import java.io.*;
    import java.applet.*;
    public class ClipboardApplet extends JApplet implements ClipboardOwner, ActionListener{
         JTextArea textField;
         JButton button1;
         JButton button2;
         JButton button3;
         Action copy = null;
    public static void main(String[] arguments){
         ClipboardApplet ca = new ClipboardApplet();
         ca.init();
         JFrame frame = new JFrame("???");
         frame.setSize(400, 400);
         frame.setLocationRelativeTo(null);
         //frame.setUndecorated(true);
         frame.setContentPane(ca);
         frame.setVisible(true);
    public void init(){
         this.getContentPane().setBackground(Color.yellow);
         JFrame frame = new JFrame("???");
         frame.setSize(200, 200);
         frame.setLocationRelativeTo(null);
         frame.setUndecorated(true);
         frame.setVisible(true);
         textField = new JTextArea("deez nutz");
         textField.setPreferredSize(new Dimension(100, 100));
         Action[] actions = textField.getActions();
         for(int i = 0; i < actions.length; i++){
         //System.out.println("Action: " + (String)actions.getValue(Action.NAME));
         if(((String)actions[i].getValue(Action.NAME)).equals("copy-to-clipboard")){
         System.out.println("Found it.");
         System.out.println("Mnemonic: " + (String)actions[i].getValue(Action.MNEMONIC_KEY));
         System.out.println("Action Command Key: " + (String)actions[i].getValue(Action.ACTION_COMMAND_KEY));
         System.out.println("Stroke: " + (String)actions[i].getValue(Action.ACCELERATOR_KEY));
         copy = actions[i];
         button1 = new JButton(copy);
         button1.setText("COPY");
         button2 = new JButton("SELECT");
         button3 = new JButton("FIRE!");
         button1.addActionListener(this);
         button2.addActionListener(this);
         button3.addActionListener(this);
         this.getContentPane().setLayout(new FlowLayout());
         this.getContentPane().add(new JScrollPane(textField));
         this.getContentPane().add(button1);
         this.getContentPane().add(button2);
         this.getContentPane().add(button3);
    public void paint(){}
    public void actionPerformed(ActionEvent e){
         if(e.getSource() == button1){
         System.out.println("Action: Copy");
         System.out.println("Event 1: " + e.getID());
         System.out.println("Event 1: " + e.getActionCommand());
         System.out.println("Event 1: " + e.getModifiers());
    //     setClipboardContents(textField.getText());
    //     setClipboard();
         if(e.getSource() == button2){
         System.out.println("Action: Select");
         selectText();
         if(e.getSource() == button3){
         fakeFire();
    public void fakeFire(){
         textField.selectAll();
         //copy.setEnabled(true);
         button1.doClick();
         actionPerformed(new ActionEvent(button1, 1001, "COPY", System.currentTimeMillis(), 16));
         // 1001, copy, 16
         ActionEvent(Object source, int id, String command)
         ActionEvent(Object source, int id, String command, int modifiers)
         ActionEvent(Object source, int id, String command, long when, int modifiers)
    public void selectText(){
         System.out.println("Selecting...");
         textField.selectAll();
    public void setClipboard(){
    //     KeyStroke controlC = KeyStroke.getKeyStroke("control C");
    //     Action copy = textArea.getActionMap().get(textArea.getInputMap().get(controlC));
         Action[] actions = textField.getActions();
         Action copy;
         for(int i = 0; i < actions.length; i++){
         System.out.println("Action: " + (String)actions[i].getValue(Action.NAME));
         if(((String)actions[i].getValue(Action.NAME)).equals("copy-to-clipboard")){
         System.out.println("Found it.");
         copy = actions[i];
    static String ACCELERATOR_KEY
    static String ACTION_COMMAND_KEY
    static String DEFAULT
    static String LONG_DESCRIPTION
    static String MNEMONIC_KEY
    static String NAME
    static String SHORT_DESCRIPTION
    static String SMALL_ICON
    public void setClipboardContents(String text){
         try{
         System.out.println("Copying...");
         textField.copy();
    //     textField.paste();
    StringSelection stringSelection = new StringSelection(text);
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents( stringSelection, this );
         System.out.println("Copied.\n");
         } catch(Exception e){
         e.printStackTrace();
    // Clipboard Owner
    public void lostOwnership( Clipboard aClipboard, Transferable aContents){

  • Accelerator key on Actions placed on a toolbar.

    I have an Action subclass instance that set Ctrl-S as accelerator in his constructor.
    putValue(ACCELERATOR_KEY , KeyStroke.getKeyStroke(KeyEvent.VK_S , ActionEvent.CTRL_MASK));When I put that action on a toolbar, the accelerator doen't work. If I put it in a menu, it works.
    Does anybody have any idea why? Is there a bug in the JRE or do I something wrong?
    Note that I have to use JRE 1.3.

    Thanks Jay.
    Indeed I set myself the accelerator by creating my own JMenu.
    private static class JMenu extends javax.swing.JMenu
         public JMenu(String name)
              super(name);
         protected JMenuItem createActionComponent(Action a)
              JMenuItem r = super.createActionComponent(a);
              KeyStroke accelerator = (KeyStroke) a.getValue(Action.ACCELERATOR_KEY);
              if (accelerator!=null)
                   r.setAccelerator(accelerator);
              return r;
    }

  • Help needed in this code

    Hi guys, I need help in debugging this code I made, which is a GUI minesweeper. Its extremely buggy...I particularly need help fixing the actionListener part of the code as everytime I press a button on the GUI, an exception occurs.
    help please!
    package minesweeperGUI;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MinesweeperGUI implements ActionListener
         //Declaration of attributes
         static int length = 0;
         JMenuItem menuItemNew = new JMenuItem();
         JRadioButtonMenuItem rbEasy = new JRadioButtonMenuItem();
         JRadioButtonMenuItem rbHard = new JRadioButtonMenuItem();
         JMenuItem menuItemExit = new JMenuItem();
         JButton buttonReset = new JButton();
         JButton buttonGrid[][] = null;
         JFrame frame = new JFrame();
         int getBombsTotal = 0;
         JLabel setBombsLabel = new JLabel();
         int a = 0;
         int b = 0;     
         //No constructor created. Uses default constructor
         //Create the menu bar
         public JMenuBar newMenuBar()
              //Sets up the menubar
              JMenuBar menuBar = new JMenuBar();
              //Sets up the Game menu with choice of new, grid size, and exit
              JMenu menu = new JMenu ("Game");
              menuBar.add (menu);
              menuItemNew = new JMenuItem ("New");
              menuItemNew.addActionListener (this);
              menu.add (menuItemNew);
              menu.addSeparator();
              //Sets up sub-menu for grid size with choice of easy and hard radio buttons
              JMenu subMenu = new JMenu ("Grid Size");
              rbEasy = new JRadioButtonMenuItem ("Easy: 5x5 grid");
              rbEasy.addActionListener (this);
              subMenu.add (rbEasy);
              rbHard = new JRadioButtonMenuItem ("Hard: 10x10 grid");
              rbHard.addActionListener (this);
              subMenu.add (rbHard);
              menu.add (subMenu);
              menu.addSeparator();
              menuItemExit = new JMenuItem ("Exit");
              menuItemExit.addActionListener (this);
              menu.add (menuItemExit);
              return menuBar;
         //Setting up of Bomb Grid
         public int [][] setGrid (int length)
              int grid[][] = null;
              grid = new int[length][length];
              for (int i = 0; i < length; i++)
                   for (int j = 0; j < length; j++)
                        grid[i][j] = ((int)Math.round(Math.random() * 10))% 2;
              return grid;     
         //Setting up of the of the graphical bomb grid
         public JButton[][] setButtonGrid (int length)
              JButton buttonGrid[][] = null;
              buttonGrid = new JButton[length][length];
              for (int i = 0; i < length; i++)
                   for (int j = 0; j < length; j++)
                        buttonGrid[i][j] = new JButton();
              return buttonGrid;
         //Setting up of a way to count the total number of bombs in the bomb grid
         public int getBombsTotal (int length, int setGrid[][])
              int bombsTotal = 0;
              for (int i = 0; i < length; i++)
                   for (int j = 0; j < length; j++)
                        if (setGrid[i][j] == 1)
                             bombsTotal += 1;
              return bombsTotal;
         //Create a label for number of bombs left
         public JLabel setBombsLabel (int getBombsTotal)
              JLabel bombsLabel = new JLabel(String.valueOf (getBombsTotal) + " Bombs Left");
              return bombsLabel;
         //Setting up a way to count the number of bombs around a button
         public String setBombs (int length, int setGrid[][], int x, int y)
              int bombs[][] = new int[length][length];
              String bombsString = null;
              for (int i = 0; i < length; i++)
                   for (int j = 0; j < length; j++)
                        if (i == 0 && j == 0)
                             bombs[i][j] = setGrid[i][j+1] + setGrid[i+1][j] +
                                  setGrid[i+1][j+1];
                        else if (i ==0 && j == (length - 1))
                             bombs[i][j] = setGrid[i][j-1] + setGrid[i+1][j-1] +
                                  setGrid[i+1][j];
                        else if (i == (length - 1) && j == 0)
                             bombs[i][j] = setGrid[i-1][j] + setGrid[i-1][j+1] +
                                  setGrid[i][j+1];
                        else if (i == (length - 1) && j == (length - 1))
                             bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
                                  setGrid[i][j-1];
                        else if (i == 0 && j != 0 && j != (length - 1))
                             bombs[i][j] = setGrid[i][j-1] + setGrid[i][j+1] +
                                  setGrid[i+1][j-1] + setGrid[i+1][j] +
                                  setGrid[i+1][j+1];
                        else if (i == (length - 1) && j != 0 && j != (length - 1))
                             bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
                                  setGrid[i-1][j+1] + setGrid[i][j-1] +
                                  setGrid[i][j+1];
                        else if (i != 0 && i != (length - 1) && j == 0)
                             bombs[i][j] = setGrid[i-1][j] + setGrid[i-1][j+1] +
                                  setGrid[i][j+1] + setGrid[i+1][j] +
                                  setGrid[i+1][j+1];
                        else if (i != 0 && i != (length - 1) && j == (length - 1))
                             bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
                                  setGrid[i][j-1] + setGrid[i+1][j-1] +
                                  setGrid[i+1][j];
                        else
                             bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
                                  setGrid[i-1][j+1] + setGrid[i][j-1] +
                                  setGrid[i][j+1] + setGrid[i+1][j-1] +
                                  setGrid[i+1][j] + setGrid[i+1][j+1];
              bombsString = String.valueOf (bombs[x][y]);
              return bombsString;
         //create the panel for the bombs label and reset button
         public JPanel newTopPanel(int length)
              int setGridNew [][] = null;
              setGridNew = new int[length][length];
              int getBombsTotalNew = 0;
              JLabel setBombsLabelNew = new JLabel();
              setGridNew = setGrid (length);
              getBombsTotalNew = getBombsTotal (length, setGridNew);
              setBombsLabelNew = setBombsLabel (getBombsTotalNew);
              JPanel topPanel = new JPanel ();
              topPanel.setLayout (new BorderLayout (50,50));
              JLabel bombsLabel = new JLabel ();
              bombsLabel = setBombsLabelNew;     
              topPanel.add (bombsLabel, BorderLayout.WEST);
              buttonReset = new JButton("Reset");
              buttonReset.addActionListener (this);
              topPanel.add (buttonReset, BorderLayout.CENTER);
              return topPanel;
         //create the panel for the play grids
         public JPanel newBottomPanel(int length)
              JButton setButtonGridNew[][] = null;
              setButtonGridNew = new JButton [length][length];
              setButtonGridNew = setButtonGrid (length);
              JPanel bottomPanel = new JPanel ();
              bottomPanel.setLayout (new GridLayout (length, length));
              buttonGrid = new JButton[length][length];          
              for (a = 0; a < length; a++)
                   for (b = 0; b < length; b++)
                        buttonGrid[a] = setButtonGridNew[a][b];
                        buttonGrid[a][b].addActionListener (this);
                        bottomPanel.add (buttonGrid[a][b]);
              return bottomPanel;
         //Overiding of abstract method actionPerformed
         public void actionPerformed(ActionEvent e)
              if (e.getSource() == menuItemNew)
                   launchFrame(length);
              else if (e.getSource() == menuItemExit)
                   frame.setVisible (false);
                   System.exit(0);
              else if (e.getSource() == rbEasy)
                   length = 5;
                   launchFrame(length);
              else if (e.getSource() == rbHard)
                   length = 10;
                   launchFrame(length);     
              else if (e.getSource() == buttonReset)
                   launchFrame(length);
              else if (e.getSource() == buttonGrid[a][b])
                   int setGridNew [][] = null;
                   setGridNew = new int[length][length];               
                   JButton bombButton [][] = null;
                   bombButton = new JButton [length][length];
                   String bombString [][] = null;
                   bombString = new String[length][length];
                   setGridNew = setGrid (length);               
                   bombString[a][b] = setBombs (length, setGridNew, a, b);
                   bombButton[a][b] = new JButton (bombString[a][b]);
                   if (setGridNew[a][b] == 0)
                        buttonGrid[a][b] = bombButton[a][b];
                        getBombsTotal--;
                        JLabel setBombsLabelNew = new JLabel();
                        setBombsLabelNew = setBombsLabel (getBombsTotal);
                   else if (setGridNew[a][b] == 1 )
                        buttonGrid[a][b] = new JButton("x");
                        JOptionPane.showMessageDialog (null, "Game Over. You hit a Bomb!");
                        System.exit(0);     
         //create the content pane
         public Container newContentPane(int length)
              JPanel topPanel = new JPanel();
              JPanel bottomPanel = new JPanel();          
              topPanel = newTopPanel(length);
              bottomPanel = newBottomPanel (length);
              JPanel contentPane = new JPanel();
              contentPane.setOpaque (true);
              contentPane.setLayout (new BorderLayout(50,50));
              contentPane.add (topPanel, BorderLayout.NORTH);
              contentPane.add (bottomPanel, BorderLayout.CENTER);
              return contentPane;
         public void launchFrame (int length)
              //Makes sure we have nice window decorations
              JFrame.setDefaultLookAndFeelDecorated(true);          
              //Sets up the top-level window     
              frame = new JFrame ("Minesweeper");
              //Exits program when the closed button is clicked
              frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              JMenuBar menuBar = new JMenuBar();
              Container contentPane = new Container();
              menuBar = newMenuBar();
              contentPane = newContentPane (length);
              //Sets up the menu bar and content pane
              frame.setJMenuBar (menuBar);
              frame.setContentPane (contentPane);
              //Displays the window
              frame.pack();
              frame.setVisible (true);
         public static void main (String args[])
              //Default length is 5
              length = 5;
              MinesweeperGUI minesweeper = new MinesweeperGUI();
              minesweeper.launchFrame(length);

    hi, thanks. that removed the exception; although now the buttons action listener won't work :(
    here is the revised code:
    To anyone out there, can you guys run this code and help me debug it?
    I'm really desperate as this is a school project of mine and the deadline is 7 hours away. I have already been working on it for 3 days, but the program is still very buggy.
    thanks!
    /* Oliver Ian C. Wee 04-80112
    * CS12 MHRU
    * Machine Problem 2
    package minesweeperGUI;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MinesweeperGUI implements ActionListener
         //Declaration of attributes
         static int length = 0;
         JMenuItem menuItemNew = new JMenuItem();
         JRadioButtonMenuItem rbEasy = new JRadioButtonMenuItem();
         JRadioButtonMenuItem rbHard = new JRadioButtonMenuItem();
         JMenuItem menuItemExit = new JMenuItem();
         JButton buttonReset = new JButton();
         JButton buttonGrid[][] = null;
         JFrame frame = new JFrame();
         int getBombsTotal = 0;
         JLabel setBombsLabel = new JLabel();
         int a = 0;
         int b = 0;
         //No constructor created. Uses default constructor
         //Create the menu bar
         public JMenuBar newMenuBar()
              //Sets up the menubar
              JMenuBar menuBar = new JMenuBar();
              //Sets up the Game menu with choice of new, grid size, and exit
              JMenu menu = new JMenu ("Game");
              menuBar.add (menu);
              menuItemNew = new JMenuItem ("New");
              menuItemNew.addActionListener (this);
              menu.add (menuItemNew);
              menu.addSeparator();
              //Sets up sub-menu for grid size with choice of easy and hard radio buttons
              JMenu subMenu = new JMenu ("Grid Size");
              ButtonGroup bg = new ButtonGroup();
              rbEasy = new JRadioButtonMenuItem ("Easy: 5x5 grid");
              bg.add (rbEasy);
              rbEasy.addActionListener (this);
              subMenu.add (rbEasy);
              rbHard = new JRadioButtonMenuItem ("Hard: 10x10 grid");
              bg.add (rbHard);
              rbHard.addActionListener (this);
              subMenu.add (rbHard);
              menu.add (subMenu);
              menu.addSeparator();
              menuItemExit = new JMenuItem ("Exit");
              menuItemExit.addActionListener (this);
              menu.add (menuItemExit);
              return menuBar;
         //Setting up of Bomb Grid
         public int [][] setGrid (int length)
              int grid[][] = null;
              grid = new int[length][length];
              for (int i = 0; i < length; i++)
                   for (int j = 0; j < length; j++)
                        grid[i][j] = ((int)Math.round(Math.random() * 10))% 2;
              return grid;     
         //Setting up of the of the graphical bomb grid
         public JButton[][] setButtonGrid (int length)
              JButton buttonGrid[][] = null;
              buttonGrid = new JButton[length][length];
              for (int i = 0; i < length; i++)
                   for (int j = 0; j < length; j++)
                        buttonGrid[i][j] = new JButton();
              return buttonGrid;
         //Setting up of a way to count the total number of bombs in the bomb grid
         public int getBombsTotal (int length, int setGrid[][])
              int bombsTotal = 0;
              for (int i = 0; i < length; i++)
                   for (int j = 0; j < length; j++)
                        if (setGrid[i][j] == 1)
                             bombsTotal += 1;
              return bombsTotal;
         //Create a label for number of bombs left
         public JLabel setBombsLabel (int getBombsTotal)
              JLabel bombsLabel = new JLabel("  " +String.valueOf (getBombsTotal) + " Bombs Left");
              return bombsLabel;
         //Setting up a way to count the number of bombs around a button
         public String setBombs (int length, int setGrid[][], int x, int y)
              int bombs[][] = new int[length][length];
              String bombsString = null;
              for (int i = 0; i < length; i++)
                   for (int j = 0; j < length; j++)
                        if (i == 0 && j == 0)
                             bombs[i][j] = setGrid[i][j+1] + setGrid[i+1][j] +
                                  setGrid[i+1][j+1];
                        else if (i ==0 && j == (length - 1))
                             bombs[i][j] = setGrid[i][j-1] + setGrid[i+1][j-1] +
                                  setGrid[i+1][j];
                        else if (i == (length - 1) && j == 0)
                             bombs[i][j] = setGrid[i-1][j] + setGrid[i-1][j+1] +
                                  setGrid[i][j+1];
                        else if (i == (length - 1) && j == (length - 1))
                             bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
                                  setGrid[i][j-1];
                        else if (i == 0 && j != 0 && j != (length - 1))
                             bombs[i][j] = setGrid[i][j-1] + setGrid[i][j+1] +
                                  setGrid[i+1][j-1] + setGrid[i+1][j] +
                                  setGrid[i+1][j+1];
                        else if (i == (length - 1) && j != 0 && j != (length - 1))
                             bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
                                  setGrid[i-1][j+1] + setGrid[i][j-1] +
                                  setGrid[i][j+1];
                        else if (i != 0 && i != (length - 1) && j == 0)
                             bombs[i][j] = setGrid[i-1][j] + setGrid[i-1][j+1] +
                                  setGrid[i][j+1] + setGrid[i+1][j] +
                                  setGrid[i+1][j+1];
                        else if (i != 0 && i != (length - 1) && j == (length - 1))
                             bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
                                  setGrid[i][j-1] + setGrid[i+1][j-1] +
                                  setGrid[i+1][j];
                        else
                             bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
                                  setGrid[i-1][j+1] + setGrid[i][j-1] +
                                  setGrid[i][j+1] + setGrid[i+1][j-1] +
                                  setGrid[i+1][j] + setGrid[i+1][j+1];
              bombsString = String.valueOf (bombs[x][y]);
              return bombsString;
         //create the panel for the bombs label and reset button
         public JPanel newTopPanel(int length)
              int setGridNew [][] = null;
              setGridNew = new int[length][length];
              int getBombsTotalNew = 0;
              JLabel setBombsLabelNew = new JLabel();
              setGridNew = setGrid (length);
              getBombsTotalNew = getBombsTotal (length, setGridNew);
              setBombsLabelNew = setBombsLabel (getBombsTotalNew);
              JPanel topPanel = new JPanel ();
              topPanel.setLayout (new BorderLayout (20,20));
              JLabel bombsLabel = new JLabel ();
              bombsLabel = setBombsLabelNew;     
              topPanel.add (bombsLabel, BorderLayout.WEST);
              buttonReset = new JButton("Reset");
              buttonReset.addActionListener (this);
              topPanel.add (buttonReset, BorderLayout.CENTER);
              return topPanel;
         //create the panel for the play grids
         public JPanel newBottomPanel(int length)
              JButton setButtonGridNew[][] = null;
              setButtonGridNew = new JButton [length][length];
              setButtonGridNew = setButtonGrid (length);
              JPanel bottomPanel = new JPanel ();
              bottomPanel.setLayout (new GridLayout (length, length));
              buttonGrid = new JButton[length][length];          
              for (int i = 0; i < length; i++)
                   for (int j = 0; j < length; j++)
                        buttonGrid[i][j] = setButtonGridNew[i][j];
                        buttonGrid[i][j].addActionListener (this);
                        bottomPanel.add (buttonGrid[i][j]);
              return bottomPanel;
         //Overiding of abstract method actionPerformed
         public void actionPerformed(ActionEvent e)
              if (e.getSource() == menuItemNew)
                   closeFrame();
                   launchFrame(length);
              else if (e.getSource() == menuItemExit)
                   frame.setVisible (false);
                   System.exit(0);
              else if (e.getSource() == rbEasy)
                   closeFrame();
                   length = 5;
                   launchFrame(length);
              else if (e.getSource() == rbHard)
                   closeFrame();
                   length = 10;
                   launchFrame(length);     
              else if (e.getSource() == buttonReset)
                   closeFrame();
                   launchFrame(length);
              else if (e.getSource() == buttonGrid[a])
                   int setGridNew [][] = null;
                   setGridNew = new int[length][length];               
                   JButton bombButton [][] = null;
                   bombButton = new JButton [length][length];
                   String bombString [][] = null;
                   bombString = new String[length][length];
                   setGridNew = setGrid (length);               
                   for (int i = 0; i < length; i++)
                        for (int j = 0; j < length; j++)
                             bombString[i][j] = setBombs (length, setGridNew, i, j);
                             bombButton[i][j] = new JButton (bombString[i][j]);
                   if (setGridNew[a][b] == 0)
                        buttonGrid[a][b] = bombButton[a][b];
                        getBombsTotal--;
                        JLabel setBombsLabelNew = new JLabel();
                        setBombsLabelNew = setBombsLabel (" " String.valueOf (getBombsTotal) " Bombs Left");
                   else if (setGridNew[a][b] == 1 )
                        buttonGrid[a][b] = new JButton("x");
                        JOptionPane.showMessageDialog (null, "Game Over. You hit a Bomb!");
                        System.exit(0);     
         //create the content pane
         public Container newContentPane(int length)
              JPanel topPanel = new JPanel();
              JPanel bottomPanel = new JPanel();          
              topPanel = newTopPanel(length);
              bottomPanel = newBottomPanel (length);
              JPanel contentPane = new JPanel();
              contentPane.setOpaque (true);
              contentPane.setLayout (new BorderLayout(5,5));
              contentPane.add (topPanel, BorderLayout.NORTH);
              contentPane.add (bottomPanel, BorderLayout.CENTER);
              return contentPane;
         public void closeFrame ()
              frame = new JFrame ("Minesweeper");
              frame.dispose();
         public void launchFrame (int length)
              //Makes sure we have nice window decorations
              JFrame.setDefaultLookAndFeelDecorated(true);          
              //Sets up the top-level window     
              frame = new JFrame ("Minesweeper");
              //Exits program when the closed button is clicked
              frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              JMenuBar menuBar = new JMenuBar();
              Container contentPane = new Container();
              menuBar = newMenuBar();
              contentPane = newContentPane (length);
              //Sets up the menu bar and content pane
              frame.setJMenuBar (menuBar);
              frame.setContentPane (contentPane);
              //Displays the window
              frame.pack();
              frame.setVisible (true);
         public static void main (String args[])
              //Default length is 5
              length = 5;
              MinesweeperGUI minesweeper = new MinesweeperGUI();
              minesweeper.launchFrame(length);

  • Adding a "Page" effect to an Internal Frame

    Hi all,
    This topic is in the 2D thread but i have possibly used the wrong forum.
    I am developing a gui that uses an internal frames as a user workspace.
    The internal frame has a canvas on it an i was intending to add 2D objects to the canvas . EG a UML editor.
    I want the canvas(Do i need a canvas or may i add 2D objects directly to the frame, or use a jpanel to keep all the components swing?) to look similar to a word/ visio application
    where there is an A4/ letter /A3... Page on the internal Frame. If the user creates a 'New' project a new InternalFrame object is created with the "blank" document waiting for a creative touch ;)
    and goto begining...
    I have the GUI upp and running so far but can find any ideas on how to implement the "Word Doc" type internal look.
    I susspect i am correct in saying that i can use scale to "Zoom" in and out of the document.
    any suggestions would be most welcome.
    Regards,
    Graham

    Here is a working sample.
    Only 2 classes are left, the Destop class was useless.
    See how actions are managed (I implemented the "New" function)
    I leave you the imagination for the rest...
    GUIMainFrame.java:
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JDesktopPane;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JToolBar;
    public class GUIMainFrame extends JFrame {
       public JMenuBar menuBar = new JMenuBar();
       public JToolBar toolbar = new JToolBar();
       public JDesktopPane desktop = new JDesktopPane();
       public GUIMainFrame() {
          super("UML database Design Editor");
          initComponents();
          this.setName("GUIMain");
       private JMenu createMenu(String title, int nbitems) {
          JMenu menu = new JMenu(title);
          for (int i=0; i<nbitems; i++) {
             JMenuItem item = new  JMenuItem("option "+i);
             menu.add(item);
          return menu;
       private JButton createButton(Action action) {
          JButton button = new JButton(action);
          return button;
       private void initComponents() {
          setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
          menuBar.add(createMenu("File", 5));
          menuBar.add(createMenu("Edit", 3));
          menuBar.add(createMenu("Help", 1));
          setJMenuBar(menuBar);
          toolbar.add(createButton(new DesktopAction("new")));
          toolbar.add(createButton(new DesktopAction("open")));
          toolbar.add(createButton(new DesktopAction("save")));
          this.getContentPane().add(toolbar, BorderLayout.NORTH);
          this.getContentPane().add(desktop, BorderLayout.CENTER);
          this.setSize(400,400);
          this.setVisible(true);
       public static void main(String[] args) {
          new GUIMainFrame();
       // Manages actions sent to the application
       private void doAction(String name) {
           if (name.equals("new")) {
              Project project = new Project();
              desktop.add(project);
              project.toFront();
              project.setVisible(true);
           else if (name.equals("open")) {
           else if (name.equals("save")) {
       // Class defining the actions to send to the application
       private class DesktopAction extends AbstractAction {
          public DesktopAction(String name) {
             super(name, new ImageIcon(name + "16.gif"));
          /* (non-Javadoc)
           * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
          public void actionPerformed(ActionEvent event) {
             // the action is only redispatched to the application
             doAction(event.getActionCommand());
    Project.java:
    import java.awt.Color;
    import java.awt.Dimension;
    import javax.swing.JInternalFrame;
    import javax.swing.JPanel;
    public class Project extends JInternalFrame {
       static int projectCount = 0, projectX = 20, projectY = 20;
       /** Creates a new instance of Project */
       public Project() {
          super("Project: " + (++projectCount), true,   //resizable
                   true,   //closable
                   true,   //maximizable
                   true);  //iconifiable
          JPanel p = new JPanel();
          p.setOpaque(true);
          p.setBackground(Color.WHITE);    
          p.setPreferredSize(new Dimension(200, 200));
          this.setLocation(projectX, projectY);
          this.setContentPane(p);
          this.pack();
          projectX += 20;
          if (projectX >= 220) {
             projectX= 20;
             projectY += 20;
    }Regards.

  • It works as an app but not as an applet!

    First of all many thanks to this forum for the help I have received already, this is true community spirit in action.
    Right I am writing a program that works both as an application and as an applet. It is starting to take shape, what I have so far is a text area and a button for pasting the contents of the clipboard to the text area. The code pastes perfectly when run as an application but when I try the code in a browser it does not seem to paste the clipboard contents into the text area. Any help gratefuly received, Dave.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.datatransfer.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class BigRedsBanBuster extends JApplet implements ClipboardOwner,ItemListener,ActionListener
         JTextArea data=new JTextArea(20,60);
         JButton action=new JButton("Hit Me!");
      JLabel area=new JLabel("Copy file to Clipboard and the press Hit Me!");
      JScrollPane scroll= new JScrollPane(data,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
         public void init()
           FlowLayout fL=new FlowLayout();
        Container contentArea=getContentPane();
        contentArea.setLayout(fL);
        setVisible(true);
        contentArea.setBackground(Color.blue);
              contentArea.add(area);
              contentArea.add(scroll);
              contentArea.add(action);
              action.addActionListener(this);
         public void actionPerformed(ActionEvent e)
           if (e.getSource()==action)
                paste();
         public void paste()
        Clipboard c = this.getToolkit().getSystemClipboard();
           Transferable t = c.getContents(this);
           try
             if (t.isDataFlavorSupported(DataFlavor.stringFlavor))
                  String s = (String) t.getTransferData(DataFlavor.stringFlavor);
                  data.setText(s);
             else if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
                  java.util.List files = (java.util.List)
                  t.getTransferData(DataFlavor.javaFileListFlavor);
                  java.io.File file = (java.io.File)files.get(0);
                  data.setText(file.getName());
           catch (Exception e)
             this.getToolkit().beep();
      public void itemStateChanged(ItemEvent e)
      public void lostOwnership(Clipboard c, Transferable t)
      public static void main(String args[])
           BigRedsBanBuster brbb=new BigRedsBanBuster();
        JFrame f=new JFrame();
           brbb.init();
           f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.setContentPane( brbb.getContentPane() );
        f.setSize(1000,600);
        f.addWindowListener(new java.awt.event.WindowAdapter()
          public void windowClosing(java.awt.event.WindowEvent evt)
            System.exit(0);
        f.show();
    }P.S. Excuse the warped indentation caused through copy & paste.

    There is a security error. I am not sure that an Applet can access the clipboard.
    Here is the error generated:
    java.security.AccessControlException: access denied (java.awt.AWTPermission accessClipboard)
         at java.security.AccessControlContext.checkPermission(AccessControlContext.java:270)
         at java.security.AccessController.checkPermission(AccessController.java:401)
         at java.lang.SecurityManager.checkPermission(SecurityManager.java:542)
         at java.lang.SecurityManager.checkSystemClipboardAccess(SecurityManager.java:1387)
         at sun.awt.windows.WToolkit.getSystemClipboard(WToolkit.java:632)
         at untitled5.BigRedsBanBuster.paste(BigRedsBanBuster.java:43)
         at untitled5.BigRedsBanBuster.actionPerformed(BigRedsBanBuster.java:38)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1767)
         at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1820)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:419)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:258)
         at java.awt.Component.processMouseEvent(Component.java:5021)
         at java.awt.Component.processEvent(Component.java:4818)
         at java.awt.Container.processEvent(Container.java:1525)
         at java.awt.Component.dispatchEventImpl(Component.java:3526)
         at java.awt.Container.dispatchEventImpl(Container.java:1582)
         at java.awt.Component.dispatchEvent(Component.java:3367)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3359)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3074)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3004)
         at java.awt.Container.dispatchEventImpl(Container.java:1568)
         at java.awt.Component.dispatchEvent(Component.java:3367)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:445)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:191)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)

  • How to send a mail by ckicking the button using java

    hi,
    how to send a mail by clicking the button (like payroll silp in that contain one button if we click that it autometically go through the mail as a attachment) pls frd to me my gmail is [email protected]

    Hi,
    It seems we are doing the homework for you; to make you start with something; look at the sample code below and try to understand it first then put the right values
    to send an email with an attachement.
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.util.Date;
    import java.util.Properties;
    import javax.activation.DataHandler;
    import javax.activation.FileDataSource;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Multipart;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    public class Main {
          * @param args
         public static void main(String[] args) {
              // Create the frame
              String title = "Frame Title";
              JFrame frame = new JFrame(title);
              // Create a component to add to the frame
              JComponent comp = new JTextField();
              Action action = new AbstractAction("Button Label") {
                   // This method is called when the button is pressed
                   public void actionPerformed(ActionEvent evt) {
                        System.out.println("sending email with attachment");
                        sendEmail();
              // Create the button
              JButton button = new JButton(action);
              // Add the component to the frame's content pane;
              // by default, the content pane has a border layout
              frame.getContentPane().add(comp, BorderLayout.SOUTH);
              frame.getContentPane().add(button, BorderLayout.NORTH);
              // Show the frame
              int width = 300;
              int height = 300;
              frame.setSize(width, height);
              frame.setVisible(true);
         protected static void sendEmail() {
              String from = "me@localhost";
              String to = "me@localhost";
              String subject = "Important Message";
              String bodyText = "This is a important message with attachment";
              String filename = "c:\\tmp\\message.pdf";
              Properties properties = new Properties();
              properties.put("mail.stmp.host", "localhost");
              properties.put("mail.smtp.port", "25");
              Session session = Session.getDefaultInstance(properties, null);
              try {
                   MimeMessage message = new MimeMessage(session);
                   message.setFrom(new InternetAddress(from));
                   message.setRecipient(Message.RecipientType.TO, new InternetAddress(
                             to));
                   message.setSubject(subject);
                   message.setSentDate(new Date());
                   // Set the email message text.
                   MimeBodyPart messagePart = new MimeBodyPart();
                   messagePart.setText(bodyText);
                   // Set the email attachment file
                   MimeBodyPart attachmentPart = new MimeBodyPart();
                   FileDataSource fileDataSource = new FileDataSource(filename) {
                        @Override
                        public String getContentType() {
                             return "application/octet-stream";
                   attachmentPart.setDataHandler(new DataHandler(fileDataSource));
                   attachmentPart.setFileName(filename);
                   Multipart multipart = new MimeMultipart();
                   multipart.addBodyPart(messagePart);
                   multipart.addBodyPart(attachmentPart);
                   message.setContent(multipart);
                   Transport.send(message);
              } catch (MessagingException e) {
                   e.printStackTrace();
    }The sample above is not ideal so you need to go through it and start to ask me some questions if you have
    Let me know if you miss something
    Regards,
    Alan Mehio
    London,UK

  • Problem with Enter key and JOptionPane in 1.4

    Hi,
    I had a problem with an application I was working on.
    In this application, pressing [Enter] anywhere within the focused window would submit the information entered into the form that was contained within the frame.
    The application would then try to validate the data. If it was found to be invalid, it would pop up a JOptionPane informing the user of that fact.
    By default, pressing [Enter] when a JOptionPane is up will activate the focused button (in most cases, the [OK] button) thus dismissing the dialog.
    In JDK 1.3 this worked fine. But in JDK 1.4, this has the result of dismissing the dialog and opping it up again. This is because the [Enter] key still works on the frame behind the JOptionPane and thus tries to validate it again, which results in another invalid dialog msg popping up.
    The only way to get out is to use the mouse or the Esc key.
    Now, in the application I put in a workaround that I was not very happy with. So, to make sure it wasn't the application itself, I created a test which demonstrates that it still misbehaves.
    Here it is.
    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.AbstractAction;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.WindowConstants;
    * @author avromf
    public class FocusProblemTest extends AbstractAction
         private static JFrame frame;
         public FocusProblemTest()
              super();
              putValue(NAME, "Test");
         public void actionPerformed(ActionEvent e)
              JOptionPane.showMessageDialog(frame, "This is a test.");
         public static void main(String[] args)
              FocusProblemTest action= new FocusProblemTest();
              try
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e)
                   e.printStackTrace();
              frame= new JFrame("Test");
              frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
              Container contents= frame.getContentPane();
              contents.setLayout(new FlowLayout());
              JTextField field= new JTextField("Test");
              field.setColumns(30);
              JButton  button= new JButton(action);
              KeyStroke enterKey = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true);
              button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(enterKey, "test");
              button.getActionMap().put("test", action);
              contents.add(field);
              contents.add(button);
              frame.pack();
              frame.setVisible(true);
    }Does anyone have any solution to this problem?

    I know that focus management has changed alot.
    Based on my experimentation a while back, in 1.4 it still believes that the JFrame is the window in focus, even though a JOptionPane is currently in front of it (unless I misinterpreted what was going on). Thus, the frame seems to get the keyboard event and re-invoke the action.
    A.F.

  • Adding mouselisteners to JPanels created through for loop

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.io.File;
    import java.io.IOException;
    import java.util.Vector;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JViewport;
    import javax.swing.SwingConstants;
    import javax.swing.filechooser.FileSystemView;
    public class ScrollableWrapTest {
        public static void main(String[] args) {
            try {
                  ScrollableWrapTest st = new ScrollableWrapTest();
                final JPanel mainPanel = new JPanel(new WrapScollableLayout(FlowLayout.LEFT, 10, 10));
                mainPanel.setBackground(Color.WHITE);
                JScrollPane pane = new JScrollPane(mainPanel);
                pane.setPreferredSize(new Dimension(550, 300));
                Vector v = new Vector();
                v.add("first.doc");
                v.add("second.txt");
                v.add("third.pdf");
                v.add("fourth.rar");
                v.add("fifth.zip");
                v.add("sixth.folder");
                v.add("seventh.exe");
                v.add("eighth.bmp");
                v.add("nineth.jpeg");
                v.add("tenth.wav");
                JButton button = null;
                for(int i =0;i<v.size();i++){
                    JPanel panel = new JPanel(new BorderLayout());
                    Icon icon = st.getIcone(st.getExtension(v.elementAt(i).toString().toUpperCase()));
                      panel.setBackground(Color.WHITE);
                     Action action = new AbstractAction("", icon) {
                         public void actionPerformed(ActionEvent evt) {
                     button = new JButton(action);
                     button.setPreferredSize(new Dimension(icon.getIconWidth(), icon.getIconHeight()));
                     JPanel buttonPanel = new JPanel();
                     buttonPanel.setBackground(Color.WHITE);
                     buttonPanel.add(button);
                     JLabel label = new JLabel((String)v.elementAt(i));
                     label.setHorizontalAlignment(SwingConstants.CENTER);
                     panel.add(buttonPanel , BorderLayout.NORTH);
                     panel.add(label, BorderLayout.SOUTH);
                     mainPanel.add(panel);
                    mainPanel.revalidate();
                st.buildGUI(pane);
            } catch (Exception e) {e.printStackTrace();}
        public void buildGUI(JScrollPane scrollPane)
             JFrame frame = new JFrame("Scrollable Wrap Test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(scrollPane, BorderLayout.CENTER);
            frame.setLocationRelativeTo(null);
            frame.pack();
            frame.setVisible(true);
        public String getExtension(String name)
              if(name.lastIndexOf(".")!=-1)
                   String extensionPossible = name.substring(name.lastIndexOf(".")+1, name.length());
                   if(extensionPossible.length()>5)
                        return "";
                   else
                        return extensionPossible;
              else return "";
         public Icon getIcone(String extension)
              //we create a temporary file on the local file system with the specified extension
              File file;
              String cheminIcone = "";
              if(((System.getProperties().get("os.name").toString()).startsWith("Mac")))
                   cheminIcone = System.getProperties().getProperty("file.separator");
              else if(((System.getProperties().get("os.name").toString()).startsWith("Linux")))
                   //cheminIcone = FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath()+
                   cheminIcone = "/"+"tmp"+"/BoooDrive-"+System.getProperty("user.name")+"/";
              else cheminIcone = System.getenv("TEMP") + System.getProperties().getProperty("file.separator");
              File repIcone = new File(cheminIcone);
              if(!repIcone.exists()) repIcone.mkdirs();
              try
                   if(extension.equals("FOLDER"))
                        file = new File(cheminIcone + "icon");
                        file.mkdir();
                   else
                        file = new File(cheminIcone + "icon." + extension.toLowerCase());
                        file.createNewFile();
                   //then we get the SystemIcon for this temporary File
                   Icon icone = FileSystemView.getFileSystemView().getSystemIcon(file);
                   //then we delete the temporary file
                   file.delete();
                   return icone;
              catch (IOException e){ }
              return null;
        private static class WrapScollableLayout extends FlowLayout {
            public WrapScollableLayout(int align, int hgap, int vgap) {
                super(align, hgap, vgap);
            public Dimension preferredLayoutSize(Container target) {
                synchronized (target.getTreeLock()) {
                    Dimension dim = super.preferredLayoutSize(target);
                    layoutContainer(target);
                    int nmembers = target.getComponentCount();
                    for (int i = 0 ; i < nmembers ; i++) {
                        Component m = target.getComponent(i);
                        if (m.isVisible()) {
                            Dimension d = m.getPreferredSize();
                            dim.height = Math.max(dim.height, d.height + m.getY());
                    if (target.getParent() instanceof JViewport)
                        dim.width = ((JViewport) target.getParent()).getExtentSize().width;
                    Insets insets = target.getInsets();
                    dim.height += insets.top + insets.bottom + getVgap();
                    return dim;
    }How can I add mouse listener to each of the 'panel' in 'mainpanel' created inside the 'for loop' using the code mainPanel.add(panel);Rony

    >
    How can I add mouse listener to each of the 'panel' in 'mainpanel' created inside the 'for loop' using the code mainPanel.add(panel);
    Change the first part of the code like this..
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.io.File;
    import java.io.IOException;
    import java.util.Vector;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JViewport;
    import javax.swing.SwingConstants;
    import javax.swing.filechooser.FileSystemView;
    public class ScrollableWrapTest {
        public static void main(String[] args) {
            try {
                  ScrollableWrapTest st = new ScrollableWrapTest();
                final JPanel mainPanel = new JPanel(new WrapScollableLayout(FlowLayout.LEFT, 10, 10));
                mainPanel.setBackground(Color.WHITE);
                JScrollPane pane = new JScrollPane(mainPanel);
                pane.setPreferredSize(new Dimension(550, 300));
                Vector<String> v = new Vector<String>();
                v.add("first.doc");
                v.add("second.txt");
                v.add("third.pdf");
                v.add("fourth.rar");
                v.add("fifth.zip");
                v.add("sixth.folder");
                v.add("seventh.exe");
                v.add("eighth.bmp");
                v.add("nineth.jpeg");
                v.add("tenth.wav");
                JButton button = null;
                MouseListener ml = new MouseAdapter() {
                        @Override
                        public void mouseClicked(MouseEvent me) {
                             System.out.println(me);
                for(int i =0;i<v.size();i++){
                    JPanel panel = new JPanel(new BorderLayout());
                    Icon icon = st.getIcone(st.getExtension(v.elementAt(i).toString().toUpperCase()));
                      panel.setBackground(Color.WHITE);
                     Action action = new AbstractAction("", icon) {
                         public void actionPerformed(ActionEvent evt) {
                     button = new JButton(action);
                     button.setPreferredSize(new Dimension(icon.getIconWidth(), icon.getIconHeight()));
                     JPanel buttonPanel = new JPanel();
                     buttonPanel.setBackground(Color.WHITE);
                     buttonPanel.add(button);
                     JLabel label = new JLabel((String)v.elementAt(i));
                     label.setHorizontalAlignment(SwingConstants.CENTER);
                     panel.add(buttonPanel , BorderLayout.NORTH);
                     panel.add(label, BorderLayout.SOUTH);
                     mainPanel.add(panel);
                     panel.addMouseListener( ml );
                    mainPanel.revalidate();
                st.buildGUI(pane);
            } catch (Exception e) {e.printStackTrace();}
    ...

Maybe you are looking for

  • Signature in Logic Post

    Ok, this is not a direct Logic question but rather a question about posting on the Logic Forum. After the latest redesign of the Forum, there is no signature field any more that gets added automatically at the end of the post. If I understand correct

  • IChat and external webcam

    We have been using iUSBCam (http://www.ecamm.com/mac/iusbcam/) with our intel iMac's running OS X Leopard (10.5). This allowed us to change the video settings from within iChat to switch between the built-in isight camera and an external usb camera.

  • Arrayindexoutofbound exception in rfc

    hello every body, i am calling one abap function module from webdynpro.In the function module , i have 3 importing parameters(employ no,name and status) and one table parameter.status is one of the importing parameter there i am passing the type of o

  • Is Itunes 8.2 better than the previous one?

    If I download Itunes 8.2 and I decide I don't like it,would I be able to restore 8.1.1.

  • PS CS3 uns AE CS3 aktivierung auf neuem iMac nicht möglich

    ich habe einen neuen iMac 21" und die Daten von dem alten iMac migriert. Nun kann ich PS CS3 und AE CS3 nicht mehr aktivieren. Bei dem Versuch es über das Internet zu tun, kommt die Meldung "keine Verbindung". Die 7 Tage sind schon rum.. was kann ich