Assigning an ActionListener to an inherited JButton

Dear all,
I have a base JPanel class with a button, a border and not much else. This class is extended by 2 other classes in my application.
I needed a means of associating an action with the button in my application's main class, so I added a static method addButtonListener to the base class, assuming that once I invoked this, the button would be 'activated' in all the panels inheriting from my base class. addButtonListener() simply invokes the button's addActionListener() method.
Unfortunately this doesn't work, the ActionListener only gets linked to the button in one of the child classes (the first one that's instantiated).
What's going on? The code for the base class is below...
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
public class LoadVolPanel extends JPanel {
     protected JPanel buttonPanel;
     protected static JButton loadButton;
     public static void addButtonListener(ActionListener a) {
          loadButton.addActionListener(a);
     public LoadVolPanel(String title) {
          super();
          setBorder(new CompoundBorder(
                    new TitledBorder(new EtchedBorder(), title), new EmptyBorder(3,
                              5, 3, 5)));
          loadButton = new JButton("Load surfaces");
          loadButton.setMnemonic('L');
          buttonPanel = new JPanel();
          buttonPanel.add(loadButton);
          setLayout(new BorderLayout());
          add(buttonPanel, BorderLayout.SOUTH);
}

I apologise for the amount of the code I've posted but it does compile, and will hopefully show you what I'm trying to do.
I would like:
- the Load button to appear at the bottom of each tab in the parent JTabbedPane;
- the Load button perform the same action in all panes;
- to be able to assign an action to the Load button from the main class.
Cheers!
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
public class TestClass {
     public class LoadVolPanel extends JPanel {
          protected JPanel buttonPanel;
          protected JButton loadButton;
          public void AddButtonListener(ActionListener a) {
               loadButton.addActionListener(a);
          public LoadVolPanel(String title) {
               super();
               setBorder(new CompoundBorder(new TitledBorder(new EtchedBorder(),
                         title), new EmptyBorder(3, 5, 3, 5)));
               loadButton = new JButton("Load surfaces");
               loadButton.setMnemonic('L');
               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;
          private JTabbedPane tabbedPane;
          private CheckListCell[] volCodes = { new CheckListCell("AMP"),
                    new CheckListCell("ALN"), new CheckListCell("ANN"),
                    new CheckListCell("ANZ"), new CheckListCell("ASX"),
                    new CheckListCell("AXA"), new CheckListCell("BNB"),
                    new CheckListCell("BIL"), new CheckListCell("BSL"),
                    new CheckListCell("CBA"), new CheckListCell("CML"),
                    new CheckListCell("CSR"), new CheckListCell("DJS"),
                    new CheckListCell("FOA"), new CheckListCell("FXJ"),
                    new CheckListCell("GNS"), new CheckListCell("GPT"),
                    new CheckListCell("IAG"), new CheckListCell("JHX"),
                    new CheckListCell("LEI"), new CheckListCell("MAP"),
                    new CheckListCell("MBL"), new CheckListCell("MIG"),
                    new CheckListCell("NAB"), new CheckListCell("NWS"),
                    new CheckListCell("NWSLV"), new CheckListCell("ORG"),
                    new CheckListCell("OST"), new CheckListCell("PBG"),
                    new CheckListCell("PBL"), new CheckListCell("PMN"),
                    new CheckListCell("QAN"), new CheckListCell("RIN"),
                    new CheckListCell("RIO"), new CheckListCell("SEV"),
                    new CheckListCell("SGB"), new CheckListCell("SHL"),
                    new CheckListCell("SSX"), new CheckListCell("STO"),
                    new CheckListCell("TAH"), new CheckListCell("TCL"),
                    new CheckListCell("TLS"), new CheckListCell("VBA"),
                    new CheckListCell("WBC"), new CheckListCell("WDC"),
                    new CheckListCell("WMR"), new CheckListCell("WOW"),
                    new CheckListCell("WPL"), new CheckListCell("WSF"),
                    new CheckListCell("ZFX"), new CheckListCell("CCL"), };
          public LoadPanel() {
               super("Codes");
               securitiesList = new JList(volCodes);
               CheckListCellRenderer renderer = new CheckListCellRenderer();
               securitiesList.setCellRenderer(renderer);
               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 final class CheckListCell {
          private String name;
          private boolean selected;
          public CheckListCell(String name) {
               this.name = name;
               selected = false;
          public String getName() {
               return this.name;
          public void setSelected(boolean selected) {
               this.selected = selected;
          public void invertSelected() {
               selected = !selected;
          public boolean isSelected() {
               return selected;
          public String toString() {
               return name;
     public final class CheckListener implements MouseListener, KeyListener {
          private LoadPanel parent;
          private JList securitiesList;
          public CheckListener(LoadPanel parentPanel) {
               parent = parentPanel;
               securitiesList = parentPanel.securitiesList;
          public void mouseClicked(MouseEvent e) {
               int index = securitiesList.locationToIndex(e.getPoint());
               if (index == securitiesList.getSelectedIndex())
                    doCheck();
          public void mousePressed(MouseEvent e) {
          public void mouseReleased(MouseEvent e) {
          public void mouseEntered(MouseEvent e) {
          public void mouseExited(MouseEvent e) {
          public void keyPressed(KeyEvent e) {
               if (e.getKeyChar() == ' ')
                    doCheck();
          public void keyTyped(KeyEvent e) {
          public void keyReleased(KeyEvent e) {
          private void doCheck() {
               int index = securitiesList.getSelectedIndex();
               if (index >= 0) {
                    CheckListCell cell = (CheckListCell) securitiesList.getModel()
                              .getElementAt(index);
                    cell.invertSelected();
                    securitiesList.repaint();
     public class CheckListCellRenderer extends JCheckBox implements
               ListCellRenderer {
          private Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);
          public CheckListCellRenderer() {
               setOpaque(true);
               setBorder(noFocusBorder);
          public Component getListCellRendererComponent(JList list, Object value,
                    int index, boolean isSelected, boolean cellHasFocus) {
               if (value != null)
                    setText(value.toString());
               setBackground(isSelected ? list.getSelectionBackground() : list
                         .getBackground());
               setForeground(isSelected ? list.getSelectionForeground() : list
                         .getForeground());
               CheckListCell data = (CheckListCell) value;
               setSelected(data.isSelected());
               setFont(list.getFont());
               setBorder((cellHasFocus) ? UIManager
                         .getBorder("List.focusCellHighlightBorder") : noFocusBorder);
               return this;
     public static void main(String argv[]) {
          JFrame frame = new JFrame("Load Volatility");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(370, 330);
          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);
          frame.getContentPane().add(jtp);
          frame.pack();
          frame.show();
}

Similar Messages

  • Can't assign an ActionListener to an external control.

    I'm having trouble assigning an ActionListene toa control.
    I have two classes, a GUI class and then a back-end class which contains in it an instance of the GUI class. What I then do is create an accessor to the controls on the GUI class so at the back-end I can assign an ActionListener via the accessor like this:
    cardSwipeTerminalUI.getSwipeButton().addActionListener(this);
    The problem is I keep getting the following error message:
    "CardSwipeTerminal.java": addActionListener(java.awt.event.ActionListener) in javax.swing.AbstractButton cannot be applied to (prototype.CardSwipeTerminal) at line 38, column 46
    I believe the MVC design pattern is fairly similar but this is a kind of cut-down idea.

    Yes... yes it is... good. I was just testing you all. I'm going to go and cry into my pillow now and not spotting such a blatantly obvious mistake akin to not pressing the power button on the computer =o)
    Thanks though, I'd have never spotted it.

  • 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();
    }

  • OM Account Assignment - Inheritance Principle

    Hi
    We are all ware that the Switch PPOM INHS when off, turns off the account assignemnt inhertitance from Org Unit to Position.
    But... How can we turn off the Org Unit to Org Unit account assignment inheritance in ECC 6.0
    To put it in simpler terms, I do not want the subordinate org unit to inherit the account assignment feature of the superior org unit. And can this be seen and/or done through PPOME?
    Thanks in advance for your inputs
    Shyam

    Hi Shyam,
    I have worked on the Issue that you have quoted. Please find below my observations:
    Org Unit - Org Unit Relationship in PPOME:
    CA01----
    CA02
        |----CA11
        |----US01                                     
    Structure: Two Org Units (CA01 and CA02 at the same level has got the Same Account Assignment Feature say
        Co. Code: CAA1
        PA:          CA00
        PSA:        CACA
    Fundamentally, Rule of Inheritance states Unless and until you EXPLICITLY change the values in the Subordinate Object, it will inherit the values from the Root Object or Parent object.
    Therefore, CA11 and US01 Should inherit the Values maintained in CA01. However, since you have explicitly changed the Values for US01 to
        Co Code: US00
        PA:         US01
        PSA:       USUS,
    the inheritance will NOT take place. For CA11, the inheritance follows.
    Your Switch for PPOM INHS is set to active.
    Coming to your Scenario 1:
    When I move CA11 as a Subordinate unit of US01 the account assignment features of US01 are inherited by CA11 (This should not happen);
    It will happen because, in the first place, you have Just caused an Inheritance to happen from CA01 to CA11 which is default and therefore not Explicit. Therefore, when you further move this org Unit CA11 to US01; it will follow the same process and inherit the values of US01.
    Scenario 2:
    Whereas when I move CA02 as a subordinate unit of US01 the account assignment feaures of US01 are NOT inherited by CA02 (This is correct).
    This is because you created the Org Unit with Account Assignment Features and Saved it (making it as explicit unit) and even if you move this unit under US01 or any other Org Unit it will NOT inherit values of the then PARENT unit. Moreover, if you relate any further org unit/position to CA02 (after you have related CA02 to US01); all the subordinate units/position will inherit the account assignment feature of CA02; which is quite valid.
    To my knowledge, to solve this, you will have to mandatorily click the Replace buttons available and set it to the requisites.
    Considering that you are using PPOME, it would be a case of few of the org units.. and therefore it wouldnt be a difficult task to do.
    Hope this helps.
    Best Regards,
    Kumarpal Jain.

  • Class inhertis from JButton, but button is not visible

    Hi!
    I'm having a class that inherits JButton. The idea was to give the button additional parameters, so it inherits from JButton to have all the attributes from JButton... But the problem is, that the Buttons are only visible when I touch them with the mouse. When I move the window they are invisible again...
    Does anybody know why? Thanks for your help!
    P.S Sorry for my bad english....

    Okay, thanks for that hint!
    Here is the class for the gui:
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    public class Temp extends JFrame{
         private static final long serialVersionUID = 5945597724189252185L;
         private JMenuItem closeItem = null;
         private JMenuItem newItem = null;
         private JPanel mainPanel = null;
         private JLabel startImage = null;
         private MineFieldButton[][] mines = null;
         public Temp(){
              this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              addMenu();
              this.add(getMainPanel());
              this.pack();
         private JPanel getMainPanel(){
              if (mainPanel == null){
                   mainPanel = new JPanel();
                   if (mines == null)
                        mainPanel.add(getStartImage());
                   else{
                        mainPanel.setLayout(new GridBagLayout());
                        GridBagConstraints c = new GridBagConstraints();
                        c.fill = GridBagConstraints.HORIZONTAL;
                        c.ipady = 20;
                        c.ipadx = 20;
                        for (int x=0;x<mines.length;x++){
                             for (int y=0;y<mines[x].length;y++){
                                  c.gridx = x;
                                  c.gridy = y;
                                  mainPanel.add(mines[x][y],c);
              return mainPanel;
         private JLabel getStartImage(){
              if(startImage == null){
                   startImage = new JLabel();
              return startImage;
         private void addMenu(){
              JMenuBar menuBar = new JMenuBar();
              JMenu menu = new JMenu("File");
              menu.add(getNewItem());
              menu.add(getCloseItem());
              menuBar.add(menu);
              this.setJMenuBar(menuBar);
         private JMenuItem getNewItem(){
              if (newItem == null){
                   newItem = new JMenuItem("New");
                   newItem.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent e) {
                             createMines();
              return newItem;
         private JMenuItem getCloseItem(){
              if (closeItem == null){
                   closeItem = new JMenuItem("Close");
                   closeItem.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent e) {
                             System.exit(0);
              return closeItem;
         public void showGUI(){
              this.setVisible(true);
         private void createMines(){
              initMinesGUI();
              this.remove(getMainPanel());
              mainPanel = null;
              this.add(getMainPanel());
              this.pack();
         private void initMinesGUI(){
              mines  = new MineFieldButton[10][10];
              for (int x=0;x<mines.length;x++){
                   for (int y=0;y<mines[x].length;y++){
                        mines[x][y] = new MineFieldButton();
                        mines[x][y].setBorder(BorderFactory.createRaisedBevelBorder());
                        mines[x][y].setX(x);
                        mines[x][y].setY(y);
                        mines[x][y].setNumber(x*y);
    }And here for the class that inherits JButton "MineFieldButton":
    import javax.swing.JButton;
    public class MineFieldButton extends JButton{
         private static final long serialVersionUID = -1020769129018597011L;
         private int number = 0;
         private int x;
         private int y;
         public int getNumber() {
              return number;
         public void setNumber(int number) {
              this.number = number;
         public int getX() {
              return x;
         public void setX(int x) {
              this.x = x;
         public int getY() {
              return y;
         public void setY(int y) {
              this.y = y;
    }I hope that you can find my error.... And that this is a SSCCE :-)
    Thanks!

  • JButton in a GridLayout

    Hi,
    I am trying to arrange 16 Buttons in a 4 by 4 grid. When you click on a button the text on the button should be concantenated to a public string. When you click on another button called okay, the string formed so far should be displayed in a JList.
    This is the code i have written so far. I can't get the text from the buttons to display.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    public class GridWin extends JFrame implements ActionListener {
    boolean inAnApplet = true;
    JButton button;
    public String word;
    public String randomword()
    char[] myCharacters = {'a','b','c','d','e','f', 'g','h','i','j',
    'k','l','m','n','o','p','q','r','s',
    't','u','v','w','x','y','z'};
    int lengthArray = 26;
    int index ;
    char theCharacter;
    String newword;
    newword = "";
    for (int i = 0; i < 16; i++)
    index = (int)(Math.random() * lengthArray );
    theCharacter = myCharacters[ index];
    newword = newword + theCharacter;
    return newword;
    public void generateGridWindow(String s) {
    char [] f = s.toCharArray();
    JFrame tJFrame = new JFrame("Grid");
    Container contentPane = tJFrame.getContentPane();
    contentPane.setLayout(new GridLayout(4,4));
    for(int d=0; d<16; d++)
    Character c = new Character(f[d]);
    String i = c.toString();
    contentPane.add(button = new JButton(i));
    button.addActionListener(this);
    tJFrame.pack();
    tJFrame.setVisible(true);
    public void actionPerformed(ActionEvent e) {
    Object source = e.getSource();
    String word = source.getLabel(); // This does work
    public GridWin() {
    String s = randomword();
    generateGridWindow(s);
    public GridWin(String s) {
    generateGridWindow(s);
    Please help it is urgent.

    The following at least compiles and runs. If this is a homework assignment, I think you can forget any marks on offer for following structured programming practices. Note the array of buttons. I've had to delete a couple of line of your code to get it to compile.Couldn't work out what they did. Delete the 2nd Frame that pops up to see the one with the buttons:
    Ask yourself what's wrong with this:
    JButton button;
    contentPane.add(button = new JButton(i));
    button.addActionListener(this);
    How many buttons do you have? There may be 16 displayed but how many can you actually reference in your program
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    public class GridWin extends JFrame implements ActionListener
        boolean inAnApplet = true;
        JButton button [ ] = new JButton[16];
        String word;
    public String randomword()
    char[] myCharacters = {'a','b','c','d','e','f', 'g','h','i','j',
    'k','l','m','n','o','p','q','r','s',
    't','u','v','w','x','y','z'};
    int lengthArray = 26;
    int index ;
    char theCharacter;
    String newword;
    newword = "";
    for (int i = 0; i < 16; i++)
        index = (int)(Math.random() * lengthArray );
        theCharacter = myCharacters[ index];
        newword = newword + theCharacter;
    return newword;
    public void generateGridWindow(String s) {
    char [] f = s.toCharArray();
    JFrame tJFrame = new JFrame("Grid");
    Container contentPane = tJFrame.getContentPane();
    contentPane.setLayout(new GridLayout(4,4));
    for(int d=0; d<16; d++)
    button[d] = new JButton("" + d);
    contentPane.add(button[d]);
    button[d].addActionListener(this);
    tJFrame.pack();
    tJFrame.setVisible(true);
    public void actionPerformed(ActionEvent e) {
    for (int counter = 0; counter < 16; ++ counter)
        if(e.getSource() == button[counter])
            System.out.println("Button " + counter + " Pressed");
    public  GridWin() {
    String s = randomword();
    generateGridWindow(s);
    public GridWin(String s) {
    generateGridWindow(s);
    public static void main (String [ ] args)
        GridWin gw = new GridWin("aa");
        gw.setVisible(true);
    }

  • How to get name from JButton?

    Hey
    Is it possible to get the name from a clicked JButton in the actionPerformed so that if i have for example 2 JButtons i can do an
    if statement to do different things when a button is clicked?
    For example if button1 is clicked the screen writes "YippiKayYeah mother ......" and if button2 is clicked it writes "Go home Lazy Boy".
    Here is my code, if it is for any use:
    public class Main extends JPanel implements ActionListener {
        private Players players;
        JTextArea output;
        JScrollPane scrollPane2;
        JButton button1, button2;
        String newline = "\n";
        public Main(){
            players = new Players();
        public JMenuBar createMenuBar(){
            JMenuBar menuBar = new JMenuBar();
            JMenu menu = new JMenu("File");
            menu.setMnemonic(KeyEvent.VK_A);
            menu.getAccessibleContext().setAccessibleDescription("The only menu in this program that has menu items");
            menuBar.add(menu);
            // add menuitems/buttons
            JMenuItem menuItemSave   = new JMenuItem("Save");
            menuItemSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
            menuItemSave.getAccessibleContext().setAccessibleDescription("This doesn't really do anything");
            // add actionlistener       
            JMenuItem menuItemOpen   = new JMenuItem("Open");
            JMenuItem menuItemQuit   = new JMenuItem("Quit");
            // add to menu
            menu.add(menuItemSave);
            menu.add(menuItemOpen);
            menu.add(menuItemQuit);
            return menuBar;
        public Container createContent(){
            JPanel contentPane = new JPanel(new GridLayout(3,1));
            ImageIcon icon = createImageIcon("middle.gif", "a pretty but meaningless splat");
            JTable scrollPane = new JTable(players.showPlayers()); 
            //Create the first label.
            button1 = new JButton("Silkeborg IF");
            button1.setToolTipText("Klik her for at se Silkeborg IF");
            button1.addActionListener(this);
            button1.setActionCommand("enable");
            //Create the second label.
            button2 = new JButton("FC Midtjylland");
            button2.setToolTipText("Klik her for at se FC Midtjylland");
            button2.addActionListener(this);
            button2.setActionCommand("disable");
            //Create a scrolled text area.
            output = new JTextArea(5, 30);
            output.setEditable(false);
            scrollPane2 = new JScrollPane(output);
            //Add stuff to contentPane.
            contentPane.add(button1);
            contentPane.add(button2);
            contentPane.add(scrollPane);
            contentPane.add(scrollPane2, BorderLayout.CENTER);
            return contentPane;
        public void actionPerformed(ActionEvent e){
            String s;
            if ("enable".equals(e.getActionCommand())){
                s = "Silkeborg IF"+e.getSource();
                output.append(s + newline);
                button1.setActionCommand("disable");
                button2.setActionCommand("enable");
            } else{
                s = "FC Midtjylland"+e.getSource();
                output.append(s + newline);
                button1.setActionCommand("enable");
                button2.setActionCommand("disable");
        protected static ImageIcon createImageIcon(String path,
                                                   String description) {
            java.net.URL imgURL = Main.class.getResource(path);
            if (imgURL != null) {
                return new ImageIcon(imgURL, description);
            } else {
                System.err.println("Couldn't find file: " + path);
                return null;
        public static void createGUI(){
            JFrame frame = new JFrame("Test af yo yo yo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Main menu = new Main();
            frame.setJMenuBar(menu.createMenuBar());
            frame.setContentPane(menu.createContent());
            frame.setSize(500, 300);
            frame.pack();
            frame.setVisible(true);
         * @param args the command line arguments
        public static void main(String[] args) {
            createGUI();
    }

    what i do with my JButtons is create and inner class that implements actionListener like this:
         private JButton button;
         button = new JButton("Button");
         button.addActionListener(new BListener());
         private class BListener implements ActionListener{
              public void actionPerformed(ActionEvent e){
                   if(e.getSource() == button){
                        //code for when the JButton button is pushed
         }Also, rather than comparing the names (Strings) and creating overhead, this compares the buttons reference variables :). Oh, and make sure that the buttons used are class variables. A good idea is to keep related buttons; listeners in one private class e.g. navigation buttons in a browser are all registered with the listener NavListener.

  • JButton inside the cell of JTable

    JButton buttonInCellOfTable = new JButton();
    buttonInCellOfTable.setBackground(Color.RED);
    buttonInCellOfTable.setText("MORE");
    buttonInCellOfTable.setPreferredSize(new Dimension(10, 22));
    buttonInCellOfTable.setMinimumSize(new Dimension(10, 22));
    buttonInCellOfTable.setMaximumSize(new Dimension(10, 22));
    myJTable.addRow("No. 1", buttonInCellOfTable);
    But Color and size isn't shown unlike those are set.
    What can I do?

    * @(#)ButtonTableCellRenderer.java     Tiger     2005 April 29
    package com.yahoo.ron.table;
    import java.awt.Component;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax,swing.JTable;
    import javax.swing.table.TableCellRenderer;
    * @author     Ronillo Ang - [email protected]
    final public class ButtonTableCellRenderer extends JButton implements TableCellRenderer{
         public ButtonTableCellEditor(ActionListener actionListener){
              super("Editor");
              if(actionListener == null)
                   throw new NullPointerException();
              addActionListener(actionListener);
         public Component getTableCellRenderComponent(JTable table, Object value, boolean selected, boolean hasFocus, int row, int col){
              if(value instanceof String){
                   String text = String.valueOf(value);
                   setText(text);
              else
                   setText("Unknown value");
              return this;
    * @(#)TestingButtonTableCellRenderer.java      Tiger     2005 April 29
    package com.yahoo.ron.test;
    import com.yahoo.ron.table.ButtonTableCellRenderer;
    import com.yahoo.ron.table.UneditableTableModel;
    import com.yahoo.ron.ThreadMonitor;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    * @author     Ronillo Ang - [email protected]
    * A class to test com.yahoo.ron.table.ButtonTableCellRenderer
    public class TestingButtonTableCellRenderer implements ActionListener{
         public TestingButtonTableCellRenderer(){
              JFrame frame = new JFrame("Testing ButtonTableCellRenderer");
              frame.getContentPane().setLayout(new GridLayout(1, 1));
              JTable table = new JTable(new UneditableTableModel(new ThreadMonitor()));
              TableColumnModel tableColumnModel = table.getColumnModel();
              // get the last column.
              TableColumn tableColumn = tableColumnModel.getColumn(tableColumnModel.getColumnCount() - 1);
              // apply the cell renderer.
              tableColumn.setCellRenderer(new ButtonTableCellRenderer(this));
              frame.getContentPane().add(new JScrollPane(table));
              frame.pack();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
         public void actionPerformed(ActionEvent ae){
              // do nothing for now.
         static public void main(String[] args){
              new TestingButtonTableCellRenderer();
    // Okie!! I dont include my source of ThreadMonitor.java and UneditableTableModel.
    // If problem occur, make some modification. Okie!
    // Thanks! God bless you all!

  • A Problem on removing a ActionListener

    In my program, due to the structure constraint, I have one action listener attached to a button in one place. And in somewhere else of my code I have to attach another action listener to this button, in this listener's actionPerformed method, I need to prevent the actionListener which I attached earlier being triggered. but I always fail to do so, here is a simplied code which can describe my situation.
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    public class ListenerTest {
    public ListenerTest(){
         final JButton button=new JButton();
         final Listener l=new Listener();
         button.addActionListener(l);
         button.addActionListener(new ActionListener(){;
         public void actionPerformed(ActionEvent e){
              System.out.println("listener 2");
              button.removeActionListener(l);
         button.doClick();
    private class Listener implements ActionListener{
         public void actionPerformed(ActionEvent e){
              System.out.println("listenr 1");
    public static void main(String[] args){
         ListenerTest test=new ListenerTest();
    }while run into the listener 2, I want prevent the trigger of listener 1, by using removeActionListener here, I can not get my expected effect, don't know how to do? Thanks in advance

    for example:
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class ListenerTest2 {
       private static void createAndShowUI() {
          JPanel panel = new JPanel(new BorderLayout());
          final LTPanel ltPanel = new LTPanel();
          final ActionListener newListener = new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                System.out.println("Now the *new* action listener is active");
          JToggleButton listenerToggle = new JToggleButton("Listener Toggle");
          listenerToggle.addActionListener(new ActionListener() {
             private ActionListener[] allAListeners;
             public void actionPerformed(ActionEvent e) {
                JToggleButton toggleBtn = (JToggleButton)e.getSource();
                JButton button = ltPanel.getButton();
                if (toggleBtn.isSelected()) {
                   allAListeners = button.getActionListeners();
                   for (ActionListener aListener : allAListeners) {
                      button.removeActionListener(aListener);
                   button.addActionListener(newListener);
                else {
                   button.removeActionListener(newListener);
                   for (ActionListener aListener : allAListeners) {
                      button.addActionListener(aListener);
          panel.add(ltPanel, BorderLayout.CENTER);
          panel.add(listenerToggle, BorderLayout.SOUTH);
          JFrame frame = new JFrame("ListenerTest2");
          frame.getContentPane().add(panel);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
    class LTPanel extends JPanel {
       private JButton button = new JButton("Button");
       public LTPanel() {
          button.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                System.out.println("The original action listener is active");
          add(button);
       public JButton getButton() {
          return button;
    }

  • JButton and ActionListeners

    I would like to change the ActionListeners registered to a JButton when the user clicks on a JButton. However there is a problem with this (see below). A typical procedure would go as follows:
    1) User clicks on button
    2) Get the appropriate listener from a list of listeners
    3) Remove the current listener(s) from the button
    4) Add the new listener(s)
    However, for some reason, the instructions of the new listener class are getting called. Is there a way of preventing this and if so, can someone please guide me in the right direction?
    Stephen

    It does not seem to happen like what you have said. Please see the test code below:
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.WindowConstants;
    public class Temp extends JFrame {
         private JButton b = null;
         public Temp() {
              super("Test");
              setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              getContentPane().setLayout(new BorderLayout());
              b = new JButton("Click Me!");
              b.addActionListener(new ActionListener1());
              getContentPane().add(b);
              pack();
              setVisible(true);
         class ActionListener1 implements ActionListener {
              public void actionPerformed(ActionEvent evt) {
                   System.out.println("Action Listener 1");
                   b.removeActionListener(this);
                   b.addActionListener(new ActionListener2());
         class ActionListener2 implements ActionListener {
              public void actionPerformed(ActionEvent evt) {
                   System.out.println("Action Listener 2");
         public static void main(String args []) {
              new Temp();
    }The first time you click the button action listener 1 code gets executed. From the second time onwards the action listener 2 code gets executed.
    Hope this helps
    Sai Pullabhotla

  • Changing cursor when rollover Jbutton

    hi All...i need help
    i want to change the cursor when i move my mouse over the button into hand cursor, then when the button being pressed, cursor change to Wait cursor
    here code of mine..
    import java.awt.Color;
    import java.awt.Cursor;
    import java.awt.GraphicsEnvironment;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    * @author tys
    public class cursor_test extends JFrame{
        public cursor_test(){                               
            add_panel panel = new add_panel();              
            add(panel);       
            setBackground(Color.WHITE);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            //GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            setSize(200,200);
            setVisible(true);
            setTitle("Test cursor");
        public static void main(String[] args){
            new cursor_test();
        }//Main  
    }//end class frame
    class add_panel extends JPanel{
        public add_panel(){
            setLayout(null);
            JButton btn1 = new JButton("button");
            btn1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                      setCursor(new Cursor(Cursor.WAIT_CURSOR));                 
                      //do my program here
                      try{
                          Thread.sleep(1000);                     
                      catch(Exception z){};                                   
                      setCursor(new Cursor(Cursor.DEFAULT_CURSOR));                   
            });//emd ActionListener
            btn1.setSize(90, 30);
            btn1.setLocation(50, 40);
            btn1.setCursor(new Cursor(Cursor.HAND_CURSOR));       
            add(btn1);       
    }//end class panelwhat did i do wrong in there...because every time i pressed the button..the cursor still Hand Cursor
    Thx
    tys
    Edited by: KingMao on 22 Sep 08 19:35

    Hope this wll helps to you.
    class add_panel extends JPanel{
        public add_panel(){
            setLayout(null);
            final JButton btn1 = new JButton("button");
            btn1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                      *btn1.setCursor(new Cursor(Cursor.WAIT_CURSOR));*                 
                      //do my program here
                      try{
                          Thread.sleep(1000);
                          *btn1.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));*                    
                      catch(Exception z){};                                   
                      setCursor(new Cursor(Cursor.DEFAULT_CURSOR));                   
            });//emd ActionListener
            btn1.setSize(90, 30);
            btn1.setLocation(50, 40);
            btn1.setCursor(new Cursor(Cursor.HAND_CURSOR));       
            add(btn1);       
    }//end class panel

  • Assigning the cost center directly to the person

    Dear friends
    We have to assign the cost center to position, and when the position is assigned to a person, he inherits the cost center from the position
    But the requirement is to assign the cost center directly to the person, with out assigning to the position, can you suggest any alternate to do this
    Regards
    Kiran

    Hello
    Maintain infotype 0027 from pa30 for the personnel number directly....
    cheers

  • How to assign the enter pressing to the button click event of swing button?

    Hello to all you pro's,
    I can't find how to make my button a default button so it will respond to an enter press.
    any help will be most appreciated.
    thanks in advanced.

    get the RootPane and call setDefaultButton on it. Something like so:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    class SwingFu2 extends JPanel
        private JButton buttonOK = new JButton("OK");
        private JButton buttonCancel = new JButton("Cancel");
        private JTextField textfield = new JTextField(12);
        private JFrame frame;
        SwingFu2(JFrame frame)
            this.frame = frame;
            ActionListener buttonActionListener = new ButtonActionListener();
            buttonOK.addActionListener(buttonActionListener);
            buttonCancel.addActionListener(buttonActionListener);
            add(textfield);
            add(buttonOK);
            add(buttonCancel);
            frame.getRootPane().setDefaultButton(buttonOK);
        private class ButtonActionListener implements ActionListener
            @Override
            public void actionPerformed(ActionEvent e)
                String command = e.getActionCommand();
                if (command.equalsIgnoreCase("OK"))
                    System.out.println("OK pressed");
                    System.out.print("Text in textfield: ");
                    System.out.println(textfield.getText());
                else if (command.equalsIgnoreCase("Cancel"))
                    frame.dispose();
        private static void createAndShowUI()
            JFrame frame = new JFrame("SwingFu1");
            frame.getContentPane().add(new SwingFu2(frame));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }

  • Unable to remove the Set Type assignment to product Hierarchy

    Hi
    I have created a set type and assigned to a product hierarchy.
    Now I want to undo the assignment as this has been inherited by the lower level hierarchies.
    Can anyone suggest how to remove this.
    Thanks & Regards
    Subhabrata

    Hi Dash,
    Sorry to say that once you have assigned the set type to a product hierarchy you can not remove this.
    Best regards,
    Vikash.

  • JButton and JComboBox

    Hi,
    I'm having problems with my comboboxes. Basically, I need that after I press a button, it would take what's selected in the combobox and pass it to database. What would be the sample code for that. Do I need to add ActionListener or ItemListener to the combobox. I'm a little confused with those.
    Thank you

    That's not really how you implement an actionlistener. Whenever the JButton is clicked the actionPeformed method of your actionListener is called. The way you have it set up, you parse what's in the combo box once and then repeatedly send this value off to the database everytime the button is pressed.
    And making a component static just to access almost always constitutes as a bad idea. You can make the DataEntryButton an innerclass. Alternatively you can declare a field in the class and pass along the combo box.
    public DataEntryButton implements ActionListener {
         JComboBox semesters;
        public DataEntryButton(JComboBox semesters) {
            this.semesters = semesters;
        public void actionPerformed(ActionEvent event) {
             int semester = Integer.parseInt((String) semesters.getSelectedItem());
            //and then I send it to DB
    }

Maybe you are looking for