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

Similar Messages

  • ActionListener with JButton and JMenu

    How do I implement actions for both a JButton and a JMenuItem? Would I have to set it in the actionPerformed method(Action e), because that doesn't seem to work, or else I don't know how to do it. Help would be appreciated.

    But the thing is that I don't want the same action for both the Button and MenuItem.Then create separate ActionListeners for each component.
    button.add(new ActionListener()
        public void actionPerformed(ActionEvent e)
            // add your code here
    }Or test which button was pressed in the actionPerformed method. The Swing tutorial on How to Use Buttons, gives example of this:
    http://java.sun.com/docs/books/tutorial/uiswing/components/button.html

  • Actions and ActionListeners as parameters

    Hi everybody,
    I want to overload a method so it can take either 2 Actions, 2 ActionListeners, or one of each. The issue with this is that I'd have to make 4 overloaded signatures and almost identical methods, like this:
    method( action, action )
    method( action, listener )
    method( listener, action )
    method( listener, listener )It seems like doing it this way would result in a lot of extra code, and hence become a real pain in the neck. So, I was curious, has anyone else either tried to do this before, or do you have any ideas as to how I might be able to do this more efficiently? When I looked at the API it didn't look like Actions and ActionListeners share a root class I can use.
    Thanks,
    Jezzica85

    jezzica85 wrote:
    Hi everybody,
    I want to overload a method so it can take either 2 Actions, 2 ActionListeners, or one of each. The issue with this is that I'd have to make 4 overloaded signatures and almost identical methods, like this:
    method( action, action )
    method( action, listener )
    method( listener, action )
    method( listener, listener )
    Well, if you want to support that then you are just going to have to do suffer through it, the only shortcut I can recommend is that your method(action, listener) and method(listener, action) are the same so you only have to implement 1 and just use the other as a entry point to call the one you wish to contain the code.

  • Executable JARs, JFrames, and ActionListeners

    I'm fairly new to Java, and am currently attempting to create my first JAR executable file. I am using the Eclipse IDE and JDK 5.0. I use Eclipse's export option to create a JAR executable. When the JAR is exectued, it successfully creates and displays the intial JFrame; however, a second JFrame that is created by an ActionListener on a JButton, and is based on input from a JTextArea, is never created when the JButton is clicked on. The second JFrame also accesses txt files based upon the JTextArea input, each of which are contained inside of the JAR file as well. The program compiles and runs successfully when ran as a Java Application or SWT Application in Eclipse, so I am unsure why the export ability is not working.
       public FrameClass1()
          inputTextArea = new JTextArea(29, 95);
          inputTextArea.setFont(new Font("Courier New", 0, 12));
          //Adds the inputTextArea to a JScrollPane, and then adds it to the frame's Center
          buttonPanel = new JPanel();
          submitButton = new JButton("Submit");
          submitButton.addActionListener(new
             ActionListener()
                public void actionPerformed(ActionEvent event)
                   String textInput = inputTextArea.getText();
                   //Output frame creation
                   FrameClass2 outputFrame = new FrameClass2(textInput);
                   outputFrame.setVisible(true);
          buttonPanel.add(submitButton);
          //buttonPanel is added to the frame's south portion
       }Any suggestions as to why the second frame class is not being generated and how to fix it are greatly appreciated. Thanks in advance.

    To capture the error messages, I've used this try-catch statement, though as I posted earlier, I am not familar with JARs. I have identified that my error is a IllegalArguementException, though I cannot find a precise location of where this exception occurs, as the exceptionOutputFrame is never populated with the stack trace. I've tried both e.getMessage() (below) and e.printStackTrace().toString() with both JLabels and JTextAreas, but the JPanel will not populate with data. Could anybody recommend a good method of outputing the stack trace? In addition, could someone explain the use of getResourceAsStream a little more? Should I be using the class ClassLoader's method or the interface ServletContext? I'm a little rough around the edges with the idea of a resource, so does anybody have a good online reference that I could look at?
         try
              // Insert output frame creation here.
              Class2 outputFrame = new Class2(textInput);
              outputFrame.setVisible(true);
         catch(Exception e)
              JFrame exceptionOutputFrame = new JFrame(e.getClass().getName());
              JScrollPane exceptionOutputScrollPane = new JScrollPane();
              JPanel exceptionOutputPanel = new JPanel();
              JTextArea exceptionOutputLabel = new JTextArea(e.getMessage());
              exceptionOutputPanel.add(exceptionOutputLabel);
              exceptionOutputScrollPane.add(exceptionOutputPanel);
              exceptionOutputFrame.add(exceptionOutputScrollPane);
              exceptionOutputFrame.setSize(exceptionOutputLabel.getWidth(), DEFAULT_HEIGHT);
              exceptionOutputFrame.setVisible(true);
         catch(Error e)
              JFrame errorOutputFrame = new JFrame(e.getClass().getName());
              JScrollPane errorOutputScrollPane = new JScrollPane();
              JPanel errorOutputPanel = new JPanel();
              JTextArea errorOutputLabel = new JTextArea(e.getMessage());
              errorOutputPanel.add(errorOutputLabel);
              errorOutputScrollPane.add(errorOutputPanel);
              errorOutputFrame.add(errorOutputScrollPane);
              errorOutputFrame.setSize(errorOutputLabel.getWidth(), DEFAULT_HEIGHT);
              errorOutputFrame.setVisible(true);
         }

  • Using JCheckBox, JButton and JTextArea with JDBC

    Hello shlumph and SoulTech2012.
    thanks for the reply. I�m wondering do any of you have links to web pages that include tutorials and source code on using JCheckBox, JButton and JTextArea with JDBC. would any of you who have experience with using JCheckBox, JButton, JTextArea and JDBC together be able to give me a few tips on how to select certain data from a table using JCheckBox, JButton and display the data in a JTextArea? examples of such data could be CD/DVD/Game data - i want users of my video library system to be able to view CD/DVD/Game information by name, age category, type and year. Users should be able to click on a check box (e.g. view by name, age category, type or year) and press a button. What would happen then is that data from the Product table would appear in the text area (which could be placed beneath the check box + button inside a frame and/or panel).
    Thank you very much for your help.

    Quit triple posting and cross posting your questions all over the forum. You already have a posting in this forum on this topic and another posting in the Swing forum and another posting in the Programming forum.

  • Sizing issues JButton and JTextField

    Hi,
    I am new to swing and could use a little guidance on the placement of JButtons and JTextFields on a component. I have tried the setSize method and it doesn't work so I think it has to do with the layout possibly. I need to know how I can resize the testMe button and enlarge the JTextFields. Here is my code.
    I would appreciate any other suggestions as well.
    Thanks,
    Steve
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class TestButton {
        public static void main(String[] arguments) {
            JFrame frame = new Interface();
            frame.show();
    class Interface extends JFrame {
         private dataPanel screenvar;
         private JTextArea msgout;
         Interface () {
              super("This is a JFrame");
            setSize(600, 200);  // width, height
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel pane = new JPanel();
              // create empty space
              pane.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30)); //top, left, bottom, right
              // declare components
              msgout = new JTextArea( 8, 40 );
              dataPanel screenvar = new dataPanel();
              buttonPanel testMe = new buttonPanel(screenvar, msgout);
              // end declare components
            GridLayout grid = new GridLayout(1, 4, 5, 15); // row, col, hgap, vgap
            pane.setLayout(grid);
              pane.add(testMe);
              pane.add(msgout);
                 pane.add( new JScrollPane(msgout));
              pane.add(screenvar);
              msgout.append("Successful");
              setContentPane(pane);
    //          pack();
              setVisible(true);
    class databaseConnection {
    class updateDataFields implements ActionListener {     // 400
         private dataPanel abc;
         private JTextArea msg;
         public updateDataFields(dataPanel xyz, JTextArea msgout) {     // 100
              abc = xyz;
              msg = msgout;
         }     // 100
         public void actionPerformed(ActionEvent evt) {     // 200
              String command = evt.getActionCommand();
                   if (command.equals("TestMe")){     // 300
                        msg.append("\nSuccessful");
                        abc.right01.setText("1000");
                        abc.left02.setText("Hi!");
                        abc.right03.setText("123456");
                   }     // 300
         }     // 200
    }     // 400
    class dataPanel extends JPanel {     // Similar to DataPanel in Duke's Bakery
         JLabel left1, left2, left3, right1, right2, right3;
         JTextField left01, left02, left03, right01, right02, right03;
        public dataPanel () {     // 1
              GridLayout grid = new GridLayout(3, 2, 5, 15); // row, col, hgap, vgap
              setLayout(grid);                    // different than panex.setLayout(xgrid);
              left1 = new JLabel("Left1");
              add(left1);
              left01 = new JTextField(0);
              add(left01);
              right1 = new JLabel("Right1");
              add(right1);
              right01 = new JTextField(0);
              add(right01);
              left2 = new JLabel("Left2");
              add(left2);
              left02 = new JTextField(0);
              add(left02);
              right2 = new JLabel("Right2");
              add(right2);
              right02 = new JTextField(0);
              add(right02);
              left3 = new JLabel("Left3");
              add(left3);
              left03 = new JTextField(0);
              add(left03);
              right3 = new JLabel("Right3");
              add(right3);
              right03 = new JTextField(0);
              add(right03);
    class buttonPanel extends JPanel {     // 200   Similar to ButtonPanel in Duke's Bakery
         public buttonPanel(dataPanel xyz, JTextArea msgout) {     // 100
              GridLayout actionGrid = new GridLayout(1, 1, 5, 15); // row, col, hgap, vgap
              setLayout(actionGrid);                    // different than panex.setLayout(xgrid);
              JButton buttonTest = new JButton("TestMe");
              buttonTest.setSize(5,5);
              buttonTest.addActionListener( new updateDataFields( xyz, msgout ));
              add(buttonTest);
         }     // 100
    }     // 200

    Nope, doesn't work. Does the fact that the JButton is part of GridLayout have any affect on this resizing issue?
    Thanks for your help, I appreciate it.
    Steve

  • Numbers on JButtons and set JButtons to Opaque

    Hi everyone:
    please check for me why numbers(like 1 to 35) don't appears on JButtons, and why I setOpaque(true) to JButtons, it doesn't work. Thanks
    // why I can not see the numbers (1 to 35) in JButtons ????????????
    // and how can I operate setOpaque(true) to JButtons.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.GridLayout;
    public class DrawCalendar extends JPanel{
         private static DrawCalendar dC;
         private static JButton jB1,jB2,jB3;
         private static Dimension dMS;
         private static GridLayout gL;
         private static Container c;
         // why I can not see the numbers (1 to 35) in JButtons ????????????
         public DrawCalendar(){
              JButton j= new JButton("1");
         gL=new GridLayout(5,7,4,4);
              setLayout(gL);
    add(j);
    add(new JButton("2"));
    add(new JButton("3"));
    add(new JButton("4"));
    add(new JButton("5"));
    add(new JButton("6"));
    add(new JButton("7"));
    add(new JButton("8"));
    add(new JButton("9"));
    add(new JButton("10"));
    add(new JButton("11"));
    add(new JButton("12"));
    add(new JButton("12"));
    add(new JButton("14"));
    add(new JButton("15"));
    add(new JButton("16"));
    add(new JButton("17"));
    add(new JButton("18"));
    add(new JButton("19"));
    add(new JButton("20"));
    add(new JButton("21"));
    add(new JButton("22"));
    add(new JButton("23"));
    add(new JButton("24"));
    add(new JButton("25"));
    add(new JButton("26"));
    add(new JButton("27"));
    add(new JButton("28"));
    add(new JButton("29"));
    add(new JButton("30"));
    add(new JButton("31"));
    add(new JButton("32"));
    add(new JButton("33"));
    add(new JButton("34"));
    add(new JButton("35"));
    import java.awt.*;
    import java.awt.Color;
    import javax.swing.*;
    import javax.swing.JButton;
    import javax.swing.JMenuBar;
    public class TestMain extends JFrame{
    private static JButton b1, b2, b3;
    private static TestMain tM;
         private static JPanel jP;
    private static Container c;
    private static DrawCalendar dC;
         public static void main(String[] args){
         tM = new TestMain();
         addItems();
         tM.setVisible(true);
         public TestMain(){
         super(" Test");
         dC=new DrawCalendar();
         setSize(600,600);
    //set up layoutManager
    c=getContentPane();
    c.setLayout ( new GraphPaperLayout(new Dimension (8,20)));
    //set up three Button and one JPanel
    b1=new JButton("1");
    b1.setOpaque(true);
    b2=new JButton("2");
    b2.setOpaque(true);
    b3=new JButton("3");
    b3.setOpaque(true);
    //add the munuBar, the Jpanel and three JButtons
    public static void addItems(){
         c.add(b1, new Rectangle(5,0,1,1));
         c.add(b2, new Rectangle(6,0,1,1));
    c.add(b3, new Rectangle(7,0,1,1));
         c.add(dC, new Rectangle(5,1,3,5));
    import java.awt.*;
    import java.util.Hashtable;
    import java.io.*;
    * The <code>GraphPaperLayout</code> class is a layout manager that
    * lays out a container's components in a rectangular grid, similar
    * to GridLayout. Unlike GridLayout, however, components can take
    * up multiple rows and/or columns. The layout manager acts as a
    * sheet of graph paper. When a component is added to the layout
    * manager, the location and relative size of the component are
    * simply supplied by the constraints as a Rectangle.
    * <p><code><pre>
    * import java.awt.*;
    * import java.applet.Applet;
    * public class ButtonGrid extends Applet {
    * public void init() {
    * setLayout(new GraphPaperLayout(new Dimension(5,5)));
    * // Add a 1x1 Rect at (0,0)
    * add(new Button("1"), new Rectangle(0,0,1,1));
    * // Add a 2x1 Rect at (2,0)
    * add(new Button("2"), new Rectangle(2,0,2,1));
    * // Add a 1x2 Rect at (1,1)
    * add(new Button("3"), new Rectangle(1,1,1,2));
    * // Add a 2x2 Rect at (3,2)
    * add(new Button("4"), new Rectangle(3,2,2,2));
    * // Add a 1x1 Rect at (0,4)
    * add(new Button("5"), new Rectangle(0,4,1,1));
    * // Add a 1x2 Rect at (2,3)
    * add(new Button("6"), new Rectangle(2,3,1,2));
    * </pre></code>
    * @author Michael Martak
    * Updated by Judy Bowen, September 2002 to allow serialization
    public class GraphPaperLayout implements LayoutManager2, Serializable{
    int hgap; //horizontal gap
    int vgap; //vertical gap
    Dimension gridSize; //grid size in logical units (n x m)
    Hashtable compTable; //constraints (Rectangles)
    * Creates a graph paper layout with a default of a 1 x 1 graph, with no
    * vertical or horizontal padding.
    public GraphPaperLayout() {
    this(new Dimension(1,1));
    * Creates a graph paper layout with the given grid size, with no vertical
    * or horizontal padding.
    public GraphPaperLayout(Dimension gridSize) {
    this(gridSize, 0, 0);
    * Creates a graph paper layout with the given grid size and padding.
    * @param gridSize size of the graph paper in logical units (n x m)
    * @param hgap horizontal padding
    * @param vgap vertical padding
    public GraphPaperLayout(Dimension gridSize, int hgap, int vgap) {
    if ((gridSize.width <= 0) || (gridSize.height <= 0)) {
    throw new IllegalArgumentException(
    "dimensions must be greater than zero");
    this.gridSize = new Dimension(gridSize);
    this.hgap = hgap;
    this.vgap = vgap;
    compTable = new Hashtable();
    * @return the size of the graph paper in logical units (n x m)
    public Dimension getGridSize() {
    return new Dimension( gridSize );
    * Set the size of the graph paper in logical units (n x m)
    public void setGridSize( Dimension d ) {
    setGridSize( d.width, d.height );
    * Set the size of the graph paper in logical units (n x m)
    public void setGridSize( int width, int height ) {
    gridSize = new Dimension( width, height );
    public void setConstraints(Component comp, Rectangle constraints) {
    compTable.put(comp, new Rectangle(constraints));
    * Adds the specified component with the specified name to
    * the layout. This does nothing in GraphPaperLayout, since constraints
    * are required.
    public void addLayoutComponent(String name, Component comp) {
    * Removes the specified component from the layout.
    * @param comp the component to be removed
    public void removeLayoutComponent(Component comp) {
    compTable.remove(comp);
    * Calculates the preferred size dimensions for the specified
    * panel given the components in the specified parent container.
    * @param parent the component to be laid out
    * @see #minimumLayoutSize
    public Dimension preferredLayoutSize(Container parent) {
    return getLayoutSize(parent, true);
    * Calculates the minimum size dimensions for the specified
    * panel given the components in the specified parent container.
    * @param parent the component to be laid out
    * @see #preferredLayoutSize
    public Dimension minimumLayoutSize(Container parent) {
    return getLayoutSize(parent, false);
    * Algorithm for calculating layout size (minimum or preferred).
    * <p>
    * The width of a graph paper layout is the largest cell width
    * (calculated in <code>getLargestCellSize()</code> times the number of
    * columns, plus the horizontal padding times the number of columns
    * plus one, plus the left and right insets of the target container.
    * <p>
    * The height of a graph paper layout is the largest cell height
    * (calculated in <code>getLargestCellSize()</code> times the number of
    * rows, plus the vertical padding times the number of rows
    * plus one, plus the top and bottom insets of the target container.
    * @param parent the container in which to do the layout.
    * @param isPreferred true for calculating preferred size, false for
    * calculating minimum size.
    * @return the dimensions to lay out the subcomponents of the specified
    * container.
    * @see java.awt.GraphPaperLayout#getLargestCellSize
    protected Dimension getLayoutSize(Container parent, boolean isPreferred) {
    Dimension largestSize = getLargestCellSize(parent, isPreferred);
    Insets insets = parent.getInsets();
    largestSize.width = ( largestSize.width * gridSize.width ) +
    ( hgap * ( gridSize.width + 1 ) ) + insets.left + insets.right;
    largestSize.height = ( largestSize.height * gridSize.height ) +
    ( vgap * ( gridSize.height + 1 ) ) + insets.top + insets.bottom;
    return largestSize;
    * Algorithm for calculating the largest minimum or preferred cell size.
    * <p>
    * Largest cell size is calculated by getting the applicable size of each
    * component and keeping the maximum value, dividing the component's width
    * by the number of columns it is specified to occupy and dividing the
    * component's height by the number of rows it is specified to occupy.
    * @param parent the container in which to do the layout.
    * @param isPreferred true for calculating preferred size, false for
    * calculating minimum size.
    * @return the largest cell size required.
    protected Dimension getLargestCellSize(Container parent,
    boolean isPreferred) {
    int ncomponents = parent.getComponentCount();
    Dimension maxCellSize = new Dimension(0,0);
    for ( int i = 0; i < ncomponents; i++ ) {
    Component c = parent.getComponent(i);
    Rectangle rect = (Rectangle)compTable.get(c);
    if ( c != null && rect != null ) {
    Dimension componentSize;
    if ( isPreferred ) {
    componentSize = c.getPreferredSize();
    } else {
    componentSize = c.getMinimumSize();
    // Note: rect dimensions are already asserted to be > 0 when the
    // component is added with constraints
    maxCellSize.width = Math.max(maxCellSize.width,
    componentSize.width / rect.width);
    maxCellSize.height = Math.max(maxCellSize.height,
    componentSize.height / rect.height);
    return maxCellSize;
    * Lays out the container in the specified container.
    * @param parent the component which needs to be laid out
    public void layoutContainer(Container parent) {
    synchronized (parent.getTreeLock()) {
    Insets insets = parent.getInsets();
    int ncomponents = parent.getComponentCount();
    if (ncomponents == 0) {
    return;
    // Total parent dimensions
    Dimension size = parent.getSize();
    int totalW = size.width - (insets.left + insets.right);
    int totalH = size.height - (insets.top + insets.bottom);
    // Cell dimensions, including padding
    int totalCellW = totalW / gridSize.width;
    int totalCellH = totalH / gridSize.height;
    // Cell dimensions, without padding
    int cellW = (totalW - ( (gridSize.width + 1) * hgap) )
    / gridSize.width;
    int cellH = (totalH - ( (gridSize.height + 1) * vgap) )
    / gridSize.height;
    for ( int i = 0; i < ncomponents; i++ ) {
    Component c = parent.getComponent(i);
    Rectangle rect = (Rectangle)compTable.get(c);
    if ( rect != null ) {
    int x = insets.left + ( totalCellW * rect.x ) + hgap;
    int y = insets.top + ( totalCellH * rect.y ) + vgap;
    int w = ( cellW * rect.width ) - hgap;
    int h = ( cellH * rect.height ) - vgap;
    c.setBounds(x, y, w, h);
    // LayoutManager2 /////////////////////////////////////////////////////////
    * Adds the specified component to the layout, using the specified
    * constraint object.
    * @param comp the component to be added
    * @param constraints where/how the component is added to the layout.
    public void addLayoutComponent(Component comp, Object constraints) {
    if (constraints instanceof Rectangle) {
    Rectangle rect = (Rectangle)constraints;
    if ( rect.width <= 0 || rect.height <= 0 ) {
    throw new IllegalArgumentException(
    "cannot add to layout: rectangle must have positive width and height");
    if ( rect.x < 0 || rect.y < 0 ) {
    throw new IllegalArgumentException(
    "cannot add to layout: rectangle x and y must be >= 0");
    setConstraints(comp, rect);
    } else if (constraints != null) {
    throw new IllegalArgumentException(
    "cannot add to layout: constraint must be a Rectangle");
    * Returns the maximum size of this component.
    * @see java.awt.Component#getMinimumSize()
    * @see java.awt.Component#getPreferredSize()
    * @see LayoutManager
    public Dimension maximumLayoutSize(Container target) {
    return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
    * Returns the alignment along the x axis. This specifies how
    * the component would like to be aligned relative to other
    * components. The value should be a number between 0 and 1
    * where 0 represents alignment along the origin, 1 is aligned
    * the furthest away from the origin, 0.5 is centered, etc.
    public float getLayoutAlignmentX(Container target) {
    return 0.5f;
    * Returns the alignment along the y axis. This specifies how
    * the component would like to be aligned relative to other
    * components. The value should be a number between 0 and 1
    * where 0 represents alignment along the origin, 1 is aligned
    * the furthest away from the origin, 0.5 is centered, etc.
    public float getLayoutAlignmentY(Container target) {
    return 0.5f;
    * Invalidates the layout, indicating that if the layout manager
    * has cached information it should be discarded.
    public void invalidateLayout(Container target) {
    // Do nothing

    Hello,
    I think you have really a problem with this layout.
    Please first check the standard [url http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html]LayoutManager.
    JButtons are opaque usually and they will be shown if you use another LayoutManager:import java.awt.*;
    import javax.swing.*;
    class DrawCalendar extends JPanel
         private static DrawCalendar dC;
         private static JButton jB1, jB2, jB3;
         private static Dimension dMS;
         private static GridLayout gL;
         private static Container c;
         // why I can not see the numbers (1 to 35) in JButtons ????????????
         public DrawCalendar()
              JButton j = new JButton("1");
              gL = new GridLayout(5, 7, 4, 4);
              setLayout(gL);
              add(j);
              add(new JButton("2"));
              add(new JButton("3"));
              add(new JButton("4"));
              add(new JButton("5"));
              add(new JButton("6"));
              add(new JButton("7"));
              add(new JButton("8"));
              add(new JButton("9"));
              add(new JButton("10"));
              add(new JButton("11"));
              add(new JButton("12"));
              add(new JButton("12"));
              add(new JButton("14"));
              add(new JButton("15"));
              add(new JButton("16"));
              add(new JButton("17"));
              add(new JButton("18"));
              add(new JButton("19"));
              add(new JButton("20"));
              add(new JButton("21"));
              add(new JButton("22"));
              add(new JButton("23"));
              add(new JButton("24"));
              add(new JButton("25"));
              add(new JButton("26"));
              add(new JButton("27"));
              add(new JButton("28"));
              add(new JButton("29"));
              add(new JButton("30"));
              add(new JButton("31"));
              add(new JButton("32"));
              add(new JButton("33"));
              add(new JButton("34"));
              add(new JButton("35"));
    public class TestMain extends JFrame
         private static JButton b1, b2, b3;
         private static TestMain tM;
         private static JPanel jP;
         private static Container c;
         private static DrawCalendar dC;
         public static void main(String[] args)
              tM = new TestMain();
              addItems();
              tM.setVisible(true);
         public TestMain()
              super(" Test");
              dC = new DrawCalendar();
              setSize(600, 600);
              //set up layoutManager
              c = getContentPane();
              c.setLayout(new FlowLayout());
              //set up three Button and one JPanel
              b1 = new JButton("1");
              b1.setOpaque(true);
              b2 = new JButton("2");
              b2.setOpaque(true);
              b3 = new JButton("3");
              b3.setOpaque(true);
         //add the munuBar, the Jpanel and three JButtons
         public static void addItems()
              c.add(b1);
              c.add(b2);
              c.add(b3);
              c.add(dC);
    }regards
    Tim

  • JButton and JComboBox problems!!!

    I have a program that has a bunch of different panels, and each of those has panels in it and soforth. Several levels down the line I add a JPanel that has a JComboBox, some JButtons and a JTextField. The textfield works fine: you can type in text, etc. However, I cannot click the JButtons (when you mouse over them, they change color appropriately, but clicking does nothing visually, and the ActionListener does not catch anything). In addition, when clicked, the JComboBox displays in a totally inappropriate area!!! (see screenshot below)
    http://www.duke.edu/~yv2/JComboBox.JPG <-- SCREENSHOT
    Any ideas?

    However, I cannot click the JButtons (when you mouse
    over them, they change color appropriately, but
    clicking does nothing visually, and the
    ActionListener does not catch anything).Make sure you have added the ActionListener to the JButton, and provide implementation for the actionPerformed() method.

  • JButtons and Icons

    Hi,
    I'd like to know how you can display a background image on a JButton, so the button is completely filled by the imaged. I've tried icons but they will only display next to the text...I've also tried extending JButton but can't get it to work...I have to use a JButton or other lightweight component. Anyone know how this is done?
    Regards,
    Falk

    Here's a simple example of extending JButton and rendering an Image into it.
    -Brian
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.swing.JButton;
    * A JButton that contains an image.
    public class ImageButton extends JButton {
            private Image theImage;
             * Constructor.
             * @param anImage An instance of Image to be drawn in the button
            public ImageButton(Image anImage) {
                    theImage = anImage;
             * Render the image on the button.
            public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    if (theImage != null)
                          g.drawImage(theImage, 0, 0, null);
            public void setImage(Image anImage) {
                    theImage = anImage;
            public Image getImage() {
                    return theImage;
    }

  • JButtons and JTextfields conflicting

    Hey again,
    I have a JPanel which contains a JTextfield, a JButton and a JLabel.
    Basically, the user sticks a word in the JTextfield, presses enter, and the word gets displayed by the JLabel.
    At the moment I have the Jpanel listening for events from both the JTextField and the JButton, which means that clicking the button generates a getActionCommand()and the text on the JButton gets stuck on the JLabel- as if the word had been entered in the JTextField.
    It's easy enough to get something else to listen to the button to get round this, but I just wondered if there's a way of allowing the JPanel to listen to them both without having this conflict (just so that it's easier for me to keep track of everything!)
    Any suggestions muchly appreciated !!

    I just saw your posting date and could not help noticing that you posted this message in January. But I hope others can benefit from our feedbacks. First of all, you do not need to add a listener to a JPanel. You could add listeners to your other components and add them all to the panel.
    And in your textField you need to add actionListener and tell the label to setText the text it receives from the textField. Make sure that your components do not listener to only one actionListener.
    The following should be in your actionPerformed method:
    String string = textField.getText();
    label.setText(string);//the text from the textField.
    Hope this helps
    [email protected]

  • JSF Actions and ActionListeners with Tiles and forms

    I�m having a problem trying to use the Tiles functionality in Struts 1.1 with JSF and was wondering if anyone could help me.
    I have defined a very simple header, menu, content Tile that doesn�t involve nesting of tiles (ExampleTile_content1Level.jsp).
    I have 3 JSP pages, the first testHarness.jsp is NOT built using Tiles and is just used to load some test data into a session scoped bean using an actionListener and then forward to a Tile generated page (ExampleTile3.jsp) using a hard-coded action �applicationSummary� when a commandLink is pressed. This works fine for both the action and actionListener.
    ExampleTile3.jsp contains another commandLink that is meant to forward to another tile ExampleTile2.jsp. This also works until I try to add the <h:form> � </h:form> tag around the outside of the <h:panelGrid> tags in ExampleContent1.jsp when the action and actionListener then fail to fire and I get an �Error on Page� message in Explorer the detail of which says �Error �com_sun_rave_web_ui_appbase_renderer_CommandLinkRendererer� is null or not an object�.
    However I need a form so that I can bind UI controls to data from the bean stored in the session scope. This is only a problem when I use Tiles to define the pages. Does anyone know what I am doing wrong?
    Any help would be much appreciated.
    Tiles.xml
       <definition name="example3" path="/pages/exampleTile_content1Level.jsp" >
              <put name="headerClass" value="someStyle"/>
              <put name="menuClass" value="someStyle"/>
              <put name="contentClass" value="someStyle"/>
              <put name="header-title" value="/pages/exampleHeader.jsp" />
              <put name="menu" value="/pages/exampleMenu.jsp" />
              <put name="content" value="/pages/exampleContent1.jsp" />
       </definition>
       <definition name="example2" path="/pages/exampleTile_content1Level.jsp" >
              <put name="headerClass" value="someStyle"/>
              <put name="menuClass" value="someStyle"/>
              <put name="contentClass" value="someStyle"/>
              <put name="header" value="/pages/exampleHeader.jsp" />
              <put name="menu" value="/pages/exampleHeader.jsp" />
              <put name="content" value="/pages/exampleContent2.jsp" />
       </definition>ExampleTile3.jsp
    <f:view>
         <h:form>
              <tiles:insert definition="example3" flush="false" />
         </h:form>
    </f:view> ExampleTile2.jsp
    <f:view>
         <h:form>
              <tiles:insert definition="example2" flush="false" />
         </h:form>
    </f:view> Faces-config.xml
    <navigation-rule>
        <from-view-id>/pages/testHarness.jsp</from-view-id>
           <navigation-case>
                <from-outcome>applicationSummary</from-outcome>
                <to-view-id>/pages/exampleTile3.jsp</to-view-id>
              <redirect/>
           </navigation-case>
    </navigation-rule>
    <navigation-rule>
        <from-view-id>/pages/exampleTile3.jsp</from-view-id>
           <navigation-case>
                <from-outcome>nextPage</from-outcome>
                <to-view-id>/pages/exampleTile2.jsp</to-view-id>
                <redirect/>
           </navigation-case>
    </navigation-rule> ExampleTile_content1Level.jsp
    <tiles:importAttribute scope="request"/>
    <h:panelGrid columns="1" >
         <f:subview id="header-title">
              <tiles:insert name="header-title" flush="false" />
         </f:subview>
         <f:subview id="menu">
              <tiles:insert name="menu" flush="false" />
         </f:subview>
         <f:subview id="content">
              <tiles:insert name="content" flush="false" />
         </f:subview>
    </h:panelGrid> ExampleHeader.jsp / ExampleMenu.jsp
    <tiles:importAttribute scope="request"/>
    <h:panelGrid columns="1" columnClasses="someSyle">
         <h:outputFormat value="This is the {0}.">
              <f:param value="Header / Menu as appropriate "/>         
         </h:outputFormat>
    </h:panelGrid> ExampleContent1.jsp
    <tiles:importAttribute scope="request"/>
    <h:form>     <----- Fails with this tag included but works without it.
    <h:panelGrid columns="1" >
              <h:outputFormat value="This is the {0}.">
                   <f:param value="Content on the FIRST page"/>
              </h:outputFormat>
              <h:commandLink action="nextPage" immediate="false">
                   <h:outputText value="Click to go to next page"/>
              </h:commandLink>
    </h:panelGrid>
    </h:form> ExampleContent2.jsp
    <tiles:importAttribute scope="request"/>
    <h:panelGrid columns="1" >
         <h:outputFormat value="This is the {0}.">
              <f:param value="Content on the SECOND page"/>
         </h:outputFormat>
    </h:panelGrid>

    jezzica85 wrote:
    Hi everybody,
    I want to overload a method so it can take either 2 Actions, 2 ActionListeners, or one of each. The issue with this is that I'd have to make 4 overloaded signatures and almost identical methods, like this:
    method( action, action )
    method( action, listener )
    method( listener, action )
    method( listener, listener )
    Well, if you want to support that then you are just going to have to do suffer through it, the only shortcut I can recommend is that your method(action, listener) and method(listener, action) are the same so you only have to implement 1 and just use the other as a entry point to call the one you wish to contain the code.

  • What's the difference between Action Objects and ActionListeners

    Hello,
    in the Introduction to JSF two ways handling action are demonstrated. One way is "Combining Component Data and Action Object" the other way is "Handling Events."
    What's the difference? When do I use this or that way?
    The one thing I understand is when using "Combining Component Data and Action Objects" I use the default ActionListener and I may directly access the input values.
    TIA,
    Juergen

    Hi Juergen,
    The bottomline is 'not much', only in the details to these two approaches differ.
    The ActionListener object will have events broadcast to it for a particular object by the event mechanism in JSF. You can add one to a specific component via the f:action_listener tag. This will have your listener getting events during specific points in the request processing lifecycle (you specify via your return value for getPhaseId).
    The Action class that an actionRef reference refers to an Action that will be invoked during the invoke application phase. (see pg 71).
    I would recommend using actionRefs and Action objects wherever possible and going to ActionListeners only when you need notifications during a specific phase of the request/response cycle.
    Hope this helps,
    -bd-
    http://bill.dudney.net

  • Jbuttons and applets and browsers

    hello folks. Well, I finally got my jbuttons to appear in by applet in ie5.5 and it is working fine except when someone resizes the browser window, the jbuttons dissapear. Does anyone know why this my occur? Does anyone know what I can do about it?
    The buttons are added to the panel and the panel into the container into init(). I add the container in paint(). Also in paint() I have .setVisible(true) for each button and the container.

    Hi!
    The reason why your buttons disappear is the layout you
    are using.
    Flow layout manager gives your components the prefered
    size.
    Grid layout manager does not.
    Border layout is a - let me say - a "mix" of both.
    If you use border layout with NORTH, SOUTH, EAST and
    WEST your components will be were they used to be.
    Add your buttons BorderLayout.SOUTH and they will
    stay there even if you resize.
    Somebody may correct me if I'm wrong.

  • How to create an array of JButtons and How to implment it ...

    This is what i want to do - I want to create an array of JButtons that has 8 rows of 8 buttons, could someone help me with this (im creating a checkers board) all i need is the array of buttons and them in 8 rows of 8 buttons .... im pretty confident in the way of making them do what i want but need help getting it up and running .... please note it is to be done in the swing environment and not in a applet or anything - ie in a JPanel and a JFrame .... any help would be GREATLY appreciated.

    U can try this
            JButton b[][] = new Button[8][8];
         setLayout(new YourLayout());
         for(int i =0; i<8; i++)
              for(int j =0; j<8; j++)
                   b[i][j] = new Button("Test");
                   b[i][j].addActionListener(new YourAction());
                   add(b[i][j]);
         }               

  • JButton and exception problem

    Hi all,
    I created a JButton, named open _DB, and add an ActionListener to this. I want that when I click the button the methods in the loop executed (see below for code). However, I always get exceptions. How can I catch these exceptions?
    If I use a try-catch loop I got the error:
    ModelClipTest.java:559: ';' expected
    public void actionPerformed(ActionEvent e)
    ModelClipTest.java:559: missing method body, or declare abstract
    public void actionPerformed(ActionEvent e)
    How can I solve this problem. Can anybody help me?
    Thanks
    Murat
    //CODE
    open_DB.addActionListener
    (new ActionListener()
    public void actionPerformed(ActionEvent e)
    try
    ifcdemo = new IFC_Demo();
    ifcdemo.execute();
    IFC_RelFillsElement_Query.query_fill(ifcdemo);
    IFC_RelVoidsElement_Query.query_void_ids(ifcdemo);
    IFC_BuildingStorey_Query.query_buildingstorey(ifcdemo);
    } //CLOSE TRY
    catch(Exception ex)
    System.out.println("Exception caught");
    System.out.println(":-(");
    } //CLOSE CATCH
    );

    yes, sorry. However, I still get these exceptions for the methods inside.
    What should I do to get rid of these exceptions?
    Thanks.
    ModelClipTest.java:579: unreported exception java.lang.Throwable; must be caught or declared to be thrown
                                  IFC_RelFillsElement_Query.query_fill(ifcdemo);
    ModelClipTest.java:580: unreported exception java.lang.Throwable; must be caught or declared to be thrown
                                  IFC_RelVoidsElement_Query.query_void_ids(ifcdemo);
    ModelClipTest.java:582: unreported exception java.lang.Throwable; must be caught or declared to be thrown
                                  IFC_BuildingStorey_Query.query_buildingstorey(ifcdemo);

Maybe you are looking for

  • Trouble displaying JSP document in IE

    I am having some trouble displaying a JSP version 2 document in IE (though everything works fine in Mozilla). All my jsp docs start off as follows: <jsp:root version="2.0"     xmlns:jsp="http://java.sun.com/JSP/Page"     xmlns:f="http://java.sun.com/

  • How to manage my database?

    Hello, I'm thinking about how to structureproducts in my database. I want to set it up as efficient as possible at the start so this will save me time in the future. How I'm thinking about setting it up: In my industrie (strollers) there are often ma

  • Best efficient general practice for serial communication

    hello, when talking to a serial instrument, do you have to insert millisecond waits in the while loop or will the reading and writing from the instrument generally control the loop speed of the loop?  On the basic read write example they feed in the

  • At line-selection and At-user command

    Hi friends, Can we use both those events at a time in report? If so can any body provide me sample code? Regards

  • Setting New Browser Window Size

    Hello out there - I have an HTML page with a flash peice containing nav buttons linking to a photo tour by location: http://www.snowolf-digital.com/clients/rysaw/map_test.html.. Anyway, I am trying to get a new browser window to open in a specific si