AbstractAction -- JButton

class QueryAction extends AbstractAction
// Constructor
QueryAction(String name)
super(name);
String iconFileName = "Images/" + name + ".gif";
if(new File(iconFileName).exists())
putValue(SMALL_ICON, new ImageIcon(iconFileName));
public void aFunc(){
QueryAction anAction = new QueryAction("Compile Query");
JButton button = new JButton(anAction);
toolBar.add(button);
in other function, I'm trying to disable the button with that particular description string (i.e. "Compile Query"):
Component[] comp = toolBar.getComponents();
for (int i=0; i<comp.length; i++){
JButton aButton = (JButton)comp;
Action act = aButton.getAction();
if(act.getValue(Action.NAME).equals("Compile Query"));
aButton.setEnable(false);
break;
But I got NullPointerException for the statement :
act.getValue(Action.NAME)
Anybody has an idea how to solve this...?? thx

Seems to me that your toolBar contains a button which has no action assigned to it.
Try this: keep a reference to your QueryAction in your class and disable it instead of the button (this feature is one of the reason to use actions afterall):
public class XYPanel {
  private QueryAction queryAction = new QueryAction();
  private class QueryAction {
    public QueryAction() {
      super("Compile Query");
    // how about using a class resource instead of a file
    // - better for using jars in your app
    putValue(SMALL_ICON, new ImageIcon(getClass().getResource("query.gif")));  
  public void aFunc() {
    toolBar.add(queryAction);
  public void anotherFunc()
    queryAction.setEnabled(false);

Similar Messages

  • Problem AbstractAction - JButton.setRolloverIcon()

    Hi,
    Since i (and i don't understand why) couldn't really find anything in google, or in this forum search, i'm requesting you guys' help
    Here's a brief description of the problem:
    When just using a JButton (with some text on it), without any Actions assigned to it, it's no problem at all to assign a disabledIcon, rolloverIcon (setDisabledIcon, setRolloverIcon) to the button.
    BUT
    once you apply an action class to it (in my case i'm extending my action class from AbstractAction), things go wrong:
    - Apparently, you CAN pass on an Icon (the default icon on the image) to the action class, and then calling the super(String command, Icon icon) constructor.
    - But how to set a disabledIcon or rolloverIcon using this action class ? You can't pass this on the the super constructor like the default icon. I'm really not seeing what i 'm doing wrong here :-(
    Thanks in advance for your replies and help,
    Regards,
    Sander
    PS: i'm new to this forum, if i'm giving you guys to little information, please let me know.

    but using action isn't the best idea. The benefit of using an Action is that it can be shared by multiple components. A typical GUI design would have a menu item and a toolbar button to invoke the same action. The coding is easy:
    Action someAction = new SomeAction(...);
    JMenuItem someItem = new JMenuItem( someAction );
    JButton someButton = new JButton( someAction );
    If you ever need to disable the Action you would do:
    someAction.setEnable( false );
    and the menu item and toolbar button would both be updated.

  • Problem with KeyAdapter and JButtons in a Jframe

    yes hi
    i have searched almost most of the threads here but nothing
    am trying to make my frame accepts keypress and also have some button on the frame here is the code and thank you for the all the help
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class RPg extends JFrame implements ActionListener
                private int width;
                private int hight;
                public    JPanel north;
                public    JPanel se;
                public    JButton start;
                public    JButton quit;
                public    Screen s;//a Jpanel
                public    KeyStrokeHandler x;
        public RPg() {
               init();
               setTitle("RPG");
               setSize(width,hight);
               setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               setResizable(false);
               setVisible(true);
               x=new KeyStrokeHandler();
             addKeyListener(x);
             public void init() {
               north=new JPanel();
               Container cp = getContentPane();
               s=new Screen();
               this.width=s.width;
               this.hight=s.hight+60;
              start=new JButton("START");
                  start.addActionListener(this);
              quit=new JButton("QUIT");
                  quit.addActionListener(this);
              north.setBackground(Color.DARK_GRAY);
              north.setLayout(new FlowLayout());
              north.add(start);
              north.add(quit);
              cp.add(north, BorderLayout.NORTH);
              cp.add(s, BorderLayout.CENTER);
        public static void main(String[] args) {
            RPg rpg = new RPg();
       public void actionPerformed(ActionEvent ae) {
            if (ae.getActionCommand().equals("QUIT")) {
                     System.exit(0);
            if (ae.getActionCommand().equals("START")) { }
       class KeyStrokeHandler extends KeyAdapter {
               public void keyTyped(KeyEvent ke) {}
               public void keyPressed(KeyEvent ke){
                  int keyCode = ke.getKeyCode();
                  if ((keyCode == KeyEvent.VK_M)){
                     System.out.println("it works");
               public void keyReleased(KeyEvent ke){}

    Use the 'tab' key to navigate through 'contentPane > start > quit' focus cycle. 'M' key works when focus is on contentPane (which it is on first showing). See tutorial pages on 'Using Key Bindings' and 'Focus Subsystem' for more.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class RPG extends JFrame implements ActionListener {
        private int width;
        private int hight;
        public JPanel north;
        public JPanel se;
        public JButton start;
        public JButton quit;
        public Screen s;    //a Jpanel
        public RPG() {
            init();
            setTitle("RPG");
            setSize(width,hight);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setResizable(false);
            setVisible(true);
        public void init() {
            north=new JPanel();
            Container cp = getContentPane();
            registerKeys((JComponent)cp);
            s=new Screen();
            this.width=s.width;
            this.hight=s.hight+60;
            start=new JButton("START");
                start.addActionListener(this);
            quit=new JButton("QUIT");
                quit.addActionListener(this);
            north.setBackground(Color.DARK_GRAY);
            north.setLayout(new FlowLayout());
            north.add(start);
            north.add(quit);
            cp.add(north, BorderLayout.NORTH);
            cp.add(s, BorderLayout.CENTER);
        public static void main(String[] args) {
            RPG rpg = new RPG();
        public void actionPerformed(ActionEvent ae) {
            if (ae.getActionCommand().equals("QUIT")) {
                     System.exit(0);
            if (ae.getActionCommand().equals("START")) { }
        private void registerKeys(JComponent jc)
            jc.getInputMap().put(KeyStroke.getKeyStroke("M"), "M");
            jc.getActionMap().put("M", mAction);
        Action mAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("it works");
    class Screen extends JPanel {
        int width, hight;
        public Screen() {
            width = 300;
            hight = 300;
            setBackground(Color.pink);
    }

  • 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 preven JButton of generated actions when the user keep pressing down

    How to preven JButton of generated actions when the user keep pressing down the key or the short cut
    The code below to show the issue when the user keep pressing Alt+ O
    We want to prevent the JButton from generating multi actions just one action only
    A sample of code shows the behaviour which has to be prevented. Continue pressing "Alt +O" and you will see the standard ouptput will print time stamps
    Please notice, I am NOT interested in Mouse press which has a solution by adding a threshold ( setMultiClickThreshhold(long threshhold) on the JButton  as an attribute.
    public class TestPanel extends JPanel
       private JButton btn;
       public TestPanel()
          btn = new JButton("Open");
          this.add(btn);
          registerCommand(new MyAction(), InputEvent.ALT_MASK,
                KeyEvent.VK_O, btn, btn.getText(), 0);
       public static void registerCommand(AbstractAction action,
             int mask,
             int shortCommand,
             JComponent component,
             String actionName,
             int mnemonicIndex)
          InputMap inputMap = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
          KeyStroke knappKombination = KeyStroke.getKeyStroke(shortCommand, mask);
          if ((component instanceof AbstractButton)
                && mnemonicIndex >= 0
                && mnemonicIndex < actionName.length()
                && (shortCommand >= KeyEvent.VK_A && shortCommand <= KeyEvent.VK_Z))
             ((AbstractButton) component).setDisplayedMnemonicIndex(mnemonicIndex);
          if (inputMap != null)
             ActionMap actionMap = component.getActionMap();
             inputMap.put(knappKombination, actionName);
             if (actionMap != null)
                actionMap.put(actionName, action);
       public static class MyAction extends AbstractAction
          private static final long serialVersionUID = 1L;
          @Override
          public void actionPerformed(ActionEvent e)
             System.out.println(System.currentTimeMillis());
       public static void main(String... args)
          SwingUtilities.invokeLater(new Runnable()
             public void run()
                JFrame frame = new JFrame("Testing");
                JPanel panel = new TestPanel();
                frame.getContentPane().add(panel);
                frame.setPreferredSize(new Dimension(500, 500));
                frame.setMinimumSize(new Dimension(500, 500));
                frame.pack();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
    }Edited by: user12130673 on 2013-feb-13 03:01

    Use KeyStroke getKeyStroke(int keyCode, int modifiers, boolean onKeyRelease) with onKeyRelease=true instead?

  • Multiple JButtons in a JTable cell: handling events

    Hello!
    I'm trying to develop a Swing application which makes use of tables in several panels.
    Each row of each table should present the user two buttons, one for editing the row, one for viewing details of that row. Both editing and viewing are done in another panel.
    I thought I could add the buttons as the last column of each row, so I made a panel which holds the two buttons and the id of the row, so that I know what I have to edit or view.
    I managed to insert the panel as the last column, but I can't have the buttons click.
    I studied cell renderers and editors from several tutorials and examples, but evidently I can't understand either of them: whatever I try doesn't change the outcome... :(
    Below is the code I use, except for imports and packages:
    ActionPanel.java - The panel which holds the buttons and the row id
    public class ActionPanel extends JPanel{
      private static final long serialVersionUID = 1L;
      public static String ACTION_VIEW="view";
      public static String ACTION_EDIT="edit";
      private String id;
      private JButton editButton;
      private JButton viewButton;
      public String getId() {
        return id;
      public void setId(String id) {
        this.id = id;
      public JButton getEditButton() {
        return editButton;
      public void setEditButton(JButton editButton) {
        this.editButton = editButton;
      public JButton getViewButton() {
        return viewButton;
      public void setViewButton(JButton viewButton) {
        this.viewButton = viewButton;
      public ActionPanel() {
        super();
        init();
      public ActionPanel(String id) {
        super();
        this.id = id;
        init();
      private void init(){
        setLayout(new FlowLayout(FlowLayout.CENTER, 10, 0))
        editButton=new JButton(new ImageIcon("./images/icons/editButtonIcon.png"));
        editButton.setBorderPainted(false);
        editButton.setOpaque(false);
        editButton.setAlignmentX(TOP_ALIGNMENT);
        editButton.setMargin(new Insets(0,0,0,0));
        editButton.setSize(new Dimension(16,16));
        editButton.setMaximumSize(new Dimension(16, 16));
        editButton.setActionCommand(ACTION_EDIT);
        editButton.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, id, "Editing", JOptionPane.INFORMATION_MESSAGE);
        viewButton=new JButton(new ImageIcon("./images/icons/viewButtonIcon.png"));
        viewButton.setMaximumSize(new Dimension(16, 16));
        viewButton.setActionCommand(ACTION_VIEW);
        viewButton.setBorderPainted(false);
        viewButton.setOpaque(false);
        viewButton.setMargin(new Insets(0,0,0,0));
        viewButton.setSize(new Dimension(16,16));
        viewButton.setMaximumSize(new Dimension(16, 16));
        viewButton.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, id, "Viewing", JOptionPane.INFORMATION_MESSAGE);
        add(viewButton);
        add(editButton);
    ActionPanelRenerer.java - the renderer for the above panel
    public class ActionPanelRenderer implements TableCellRenderer{
      public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        Component ret=(Component)value;
        if (isSelected) {
          ret.setForeground(table.getSelectionForeground());
          ret.setBackground(table.getSelectionBackground());
        } else {
          ret.setForeground(table.getForeground());
          ret.setBackground(UIManager.getColor("Button.background"));
        return ret;
    ActionPanelEditor.java - this is the editor, I can't figure out how to implement it!!!!
    public class ActionPanelEditor extends AbstractCellEditor implements TableCellEditor{
      public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column) {
        return (ActionPanel)value;
      public Object getCellEditorValue() {
        return null;
    ServicesModel.java - The way I fill the table is through a model:
    public class ServicesModel extends AbstractTableModel  {
      private Object[][] data;
      private String[] headers;
      public ServicesModel(Object[][] services, String[] headers) {
        this.data=services;
        this.headers=headers;
      public int getColumnCount() {
        return headers.length;
      public int getRowCount() {
        return data.length;
      public Object getValueAt(int row, int col) {
        if(col==data.length-1)
          return new ActionPanel(""+col);
        else
          return data[row][col];
      public boolean isCellEditable(int row, int col) {
        return false;
      public Class getColumnClass(int column) {
        return getValueAt(0, column).getClass();
    ServicesList.java - The panel which holds the table (BasePanel is a custom class, not related to the table)
    public class ServicesList extends BasePanel {
      private JLabel label;
      private JTable grid;
      public ServicesList(SessionManager sessionManager){
        super(sessionManager);
        grid=new JTable() ;
        add(new JScrollPane(grid), BorderLayout.CENTER);
        layoutComponents();
      public void layoutComponents(){
        ConfigAccessor dao=new ConfigAccessor(connectionUrl, connectionUser, connectionPass);
        String[] headers=I18N.get(dao.getServiceLabels());
        grid.setModel(new ServicesModel(dao.getServices(), headers));
        grid.setRowHeight(20);
        grid.getColumnModel().getColumn(headers.length-1).setCellRenderer(new ActionPanelRenderer());
        grid.setDefaultEditor(ActionPanel.class, new ActionPanelEditor());
        grid.removeColumn(grid.getColumnModel().getColumn(0));
        dao.close();
    }Please can anyone at least address me to what I'm doing wrong? Code would be better, but examples or hints will do... ;)
    Thank you very much in advance!!!

    Hello!
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class MultipleButtonsInCellTest {
      public JComponent makeUI() {
        String[] columnNames = {"String", "Button"};
        Object[][] data = {{"AAA", null}, {"BBB", null}};
        DefaultTableModel model = new DefaultTableModel(data, columnNames) {
          @Override public Class<?> getColumnClass(int column) {
            return getValueAt(0, column).getClass();
        JTable table = new JTable(model);
        table.setRowHeight(36);
        ActionPanelEditorRenderer er = new ActionPanelEditorRenderer();
        TableColumn column = table.getColumnModel().getColumn(1);
        column.setCellRenderer(er);
        column.setCellEditor(er);
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(table));
        p.setPreferredSize(new Dimension(320, 200));
        return p;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          @Override public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new MultipleButtonsInCellTest().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    class ActionPanelEditorRenderer extends AbstractCellEditor
                       implements TableCellRenderer, TableCellEditor {
      JPanel panel1 = new JPanel();
      JPanel panel2 = new JPanel();
      public ActionPanelEditorRenderer() {
        super();
        JButton viewButton2 = new JButton(new AbstractAction("view2") {;
          public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "Viewing");
        JButton editButton2 = new JButton(new AbstractAction("edit2") {;
          public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "Editing");
        panel1.setOpaque(true);
        panel1.add(new JButton("view1"));
        panel1.add(new JButton("edit1"));
        panel2.setOpaque(true);
        panel2.add(viewButton2);
        panel2.add(editButton2);
      @Override
      public Component getTableCellRendererComponent(JTable table, Object value,
                   boolean isSelected, boolean hasFocus, int row, int column) {
        panel1.setBackground(isSelected?table.getSelectionBackground()
                                       :table.getBackground());
        return panel1;
      @Override
      public Component getTableCellEditorComponent(JTable table, Object value,
                                    boolean isSelected, int row, int column) {
        panel2.setBackground(table.getSelectionBackground());
        return panel2;
      @Override
      public Object getCellEditorValue() {
        return null;
    }

  • Changing images on JButtons

    hi all,
    I have a collection of icons that having images available in multiple sizes. The program my company is working on is geared towards deaf/hard of hearing and sight impaired individuals.
    I have assigned all the buttons images - however I want to be able to change the image on the button at a user's whim.
    I have all the buttons in a collection and wanted to just iterate through them, retrieve the path of the image associated with them, modify it so that it reflects the right path for the right sized images, and then set it back to the button.
    I can't figure out or find where that property is.
    Can anyone help?

    I have to agree with camickr, storing buttons in a collection isn't really Swingish.
    Generally you assign actions to buttons, and for reusability's sake, you assign icons to these actions. If you change a button's action, when the icon is defined in the action, the icon (and text) change as well.
    Try this (example that switches button actions when a button is clicked):
    Test.java
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    public class Test extends JFrame{
         private static final long serialVersionUID = 1L;
         private static AbstractAction [] actionList;
         public static void main( String args[]) throws Exception {
              JFrame f = new JFrame();
              f.setSize( 400, 400 );
              actionList = new AbstractAction[]{
                   new IconAndTextAction( "Foo", "/images/lock_function.png", 1 ),
                   new IconAndTextAction( "Bar", "/images/lock_payment.png", 0 )
              f.getContentPane().add( new JButton( actionList[0] ) );
              f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              f.setVisible( true );               
         private static class IconAndTextAction extends AbstractAction{
              private static final long serialVersionUID = 1L;
              private int nextinline;
              public IconAndTextAction( String text, String iconPath, int next ) {
                   putValue( Action.NAME, text );
                   putValue( Action.LARGE_ICON_KEY,
                        new ImageIcon(
                             Test.class.getResource( iconPath )
                   nextinline = next;
              @Override
              public void actionPerformed(ActionEvent e) {
                   ((JButton)e.getSource()).setAction( actionList[nextinline] );               
    }GL
    Alex

  • JLabel and JButton both disappear under Mac OS X

    Hello all,
    In my application I have two JButtons and a JLabel. When I compile and run the application the resulting window always shows the first button to begin with but doesn't show the second button until the window loses focus then gains it, or until I click where the second button was suppose to be. Regardless, the JLabel never appears. I've run this on both Windows and Linux now and everything appears as they should. Any thoughts?

    Sorry, I'm still new to these forums.
    import java.util.Locale;
    import java.util.ResourceBundle;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import java.io.*;
    import javax.swing.*;
    import com.apple.eawt.*;
    public class railsservermanager extends JFrame
         private Font font = new Font("calibri", Font.BOLD, 36);
         protected ResourceBundle resbundle;
         protected AboutBox aboutBox;
         protected PrefPane prefs;
         private Application fApplication = Application.getApplication();
         protected Action newAction, openAction, closeAction, saveAction, saveAsAction, undoAction, cutAction, copyAction, pasteAction, clearAction, selectAllAction;
         static final JMenuBar mainMenuBar = new JMenuBar();     
         protected JMenu fileMenu, editMenu;
         public railsservermanager()
              super("");
              resbundle = ResourceBundle.getBundle ("strings", Locale.getDefault());
              setTitle(resbundle.getString("frameConstructor"));
              Container primaryContainer = this.getContentPane();
              FlowLayout primaryLayout = new FlowLayout();
              primaryContainer.setLayout(primaryLayout);
              createActions();
              addMenus();
              //Collect User's Project Directory
              final String usersproject = JOptionPane.showInputDialog("Please enter your project directory");
              //Initialize My Objects
              final ScriptManager scriptM = new ScriptManager(usersproject);
              final RunCommand runC = new RunCommand();          
              Action startAction = new AbstractAction("Start Server")
                   public void actionPerformed(ActionEvent evt)
                        String startPath = scriptM.createStartScript();
                        int exitstatus = runC.command(startPath);
                        //scriptM.deleteFile(startPath);
                        String result;
                        if(exitstatus == 0)
                             result = "Server Started Successfully.";
                             JOptionPane.showMessageDialog(null, result, result, JOptionPane.INFORMATION_MESSAGE);
              Action stopAction = new AbstractAction("Stop Server")
                   public void actionPerformed(ActionEvent evt)
                        String stopPath = scriptM.createStopScript();
                        int exitstatus = runC.command(stopPath);
                        //scriptM.deleteFile(stopPath);
                        String result;
                        if(exitstatus == 0)
                             result = "Server Stopped Successfully.";
                             JOptionPane.showMessageDialog(null, result, result, JOptionPane.INFORMATION_MESSAGE);
              JButton startserver = new JButton(startAction);
              JButton stopserver = new JButton(stopAction);
              JLabel apptitle = new JLabel(resbundle.getString("frameConstructor"));
              primaryContainer.add(apptitle);
              primaryContainer.add(startserver);
              primaryContainer.add(stopserver);
              setSize(310, 150);
              setVisible(true);
         }I hope this helps a little more.

  • ActionListener/AbstractAction

    Hello everyone,
    Can someone tell me the best choice for action-event handling in swing?
    Extends AbstractAction or implements ActionListener
    Thanks for clarifying

    abstractAction implements actionListener so if you extend it then you are infact implementing actionListener...
    but AbstractAction has values like tooltip, text, icon, and others, and you can construct JButton or menus from AbsractAction,
    this is good when you lets say you have a JMenuItem that dose somthing and you want the same thing to be on a JToolBar then just add the same AbsractAction to bot the JMenuItem and JToolBar then you will not have multiple
    if(event.getSource()==button1)so i preffer the AbstractAction but i use it like this..
    //Menu -> Help -> About
          AbstractAction about=new AbstractAction(){
             public void actionPerformed(ActionEvent e){aboutAction();}
          Utils.setActionValues(about,"About",
                new ImageIcon("about.gif"),KeyEvent.VK_A,
                "Shows the about dialog",null,true);
    //the Utils method is like this
        * Sets the values of the input action
       public static void setActionValues (Action action, String name, Icon icon,
          int mnemonic, String description, KeyStroke accelerator,
          boolean enabled)
          action.putValue(Action.ACCELERATOR_KEY, accelerator);
          action.putValue (Action.MNEMONIC_KEY, new Integer (mnemonic));
          action.putValue (Action.NAME, name);
          action.putValue (Action.SHORT_DESCRIPTION, description);
          action.putValue (Action.SMALL_ICON , icon);
          action.setEnabled (enabled);
       }i would then use it like this
    JMenu menu=new JMenu();
    menu.add(about);
    JToolBar toolBar =new JToolBar();
    tooBar.add(about);hope this helps... you

  • Icon on JButton

    I'm having an odd problem. Seemingly, I've done mostly everything correctly, but something must be wrong somewhere.
    I'm trying to make JButtons with icon on them. I've made one, but the icon won't show. Here's my code:
              ImageIcon selectedIcon = new ImageIcon("selected.png", "Selected Menu");
              JButton characterScreenIcon = new JButton(selectedIcon);Now, that one actually works. But when I try to use setAction() on it, the icon disappears. This is the setAction line:
              characterScreenIcon.setAction(new ShowCharacterScreen());And here is the ShowCharacterScreen class:
         public class ShowCharacterScreen extends AbstractAction {
              public ShowCharacterScreen() {
                   super();
              public void actionPerformed(ActionEvent e) {
                   JButton icon = (JButton)(e.getSource());
                   icon.setIcon(selectedIcon);
                   JOptionPane.showMessageDialog(frame, "Button 1 pressed");
         }Now, it is worth noting that the action does work perfectly fine. I get the Dialog box. It's just the icon disappears when I use setAction() on it.
    I would like to know why this happens, so I can figure out how to fix it.

    hii,
    are you meaning this one ??? --->
    import java.awt.*;
    import java.awt.event.*;
    import java.io.BufferedInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import javax.swing.*;
    class TerraGUI {
        //GUI Fields
        static JFrame frame = new JFrame("TWOReborn");
        JPanel mainPane;
        JPanel characterPane;
        ImageIcon nonSelectedIcon;
        ImageIcon selectedIcon;
        public Container createContentPane() {
            mainPane = new JPanel();
            characterPane = new JPanel();
            characterPane.setPreferredSize(new Dimension(218, 442));
            characterPane.setBorder(BorderFactory.createLineBorder(Color.black));
            Image ViewMmImage = ImageViewMmLoader.getImage(TerraGUI.class, "resources/passed.png");
            Image ViewMmImage1 = ImageViewMmLoader.getImage(TerraGUI.class, "resources/failed.png");
            selectedIcon = new ImageIcon(ViewMmImage);
            nonSelectedIcon = new ImageIcon(ViewMmImage1);
            JPanel controlsAndStatus = new JPanel();
            JButton characterScreenIcon = new JButton();
            characterScreenIcon.setIcon(selectedIcon);
            characterScreenIcon.setMargin(new Insets(0, 0, 0, 0));
            characterScreenIcon.setAction(new ShowCharacterScreen());
            controlsAndStatus.add(characterScreenIcon);
            characterPane.add(controlsAndStatus);
            mainPane.add(characterPane);
            return mainPane;
        private static void createAndShowGUI() {
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setResizable(false);
            TerraGUI terra = new TerraGUI();
            frame.getContentPane().add(terra.createContentPane());
            frame.pack();
            frame.setVisible(true);
        public class ShowCharacterScreen extends AbstractAction {
            private static final long serialVersionUID = 1L;
            public ShowCharacterScreen() {
                super("", selectedIcon);
            public void actionPerformed(ActionEvent e) {
                JButton icon = (JButton) (e.getSource());
                icon.setIcon(null);
                icon.setIcon(nonSelectedIcon);
                JOptionPane.showMessageDialog(frame, "Button 1 pressed");
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    final class ImageViewMmLoader {
        private ImageViewMmLoader() {
        public static Image getImage(Class<?> relativeClass, String filename) {
            Image returnValue = null;
            InputStream is = relativeClass.getResourceAsStream(filename);
            if (is != null) {
                BufferedInputStream bis = new BufferedInputStream(is);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    int ch;
                    while ((ch = bis.read()) != -1) {
                        baos.write(ch);
                    returnValue = Toolkit.getDefaultToolkit().createImage(baos.toByteArray());
                } catch (IOException exception) {
                    System.err.println("Error loading: " + filename);
            return returnValue;
    }... kopik

  • Adding Dynamic JButtons & JLabels on the JTool

    On occerance of certain ActionEvent i need to add dynamic JButtons & JLabels on the JToolBar. Initially JToolBar will be empty.
    Code below is not working properly...
    It is creating buttons dynamiclly but i cant set any property for that one.
    class DeviceAction extends AbstractAction
         public DeviceAction()
         // Add this action to the toolbar resulting
         // in a new button getting added to the
         // toolbar
         JButton jbutton = xmlFilesToolBar.add( this);
         xmlFilesToolBar.addSeparator();
         jbutton.setActionCommand( "Dynamic" );
    I will call " new DeviceAction(); " when ever ActionEvent occurs.
    I need to have controle over the dynamically added JButtons & JLables, bcoz each JButtons shld do some Actions when it is clicked.
    Plz do the needful.
    Reg,
    Bha.

    Multi-post: http://forum.java.sun.com/thread.jspa?threadID=725394&tstart=0

  • Squished JButtons

    I'm trying to make a JFrame that will cycle through several Images (VCR-like).
    I've tried various methods, all with the same basic results. The image comes up fine, but the 4 buttons (first, previous, next, last) are all squished at the bottom (should be 36x36 icons - gifs really - but are displaying as about 25x10) and are unreadable. They are coming up in the correct order and work properly, it's just impossible for the operator to know what they do without the icon.
    I've tried making a BorderLayout JPanel on the content pane, put the image in the CENTER and the 4 buttons in the SOUTH.
    I've tried making a BoxLayout JPanel (Y-Axis) on the content pane with the image added first and the button panel (built on a BoxLayout (X-Axis)) second.
    I've tried forcing the size of the buttons by setting the minimum size to the size of the GIF files.
    I've run out of ideas.
    Below is what I currently have, which builds the main panel with a BoxLayout in the Y-Axis then adds the image as a JLabel, builds another JPanel for the buttons (which is a BoxLayout in the X-Axis) which is added to the main panel.
    public class ImageReview
                 extends JFrame
       private int index = 0;
       private int numImages = 0;
       private ImageIcon[] images = null;
       private JLabel imageLabel = null;
       private JPanel mainPanel = null;
       private String FIRST_BUTTON = "firstArrowIcon.gif";
       private String PREV_BUTTON = "previousArrowIcon.gif";
       private String NEXT_BUTTON = "nextArrowIcon.gif";
       private String LAST_BUTTON = "lastArrowIcon.gif";
       public ImageReview (ImageIcon[] images)
          super ("Image Review");
          setSize (640, 550);
          Container contentPane = getContentPane();
          mainPanel = new JPanel ();
          mainPanel.setLayout (new BoxLayout (mainPanel, BoxLayout.Y_AXIS));
          numImages = images.length;
          this.images = new ImageIcon[numImages];
          for (int i=0 ; i<numImages ; i++)
             this.images[i] = images;
    JPanel imagePanel = new JPanel ();
    imageLabel = new JLabel (this.images[0]);
    imagePanel.add (imageLabel);
    mainPanel.add (imagePanel, BorderLayout.CENTER);
    mainPanel.add (Box.createVerticalStrut (10));
    index=0;
    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout (new BoxLayout (buttonPanel, BoxLayout.X_AXIS));
    buttonPanel.add (createButton (FIRST_BUTTON));
    buttonPanel.add (createButton (PREV_BUTTON));
    buttonPanel.add (createButton (NEXT_BUTTON));
    buttonPanel.add (createButton (LAST_BUTTON));
    mainPanel.add (buttonPanel);
    mainPanel.add (Box.createVerticalStrut (20));
    contentPane.add (mainPanel);
    private JButton createButton (String buttonType)
    JButton button = new JButton ();
    ImageIcon imageIcon = new ImageIcon (buttonType);
    Image image = imageIcon.getImage();
    button.setIcon (imageIcon);
    Dimension preferredSize = new Dimension (imageIcon.getIconWidth (),
    imageIcon.getIconHeight());
    button.setMinimumSize (preferredSize);
    button.setAction (new imageReviewAction (buttonType));
    String tooltip = "Press to go to ";
    if (buttonType == FIRST_BUTTON)
    tooltip += "First";
    else if (buttonType == PREV_BUTTON)
    tooltip += "Previous";
    else if (buttonType == NEXT_BUTTON)
    tooltip += "Next";
    else if (buttonType == LAST_BUTTON)
    tooltip += "Last";
    tooltip += " Image in List";
    button.setToolTipText (tooltip);
    return button;
    class imageReviewAction
    extends AbstractAction
    private Button button = null;
    public imageReviewAction (Button button)
    this.button = button;
    public void actionPerformed (ActionEvent e)
    if (button == FIRST_BUTTON)
    index = 0;
    else if (button == PREV_BUTTON)
    if (index > 0)
    index--;
    else if (button == NEXT_BUTTON)
    if (index < numImages - 1)
    index++;
    else if (button == LAST_BUTTON)
    index = numImages - 1;
    else
    // No other buttons, can't do anything.
    imageLabel.setIcon (images[index]);

    Had to make a lot of changes to your app to get it squared away. It compiles and runs okay; you can have a look.
    I think the central problem of the button size is in this line:
    button.setAction (new imageReviewAction (buttonType));
    Setting the action removes the icon. One way around it is to change your AbstractAction class to an ActionListener.
    import java.awt.*;
    import java.awt.event.*;
    import java.net.URL;
    import javax.swing.*;
    public class ImageReviewRx extends JFrame
        private ImageIcon[] icons = null;
        private JLabel imageLabel = null;
        private JPanel mainPanel = null;
        ImageReviewAction action;
        public ImageReviewRx ()
            super ("Image Review");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setSize (640, 550);
            createIcons();
            action = new ImageReviewAction();
            mainPanel = new JPanel ();
            mainPanel.setLayout (new BorderLayout ());
            JPanel imagePanel = new JPanel ();
            imageLabel = new JLabel (icons[0]);
            imagePanel.add (imageLabel);
            mainPanel.add (imagePanel, BorderLayout.CENTER);
            JPanel buttonPanel = new JPanel();
            for(int j = 0; j < icons.length; j++)
                buttonPanel.add (createButton (j));
            mainPanel.add (buttonPanel, "South");
            Container contentPane = getContentPane();
            contentPane.add (mainPanel);
        private JButton createButton (int iconIndex)
            JButton button = new JButton ();
            int w = icons[iconIndex].getIconWidth();
            int h = icons[iconIndex].getIconHeight();
    //        button.setPreferredSize(new Dimension(w,h));  // an option
            button.setIcon (icons[iconIndex]);
            button.addActionListener (action);
            String ac = "";
            switch(iconIndex)
                case 0:
                    ac = "First";
                    break;
                case 1:
                    ac = "Previous";
                    break;
                case 2:
                    ac = "Next";
                    break;
                case 3:
                    ac = "Last";
            String tooltip = "Press to go to " + ac + " Image in List";
            button.setToolTipText (tooltip);
            button.setActionCommand(ac);
            return button;
        private void createIcons()
            String[] fileNames = {
                "firstArrowIcon.gif", "previousArrowIcon.gif",
                "nextArrowIcon.gif",  "lastArrowIcon.gif"
            icons = new ImageIcon[fileNames.length];
            for(int j = 0; j < icons.length; j++)
                URL url = getClass().getResource(fileNames[j]);
                icons[j] = new ImageIcon(url);
        class ImageReviewAction implements ActionListener
            int index = 0;
            public void actionPerformed (ActionEvent e)
                JButton button = (JButton)e.getSource();
                String ac = button.getActionCommand();
                if (ac.equals("First"))
                    index = 0;
                if (ac.equals("Previous"))
                    index--;
                    if(index < 0)
                        index = icons.length - 1;
                if (ac.equals("Next"))
                    index++;
                    if(index > icons.length - 1)
                        index = 0;
                if (ac.equals("Last"))
                    index = icons.length - 1;
                imageLabel.setIcon(icons[index]);
        public static void main(String[] args)
            ImageReviewRx rx = new ImageReviewRx();
            rx.setVisible(true);
    }

  • Disabling an inherited JButton

    Dear all,
    I have 2 child classes (ChildPanel1 & ChildPanel2) that extend ParentPanel. ParentPanel has a JButton component coupled with an accessor method toggleButton() to enable/disable the button.
    I currently enable/disable the button by calling toggleButton() twice, once on the ChildPanel1 instance and then again on the ChildPanel2 instance. I'd like to be able to organise things so that I could enable/disable the button on all the instances of all the classes that extend ParentPanel with one call.
    How can I do this?
    Cheers!
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ButtonTest {
        public class ParentPanel extends JPanel {
            protected JPanel buttonPanel;
            protected boolean enabled;
            protected JButton button1;
            public void toggleButton() {
                button1.setEnabled(enabled);
                if (enabled)
                    enabled = false;
                else
                    enabled = true;
            public ParentPanel(String title) {
                super(new BorderLayout());
                enabled = false;
                button1 = new JButton("Button 1");
                buttonPanel = new JPanel();
                buttonPanel.add(button1);
                setLayout(new BorderLayout());
                add(buttonPanel, BorderLayout.SOUTH);
        public class ChildPanel1 extends ParentPanel {
            public ChildPanel1() {
                super("Panel 1");
                JTextArea ta = new JTextArea();
                JScrollPane scroll = new JScrollPane();
                scroll.getViewport().add(ta);
                add(scroll, BorderLayout.CENTER);
        public class ChildPanel2 extends ParentPanel {
            protected JList myList;
            public ChildPanel2() {
                super("Panel 2");
                myList = new JList(new String[] { "item 1", "item 2" });
                JScrollPane ps = new JScrollPane();
                ps.getViewport().add(myList);
                JButton button2 = new JButton("Button 2");
                buttonPanel.add(button2);
                add(ps, BorderLayout.CENTER);
        public static void main(String argv[]) {
            JFrame frame = new JFrame("Button Test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(370, 330);
            JPanel mainPanel = new JPanel(new BorderLayout());
            ButtonTest myTest = new ButtonTest();
            final ChildPanel1 panel1 = myTest.new ChildPanel1();
            final ChildPanel2 panel2 = myTest.new ChildPanel2();
            JTabbedPane jtp = new JTabbedPane();
            jtp.addTab("Tab 1", panel1);
            jtp.addTab("Tab 2", panel2);
            JButton disableButton = new JButton(new AbstractAction(
                    "Toggle button 1") {
                public void actionPerformed(ActionEvent e) {
                    panel1.toggleButton();
                    panel2.toggleButton();
            mainPanel.add(disableButton, BorderLayout.SOUTH);
            mainPanel.add(jtp, BorderLayout.CENTER);
            frame.setContentPane(mainPanel);
            frame.pack();
            frame.show();
    }

    I've added another button to your test class that calls LoadSurfacesAction.getLoadSurfaceAction().setEnabled(false) when it's pressed. Once this method is invoked, LoadSurfacesAction.getLoadSurfaceAction().isEnabled does return false, however the button remains enabled.
    Am I missing something?
    Cheers!import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TestClass {
        public static class LoadSurfacesAction extends AbstractAction {
            private static LoadSurfacesAction theInstance;
            private static final Action DEFAULT_ACTION = new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Default load surfaces action called");
            private static Action theDelegate = DEFAULT_ACTION;
            public static Action getLoadSurfaceAction() {
                if (theInstance == null) {
                    theInstance = new LoadSurfacesAction();
                return theInstance;
            public static void setAction(Action anAction) {
                theDelegate = anAction;
            public void actionPerformed(ActionEvent e) {
                theDelegate.actionPerformed(e);
        public class LoadVolPanel extends JPanel {
            protected JPanel buttonPanel;
            public LoadVolPanel(String title) {
                super(new BorderLayout());
                setBorder(new CompoundBorder(new TitledBorder(new EtchedBorder(),
                        title), new EmptyBorder(3, 5, 3, 5)));
                JButton loadButton = new JButton("Load surfaces");
                loadButton.setMnemonic('L');
                loadButton.addActionListener(LoadSurfacesAction
                        .getLoadSurfaceAction());
                buttonPanel = new JPanel();
                buttonPanel.add(loadButton);
                setLayout(new BorderLayout());
                add(buttonPanel, BorderLayout.SOUTH);
        public class LogPanel extends LoadVolPanel {
            public LogPanel() {
                super("Log");
                JTextArea ta = new JTextArea();
                ta.setLineWrap(true);
                ta.setWrapStyleWord(true);
                ta.setEditable(false);
                ta.append("The Load Surfaces button below kicks off\n");
                ta.append("a shell script on a unix box\n");
                ta.append("Output from the script appears here.\n");
                JScrollPane scroll = new JScrollPane();
                scroll.getViewport().add(ta);
                add(scroll, BorderLayout.CENTER);
        public class LoadPanel extends LoadVolPanel {
            protected JList securitiesList;
            public final int VISIBLE_ROWS = 12;
            public LoadPanel() {
                super("Codes");
                securitiesList = new JList(new String[] { "item 1", "item2" });
                securitiesList
                        .setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                securitiesList.setLayoutOrientation(JList.VERTICAL_WRAP);
                securitiesList.setVisibleRowCount(VISIBLE_ROWS);
                JScrollPane ps = new JScrollPane();
                ps.getViewport().add(securitiesList);
                JButton refreshButton = new JButton("Refresh Securities List");
                buttonPanel.add(refreshButton);
                add(ps, BorderLayout.CENTER);
        public static void main(String argv[]) {
            JFrame frame = new JFrame("Load Volatility");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(370, 330);
            JPanel mainPanel = new JPanel();
            JPanel buttonPanel = new JPanel();
            mainPanel.setLayout(new BorderLayout());
            TestClass myTest = new TestClass();
            JPanel logPanel = myTest.new LogPanel();
            LoadPanel loadPanel = myTest.new LoadPanel();
            JTabbedPane jtp = new JTabbedPane();
            jtp.addTab("Load Volatility", loadPanel);
            jtp.addTab("Log", logPanel);
            mainPanel.add(jtp, BorderLayout.CENTER);
            LoadSurfacesAction.getLoadSurfaceAction().setEnabled(false);
            JButton changeActionButton = new JButton(new AbstractAction(
                    "change action") {
                public void actionPerformed(ActionEvent e) {
                    LoadSurfacesAction.setAction(new AbstractAction() {
                        public void actionPerformed(ActionEvent e) {
                            System.out
                                    .println("Modified load surfaces action called");
            JButton disableButton = new JButton(new AbstractAction(
                    "disable load button") {
                public void actionPerformed(ActionEvent e) {
                    LoadSurfacesAction.getLoadSurfaceAction().setEnabled(false);
                    System.out
                            .println("LoadSurfacesAction.getLoadSurfaceAction().isEnabled returned: "
                                    + LoadSurfacesAction.getLoadSurfaceAction()
                                            .isEnabled());
            buttonPanel.add(changeActionButton);
            buttonPanel.add(disableButton);
            mainPanel.add(buttonPanel, BorderLayout.SOUTH);
            frame.setContentPane(mainPanel);
            frame.pack();
            frame.show();
    }

  • Making JButton not respond when hour glass cursor

    Hi,
    I know how to change the cursor to the hour glass one but what I want is that JButtons will not responds to clicks from an hour glass cursor. The JButtons should only respond to clicks from the normal cursor.
    Does anyone know how to do this?
    Thanks,
    Jim

    Below is a solution for JDK 1.4 without threading.
    In the event handler of ActionLock the following happens:
    1. disable the button.
    2. repaint the button using paintImmediately().
    3. perform the search.
    4. post an "enable button" event on the event dispatching queue using invokeLater().
    5. handle possible clicks during the search. They are ignored since the button is disabled.
    6. the "enable button" event is handled on the event dispatching thread.
    Three comments:
    i) if step 2 is not done the paint event triggered by disabling the button will not be handled until just before step 6. Visually the button will thus not appear disable.
    ii) if step 4 is not done through invokeLater step 6 is done before step 5, thus the clicks will start new searches.
    iii) focus issues are solved by making the button not focusable.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ButtonTest
      public static void main(String[] args)
        JFrame frame = new JFrame("Button test");
        frame.getContentPane().add(new MButton(new SearchAction()));
        frame.pack();
        frame.show();
    class SearchAction extends AbstractAction
      public SearchAction()
        super("Search");
      public void actionPerformed(ActionEvent e)
        try
          Thread.currentThread().sleep(3000);  // Simulate time-consuming search
        catch (InterruptedException ex)
    class ActionLock implements ActionListener
      private ActionListener m_OriginalListener;
      private JButton m_button;
      public ActionLock(ActionListener listener, JButton button)
        m_OriginalListener = listener;
        m_button = button;
      public void actionPerformed(final ActionEvent e)
        m_button.setEnabled(false);
        m_button.paintImmediately(
            0, 0, m_button.getWidth(), m_button.getHeight());
        m_OriginalListener.actionPerformed(e);
        SwingUtilities.invokeLater(new Runnable()
          public void run()
            m_button.setEnabled(true);
    class MButton extends JButton
      public MButton(Action action)
        super(action);
        setFocusable(false);
      public void addActionListener(ActionListener listener)
        super.addActionListener(new ActionLock(listener, this));

  • Using 1.3 Action Framework, JButton firing strangely...

    I have a bunch of AbstractActions in an array, like so:
         AbstractAction posHousingActions[] = new AbstractAction[] {
             new AbstractAction("", UP_ARROW_ICON) {
                  public void actionPerformed(ActionEvent evt) {
                   System.out.println("Building House");
                   buildHousing(HOUSE);
             new AbstractAction("", UP_ARROW_ICON) {
                  public void actionPerformed(ActionEvent evt) {
                   System.out.println("Building Large House");
                   buildHousing(LARGE_HOUSE);
              },...Then (in the same method), a for loop that uses this array to generate custom arrow buttons:
    for(int i = 0; i < NUM_OF_HOUSING_TYPES; i++) {
             JButton newTopArrow = new JButton();
             newTopArrow.setMargin(buttonI);
             topButtons.add(newTopArrow);
             newTopArrow.setAction(posHousingActions);
    *topButtons is a JToolBar.
    When I click on one of these buttons, it flickers extremely briefly, then does nothing. The System.out in my ActionPerformed does not go off, and the button does not stay 'pressed' if I hold the mouse button down.
    I was sure I wasn't spelling 'actionPerformed' right, or something like that, but after going over and over it, I'm stumped. Any help is greatly appreciated. Thank you,
    Bret

    To anyone who may also have this problem, I've solved it; I had another component that was constantly requesting the focus. Apparently, the button was retaining the focus just long enough to blink in response to the click, but not long enough to fire the event, or stay 'clicked'.

Maybe you are looking for

  • Help! How to create Jar file for a packaged class?

    Hi! I am new in jar complexities. I made a swing frame that just prompts a JOptionPane when executed. I accomplished the same using jar without packaging my class SwingTest. But when i package it, it doesn't run. Can any one tell me how to make jar f

  • Error launching Word with Robohelp for Word

    I have a test rack at work with a machine dedicated to Robohelp, which we just purchased and set up to replace our very old and outdated solution. It has Robohelp 8 on Windows 7, with Office 2007. Since the Robohelp installation, Word has consistent

  • How do i get a gray screen on my nano

    i know im new but, yesterday i was going to turn on my nano and a gray screen appered with all this wierd junk. well at first i thought that i had made it reset because i havent done that before and i thought it was normal and at the bottom of the sc

  • Get the data type

    Hi All,           I have one requirement like i have statement : "data: text type c  length 1" i need to get only data type "C" into one variable.I used split it will not work for my requirement .Can anybody please suggest  any other abap syntax to g

  • How can i upload a HTML5 contains in an advanced button ?

    how can help me to put a HTML5 in an advenced button .