JCheckBox/Action Listener help

Hey
I'm trying to make an applet with two tabs, a PurchasePanel and a StorePanel, and have data altered in one of them affect the data in the other. On the StorePanel, the data is input infields and through a ButtonListener command it is stored as both a String in a text field on the StorePanel, and as a check box on the PurchasePanel. Now, from the PurchasePanel I need to make an ActionListener function that when the CheckBoxes are pressed, some data is added to another textfield, and when it is unchecked the data is removed. I'm not sure I implemented the actionlistener correctly as the buttonlistener and the actionlistener commands aren't recognizing variables from each other. Any help is appreciated.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.Container;
import java.text.*;
public class StorePanel extends JPanel
private ArrayList compList;
private PurchasePanel purchasePanel;
private JLabel brandName, price, memory, cpuType, cpuSpeed, info;
private JTextArea cpuInfo;
private JTextField BTL, PTL, MTL, TTL, STL;
private JPanel smallPanel, leftPanel, rightPanel, wholePanel;
private JScrollPane scrollBox;
public int counter = 0;
public StorePanel(ArrayList compList, PurchasePanel pPanel)
this.compList = compList;
this.purchasePanel = pPanel;
brandName = new JLabel("Brand Name ");
price = new JLabel("Price");
memory = new JLabel("Memory");
cpuType = new JLabel("CPU Type");
cpuSpeed = new JLabel("CPU Speed");
BTL = new JTextField();
PTL = new JTextField();
MTL = new JTextField();
TTL = new JTextField();
STL = new JTextField();
JPanel smallPanel = new JPanel();
smallPanel.setLayout(new GridLayout(5,2));
smallPanel.add(brandName);
smallPanel.add(BTL);
smallPanel.add(price);
smallPanel.add(PTL);
smallPanel.add(memory);
smallPanel.add(MTL);
smallPanel.add(cpuType);
smallPanel.add(TTL);
smallPanel.add(cpuSpeed);
smallPanel.add(STL);
// organize components here
// here is an example
JButton button1 = new JButton("Store");
button1.setSize(1,1);
button1.addActionListener(new ButtonListener());
info = new JLabel("INFORMATION", SwingConstants.CENTER);
leftPanel = new JPanel();
leftPanel.setLayout(new BorderLayout());
leftPanel.add(info,BorderLayout.NORTH);
leftPanel.add(smallPanel,BorderLayout.CENTER);
leftPanel.add(button1,BorderLayout.SOUTH);
cpuInfo = new JTextArea("No Computer",19,27);
scrollBox = new JScrollPane(cpuInfo);
rightPanel = new JPanel();
rightPanel.add(scrollBox);
wholePanel = new JPanel();
wholePanel.setLayout(new BorderLayout());
wholePanel.add(leftPanel,BorderLayout.WEST);
wholePanel.add(rightPanel,BorderLayout.EAST);
this.add(wholePanel);
private class ButtonListener implements ActionListener
     public void actionPerformed(ActionEvent event)
          String BN = BTL.getText();
          String P = PTL.getText();
          String M = MTL.getText();
          String CT = TTL.getText();
          String CS = STL.getText();
          String error = "";
          String enter = "";
          String computerString = "";
          int speed = 0;
          int memory = 0;
          double price = 0;
          String status = "Yes";
          String bPrice = "";
          JCheckBox computer;
          try
               speed = Integer.parseInt(CS);
               memory = Integer.parseInt(M);
               price = Double.parseDouble(P);
          catch (NumberFormatException exception)
               info.setText("Enter a number for Price, Memory, or Speed.");
               info.setForeground(Color.red);
               status = "No";
          if(BN.length() == 0 || P.length() == 0 || M.length() == 0 || CT.length() == 0 || CS.length() == 0)
               error = "Please Enter All Fields.";
               status = "Empty";
          if(status == "Yes" || status == "Empty")
          if(error == "Please Enter All Fields.")
               info.setText(error);
               info.setForeground(Color.red);
          else
               DecimalFormat myFormatter = new DecimalFormat("0,000.00");
               bPrice = myFormatter.format(price);
               if(counter == 0)
                    cpuInfo.replaceRange("",0,11);
               enter = "\nBrandName:\t\t" + BN + "\nCPU:\t\t" + CT + "," + speed
                              + "HZ\nMemory:\t\t" + memory + "M\nprice:\t\t$" + bPrice + "\n";
               info.setText("Computer Added.");
               info.setForeground(Color.red);
               cpuInfo.append(enter);
               counter ++;
               computer = new JCheckBox("BrandName:"+BN+"CPU:"+CT+","+speed+"HZMemory:"+memory+"Mprice:$"+bPrice);
               computer.addItemListener(new PurchasePanel.CheckBoxListener());
               purchasePanel.leftPane.add(computer);
               compList.add(computer);
public class PurchasePanel extends JPanel
private ArrayList compList;
private JLabel CTP, Filler;
private JTextArea totalPrice;
protected JPanel rightPane, leftPane;
protected JSplitPane wholePane;
private JScrollPane scrollPane;
private JCheckBox checked;
private double TP = 0.00;
public PurchasePanel(ArrayList compList)
     this.compList = compList;
     // organize components for purchase panel
     CTP = new JLabel("Current Total Purchase");
     Filler = new JLabel(" ");
totalPrice = new JTextArea("$" + TP,18,22);
scrollPane = new JScrollPane(totalPrice);
     rightPane = new JPanel();
     rightPane.setLayout(new BorderLayout());
rightPane.add(CTP, BorderLayout.CENTER);
     rightPane.add(scrollPane, BorderLayout.SOUTH);
     leftPane = new JPanel();
     leftPane.setLayout(new BoxLayout(leftPane, BoxLayout.Y_AXIS));
     leftPane.setSize(800,700);
     leftPane.add(Filler);
     wholePane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPane, rightPane);
     this.add(wholePane);
private class CheckBoxListener implements ItemListener
     public void itemStateChanged(ItemEvent event)
               if(StorePanel.ButtonListener.computer.getStateChange() == ItemEvent.SELECTED)
                    TP = TP + 10.05;
public class Assignment6 extends JApplet
private int APPLET_WIDTH = 650, APPLET_HEIGHT = 350;
private JTabbedPane tPane;
private StorePanel storePanel;
private PurchasePanel purchasePanel;
private ArrayList computerList;
//The method init initializes the Applet with a Pane with two tabs
public void init()
     //list of computers to be used in every panel
     computerList = new ArrayList();
     //customer purchase panel uses the list of computers
     purchasePanel = new PurchasePanel(computerList);
     //store inventory panel uses the list of computers and also
     //established a connection with purchasePanel
storePanel = new StorePanel(computerList, purchasePanel);
//create a tabbed pane with two tabs
tPane = new JTabbedPane();
tPane.addTab("Store Inventory", storePanel);
tPane.addTab("Customer Purchase", purchasePanel);
getContentPane().add(tPane);
setSize (APPLET_WIDTH, APPLET_HEIGHT); //set Applet size
}

If you pass along references to the appropriate panel to the Listeners, then they can update the right thing accordingly eg.
// To enable the StorePanel to add/erase data from a textfield by listening to a checkbox in the PurchasePanel class
// PurchasePanel class
checked.addItemListener(new CheckBoxListener(storePanel));
// CheckBoxListener class
public void itemStateChanged(ItemEvent e) {
    // When checkbox checked
    if(checked)
        storePanel.writeToTextField("blahblah");
    else
        storePanel.writeToTextField("");
}That was pseudocode of course! If you need the PurchasePanel to listen to the button in the StorePanel, you need to do the reverse.

Similar Messages

  • I need a code example for an action listener for a jcheckbox using matisse

    I am trying to make it so that when some body clicks a jcheckbox it will put a figure into a jtextfield. Because I am using matisse I need to know the code for the action listener and I need to know quickly as well so I don't have time to look it up with searches etc.
    Can anbody provide me with some example code please.

    I thought that as you are all more experienced than I am that you would know where to look and as you would have already been to all of the sites you would have been able to save me a lot of time looking for the best one. I didn't mean to insult you sorry, I knew that I would be looking for a long time and hoped that some one could help speed that up for me.
    Any way I have obviously annoyed you in that thread earlier this week. I know that you are all pee'd at me and don't believe me and that is fine. I have learnt every thing that I need to learn and would like to thank you for your help although I think that your language in your last post was not very pleasant, but that is ok.
    I don't want to continue posting any more. But thank you for your help.

  • Transaction Posting Confirmation Message and Action Listener behaviour

    Hi, I have a scenario that a user is Posting a Transaction and when he press the “Post” Button a, confirmation dialog box should popup asking “Do you really want to Post the record ?”. If the user press “Yes” the record is further process and If the user press “No” then the transaction should not proceed.
    I have implemented the main screen(PostTransaction.java) and the popup confirmation window(ConfirmationWindow.java)
    Question 1 ) Why the code is not stoping in the Post Button Action listener as in JOptionPane, then how do i know that the user has selected "Yes" or "No" ?
    Question 2) Do I have to write the code for posting of a Transaction(postTransaction() method) in the “ConfirmationWindow”? or it should be in “PostTransaction”.
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.application.Application;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.Label;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.GridPane;
    import javafx.stage.Stage;
    public class PostTransaction extends Application{
           public void start(final Stage stage) throws Exception {
                  Group root = new Group();
                  Scene scene = new Scene(root, 300,300);
                  stage.setScene(scene);
                  stage.setTitle("Transaction Post Screen");
                  GridPane gp = new GridPane();
                  Label lblName = new Label("Name");
                  Label lblAmount = new Label("Amount");
                  TextField txtName = new TextField();
                  TextField txtAmount = new TextField();
                  Button btnPost = new Button("Post Record");
                  gp.add(lblName, 1, 1);
                  gp.add(lblAmount, 1, 2);
                  gp.add(txtName, 2, 1);
                  gp.add(txtAmount, 2, 2);
                  gp.add(btnPost, 2, 3);
                  btnPost.setOnAction(new EventHandler<ActionEvent>() {
                        @Override
                        public void handle(ActionEvent arg0) {
                             //The code does not stop here as in JOptionPane, then how do i know that the user has selected "Yes" or "No" ??
                             boolean popupResult = ConfirmationWindow.confirmTranactionPosting(stage, "Please Confirm");
                             if(popupResult==true){
                                  //This line is printed before the user selects yes or no
                                  System.out.println("Proceeding with Tranaction Posting");
                                  //postTransaction();
                             if(popupResult==false){
                                  //This line is printed before the user selects yes or no
                                  System.out.println("Do not Proceed with Tranaction Posting");
                 root.getChildren().add(gp);
                stage.show();
                public static void main(String[] args) {
                  launch(args);
              private void postTransaction(){
                   //write the code for posting here
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.Label;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.layout.HBox;
    import javafx.stage.Modality;
    import javafx.stage.Stage;
    import javafx.stage.StageStyle;
    public class ConfirmationWindow extends Stage {
         Stage owner;
         Stage stage;
         BorderPane root;
         static boolean postStatus = false;
      public ConfirmationWindow( Stage owner, String title){
        root = new BorderPane();
        stage = this;
        this.owner = owner;
        initModality( Modality.APPLICATION_MODAL );
        initOwner( owner );
        initStyle( StageStyle.UTILITY );
        setTitle( title );
        setContents();
      public void setContents(){
        Scene scene = new Scene(root,250,150);
        setScene(scene);
        Group groupInDialog = new Group();
        groupInDialog.getChildren().add( new Label("Do you really want to Post this record ?") );
        root.setCenter( groupInDialog );
        Button yes = new Button( "Yes" );
        yes.setOnAction(new EventHandler<ActionEvent>() {
              @Override
              public void handle(ActionEvent e) {
                   postStatus =true;
                   stage.close(); // Close the pop up. Transfer control to PostTransaction.java and execute the PostTransaction() method.
        Button no  = new Button( "No" );
        no.setOnAction(new EventHandler<ActionEvent>() {
              @Override
              public void handle(ActionEvent e) {
                   postStatus =false;
                   stage.close(); // Close the pop up only
        HBox buttonPane = new HBox();
        buttonPane.setSpacing(10);
        buttonPane.getChildren().addAll(yes,no);
        root.setBottom(buttonPane);
        stage.show();
      public static boolean confirmTranactionPosting(Stage owner, String title) {
           new ConfirmationWindow(owner, title);
           return postStatus;
    }

    The MII Message listener is a queue. But when I understand you correctly, you do not want to process the messages immediately after arriving in the Listener.
    Maybe the categorization of messages is an option for you (see [Sap Help: Processing Rule Editor - Category|http://help.sap.com/saphelp_mii121/helpdata/en/43/e80b59ad40719ae10000000a1553f6/frameset.htm]. You can enter a category for the control recipe messages. The messages will then be placed in the Listener queue. You can use the [Message Services|http://help.sap.com/saphelp_mii121/helpdata/en/43/e80b59ad40719ae10000000a1553f6/frameset.htm] actions to read the categorized messages and process them as you need.
    In addition to Manoj, you may also use the [Queueing actions|http://help.sap.com/saphelp_mii121/helpdata/en/43/e80b59ad40719ae10000000a1553f6/frameset.htm] of MII, where you can queue xml contents.
    Hope this helps.
    Michael

  • Calling action listener for a BUTTON component in java bean page

    Hi,
    I have made it like this.
    public void handleButtonPressed(ActionEvent event){
    System.out.println("success!!!!!");
    //code for calling actionlistener
    FacesContext fctx = FacesContext.getCurrentInstance();
    ELContext elctx = fctx.getELContext();
    Application application = fctx.getApplication();
    ExpressionFactory exprFactory = application.getExpressionFactory();
    MethodExpression methodExpr = null;
    methodExpr = exprFactory.createMethodExpression(elctx, "#{exbean.handleButtonPressed}",null,new Class[] { ActionEvent.class });
    MethodExpressionActionListener actionListener = null;
    actionListener = new MethodExpressionActionListener(methodExpr);
    button.addActionListener(actionListener);
    Even after making the listener Function as Void wHen i click the button i m getting the error saying."ARGUMENTS MISMATCH,ADF_FACES60097"??
    can you help me out?
    and in the msg log i m getting this
    "SkinFactoryImpl> <getSkin> Cannot find a skin that matches family portal and version v1.1. We will use the skin portal.desktop.
    <MethodExpressionActionListener> <processAction> Received 'javax.el.PropertyNotFoundException' when invoking action listener '#{exbean.handleButtonPressed}' for component 'null'
    <MethodExpressionActionListener> <processAction> javax.el.PropertyNotFoundException: Target Unreachable, identifier 'custombean' resolved to null"
    I Have tried with this giving Void TYPE as an argument
    methodExpr = exprFactory.createMethodExpression(elctx, "#{exbean.handleButtonPressed},Void.TYPE,new Class[] { ActionEvent.class });
    I M getting the same error.
    Edited by: chaya on Dec 22, 2011 2:47 PM

    yeah but i m creating button itself dynamically by java code....
    //code
    UIComponent button;
    button = findComponentInRoot("cb1");
    RichPanelGroupLayout pgl;
    pgl = (RichPanelGroupLayout)button.getParent();
    List<UIComponent> children;
    children = pgl.getChildren();
    RichPanelGroupLayout pgll;
    pgll = new RichPanelGroupLayout();
    RichInputText it;
    it = new RichInputText();
    it.setLabel("New textbox " + (children.size()));
    RichCommandButton but = new RichCommandButton();
    but.setPartialSubmit(true);
    but.setText("Delete");
    /*calling actionevent*/
    FacesContext fctx = FacesContext.getCurrentInstance();
    ELContext elctx = fctx.getELContext();
    Application application = fctx.getApplication();
    ExpressionFactory exprFactory = application.getExpressionFactory();
    MethodExpression methodExpr = null;
    methodExpr = exprFactory.createMethodExpression( elctx,"#{inbean.actionPerformed}",null, new Class[] {ActionEvent.class});
    MethodExpressionActionListener actionListener = null;
    actionListener = new MethodExpressionActionListener(methodExpr);
    but.addActionListener(actionListener);
    /*end of call*/
    children.add(pgll);
    children.add(it);
    children.add(but);
    AdfFacesContext.getCurrentInstance().addPartialTarget(pgl);
    //code to call method
    public void actionPerformed(ActionEvent event) {
    System.out.println("entered sec bean");
    return " ";}
    this way i m trying to create a button programatically and tryin to add actionlistener which is not working.
    the actionlistener is throwing error.... with the line
    methodExpr = exprFactory.createMethodExpression( elctx,"#{inbean.actionPerformed}",null, new Class[] {ActionEvent.class});

  • Problem with action listener

    hello
    the problem in my code is that i defined
    actionlistener for a button but it does not
    do what it should do . it throws an error in the console
    and i think my code is 100% correct what is the problem
    please help me this is the codewith
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    class Library extends JFrame implements ActionListener     {
         private JMenuBar jmb      = new JMenuBar();
         private JMenu books      = new JMenu("Books",true);
         private JMenu members      = new JMenu("Members",true);
         private JMenu loans      = new JMenu("Loans",true);
         private JMenuItem addNb = new JMenuItem("Add New Book");
         private JMenuItem listB = new JMenuItem("List All Books");
         private JMenuItem listAb = new JMenuItem("List Available Books");
         private JMenuItem listBb = new JMenuItem("List Borrowed Books");
         private JMenuItem addNm = new JMenuItem("Add New Member");
         private JMenuItem removeM = new JMenuItem("Remove a Member");
         private JMenuItem listAm = new JMenuItem("List All Members");
         private JMenuItem loanB = new JMenuItem("Loan A Book");
         private JMenuItem returnB = new JMenuItem("Return A Book");
         private JTextField bNumber = new JTextField(14);
         private JTextField bAuthor = new JTextField(14);
         private JTextField bTitle = new JTextField(14);
         private JTextField mId = new JTextField(14);
         private JTextField mName = new JTextField(14);
         private JTextField idB = new JTextField(14);
         private JTextField nBToB = new JTextField(14);
         private JTextField nBTor = new JTextField(14);
         private JTextArea dispaly = new JTextArea();
         private JButton oKb1 = new JButton("OK");
         private JButton okb2 = new JButton("OK");
         private JButton cloaseb = new JButton("Close");
         private JButton oKm1 = new JButton("OK");
         private JButton oKm2 = new JButton("OK");
         private JButton cancelM = new JButton("Cancel");
         private JButton oKm3 = new JButton("OK");
         private JButton oKm4 = new JButton("OK");
         private JButton cancelM2 = new JButton("Cancel");
         private JButton oKl = new JButton("OK");
         private JButton oKr = new JButton("OK");
         private JButton yes = new JButton("Yes");
         private JButton no = new JButton("No");     
         private JLabel bN = new JLabel("Book Number");
         private JLabel bA = new JLabel("Book Author");
         private JLabel bT = new JLabel("Book Title");
         private JLabel iN          = new JLabel("ID Number");
         private JLabel mN          = new JLabel("Member's Name");
         private JLabel     iNb          = new JLabel("ID number of the borrower");
         private JLabel nBb          = new JLabel("Number of the books to borrow");
         private JLabel nBr          = new JLabel("Number of the books to return");
         private JLabel mIdl     = new JLabel("ID number of the stuednt");
         private JPanel tempoIPanel= new JPanel(new FlowLayout());
         Container cp;
         JFrame mainFrame;
         JInternalFrame tempoI;
    Library()     {
         //LibraryClass lClass = new LibraryClass();/*
         mainFrame = new JFrame();
         mainFrame.setJMenuBar(jmb);
         mainFrame.setSize(800,550);
         mainFrame.getContentPane().setLayout(new FlowLayout());
         jmb.add(books);
         jmb.add(members);
         jmb.add(loans);
         books.add(addNb);
         addNb.addActionListener(this);
         books.add(listB);
         listB.addActionListener(this);
         books.add(listAb);
         listAb.addActionListener(this);
         books.add(listBb);
         listBb.addActionListener(this);
         members.add(addNm);
         addNm.addActionListener(this);
         members.add(removeM);
         removeM.addActionListener(this);
         members.add(listAm);
         listAm.addActionListener(this);
         loans.add(loanB);
         loanB.addActionListener(this);
         loans.add(returnB);
         returnB.addActionListener(this);
         //actions listeners
         oKb1.addActionListener(this);
         mainFrame.setVisible(true);
    public void actionPerformed(ActionEvent ae)     {
         if(ae.getSource() == addNb)     {
              tempoI = new JInternalFrame("Add new Book",true,true);
              mainFrame.getContentPane().add(tempoI);
              tempoI.getContentPane().setLayout(new FlowLayout());
              tempoI.getContentPane().add(bN);
              tempoI.getContentPane().add(bNumber);
              tempoI.getContentPane().add(bA);
              tempoI.getContentPane().add(bAuthor);
              tempoI.getContentPane().add(bT);
              tempoI.getContentPane().add(bTitle);
              tempoI.getContentPane().add(oKb1);//add action listener here
              tempoI.setVisible(true);
         if(ae.getSource() == listB)     {
              //LibraryClass.listBooks();
         if(ae.getSource() == listAb){}
         if(ae.getSource() == listBb){}
         if(ae.getSource() == addNm)     {
              tempoI = new JInternalFrame("Add new Member",true,true);
              mainFrame.getContentPane().add(tempoI);
              tempoI.getContentPane().setLayout(new FlowLayout());
              tempoI.getContentPane().add(iN);
              tempoI.getContentPane().add(mId);
              tempoI.getContentPane().add(mN);
              tempoI.getContentPane().add(mName);
              tempoI.getContentPane().add(oKm1);//add action listener
              tempoI.getContentPane().setSize(300,400);
              tempoI.setVisible(true);
         if(ae.getSource() == removeM)     {
              tempoI = new JInternalFrame("Rmove member",true,true);
              mainFrame.getContentPane().add(tempoI);
              tempoI.getContentPane().setLayout(new FlowLayout());
              tempoI.getContentPane().add(mIdl);
              tempoI.getContentPane().add(mId);
              tempoI.getContentPane().add(oKm2);//add action listener
              //LibraryClass.removeM(Double.parseDouble(mId.getText()));
              tempoI.getContentPane().setSize(300,400);
              tempoI.setVisible(true);
         if(ae.getSource() == listAm)     {
              //LibraryClass.listMembers();
         if(ae.getSource() == loanB)     {
              tempoI = new JInternalFrame("Loan book",true,true);
              mainFrame.getContentPane().add(tempoI);
              tempoI.getContentPane().setLayout(new FlowLayout());
              tempoI.getContentPane().add(iNb);
              tempoI.getContentPane().add(idB);
              tempoI.getContentPane().add(nBb);
              tempoI.getContentPane().add(nBToB);
              tempoI.getContentPane().add(oKl);
              //LibraryClass.borrowBook(Book bk,Member m);
              tempoI.getContentPane().setSize(300,400);
              tempoI.setVisible(true);
         if(ae.getSource() == returnB)     {
              tempoI = new JInternalFrame("Return Book",true,true);
              mainFrame.getContentPane().add(tempoI);
              tempoI.getContentPane().setLayout(new FlowLayout());
              tempoI.getContentPane().add(iNb);
              tempoI.getContentPane().add(idB);
              tempoI.getContentPane().add(nBr);
              tempoI.getContentPane().add(nBTor);
              tempoI.getContentPane().add(oKr);
              tempoI.getContentPane().setSize(400,300);
              tempoI.setVisible(true);
              //Book.addBook(bNumber.getText(),bAuthor.getText(),bTitle.getText());
    class ClubLibrarySystem     {
         public static void main(String[] args)     {
         new Library();
    }

    hello
    the problem in my code is that i defined
    actionlistener for a button but it does not
    do what it should do . it throws an error in the
    consoleWhat error?
    and i think my code is 100% correct what is theWell, but it isn't.
    Have you tried using a debugger?
    problem
    please help me this is the codewith
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    class Library extends JFrame implements
    ActionListener     {
         private JMenuBar jmb      = new JMenuBar();
         private JMenu books      = new JMenu("Books",true);
    private JMenu members      = new
    JMenu("Members",true);
    private JMenu loans      = new
    JMenu("Loans",true);
    private JMenuItem addNb = new JMenuItem("Add New
    Book");
    private JMenuItem listB = new JMenuItem("List All
    Books");
    private JMenuItem listAb = new JMenuItem("List
    Available Books");
    private JMenuItem listBb = new JMenuItem("List
    Borrowed Books");
    private JMenuItem addNm = new JMenuItem("Add New
    Member");
    private JMenuItem removeM = new JMenuItem("Remove a
    Member");
    private JMenuItem listAm = new JMenuItem("List All
    Members");
    private JMenuItem loanB = new JMenuItem("Loan A
    Book");
    private JMenuItem returnB = new JMenuItem("Return A
    Book");
         private JTextField bNumber = new JTextField(14);
         private JTextField bAuthor = new JTextField(14);
         private JTextField bTitle = new JTextField(14);
         private JTextField mId = new JTextField(14);
         private JTextField mName = new JTextField(14);
         private JTextField idB = new JTextField(14);
         private JTextField nBToB = new JTextField(14);
         private JTextField nBTor = new JTextField(14);
         private JTextArea dispaly = new JTextArea();
         private JButton oKb1 = new JButton("OK");
         private JButton okb2 = new JButton("OK");
         private JButton cloaseb = new JButton("Close");
         private JButton oKm1 = new JButton("OK");
         private JButton oKm2 = new JButton("OK");
         private JButton cancelM = new JButton("Cancel");
         private JButton oKm3 = new JButton("OK");
         private JButton oKm4 = new JButton("OK");
         private JButton cancelM2 = new JButton("Cancel");
         private JButton oKl = new JButton("OK");
         private JButton oKr = new JButton("OK");
         private JButton yes = new JButton("Yes");
         private JButton no = new JButton("No");     
    private JLabel bN = new JLabel("Book
    Number");
    private JLabel bA = new JLabel("Book
    Author");
    private JLabel bT = new JLabel("Book
    Title");
         private JLabel iN          = new JLabel("ID Number");
    private JLabel mN          = new JLabel("Member's
    Name");
    private JLabel     iNb          = new JLabel("ID number of the
    borrower");
    private JLabel nBb          = new JLabel("Number of the
    books to borrow");
    private JLabel nBr          = new JLabel("Number of the
    books to return");
    private JLabel mIdl     = new JLabel("ID number of
    the stuednt");
    private JPanel tempoIPanel= new JPanel(new
    FlowLayout());
         Container cp;
         JFrame mainFrame;
         JInternalFrame tempoI;
    Library()     {
         //LibraryClass lClass = new LibraryClass();/*
         mainFrame = new JFrame();
         mainFrame.setJMenuBar(jmb);
         mainFrame.setSize(800,550);
    mainFrame.getContentPane().setLayout(new
    FlowLayout());
         jmb.add(books);
         jmb.add(members);
         jmb.add(loans);
         books.add(addNb);
         addNb.addActionListener(this);
         books.add(listB);
         listB.addActionListener(this);
         books.add(listAb);
         listAb.addActionListener(this);
         books.add(listBb);
         listBb.addActionListener(this);
         members.add(addNm);
         addNm.addActionListener(this);
         members.add(removeM);
         removeM.addActionListener(this);
         members.add(listAm);
         listAm.addActionListener(this);
         loans.add(loanB);
         loanB.addActionListener(this);
         loans.add(returnB);
         returnB.addActionListener(this);
         //actions listeners
         oKb1.addActionListener(this);
         mainFrame.setVisible(true);
    public void actionPerformed(ActionEvent ae)     {
         if(ae.getSource() == addNb)     {
    tempoI = new JInternalFrame("Add new
    w Book",true,true);
              mainFrame.getContentPane().add(tempoI);
    tempoI.getContentPane().setLayout(new
    w FlowLayout());
              tempoI.getContentPane().add(bN);
              tempoI.getContentPane().add(bNumber);
              tempoI.getContentPane().add(bA);
              tempoI.getContentPane().add(bAuthor);
              tempoI.getContentPane().add(bT);
              tempoI.getContentPane().add(bTitle);
    tempoI.getContentPane().add(oKb1);//add action
    n listener here
              tempoI.setVisible(true);
         if(ae.getSource() == listB)     {
              //LibraryClass.listBooks();
         if(ae.getSource() == listAb){}
         if(ae.getSource() == listBb){}
         if(ae.getSource() == addNm)     {
    tempoI = new JInternalFrame("Add new
    w Member",true,true);
              mainFrame.getContentPane().add(tempoI);
    tempoI.getContentPane().setLayout(new
    w FlowLayout());
              tempoI.getContentPane().add(iN);
              tempoI.getContentPane().add(mId);
              tempoI.getContentPane().add(mN);
              tempoI.getContentPane().add(mName);
    tempoI.getContentPane().add(oKm1);//add action
    n listener
              tempoI.getContentPane().setSize(300,400);
              tempoI.setVisible(true);
         if(ae.getSource() == removeM)     {
    tempoI = new JInternalFrame("Rmove
    e member",true,true);
              mainFrame.getContentPane().add(tempoI);
    tempoI.getContentPane().setLayout(new
    w FlowLayout());
              tempoI.getContentPane().add(mIdl);
              tempoI.getContentPane().add(mId);
    tempoI.getContentPane().add(oKm2);//add action
    n listener
              //LibraryClass.removeM(Double.parseDouble(mId.getText
              tempoI.getContentPane().setSize(300,400);
              tempoI.setVisible(true);
         if(ae.getSource() == listAm)     {
              //LibraryClass.listMembers();
         if(ae.getSource() == loanB)     {
              tempoI = new JInternalFrame("Loan book",true,true);
              mainFrame.getContentPane().add(tempoI);
    tempoI.getContentPane().setLayout(new
    w FlowLayout());
              tempoI.getContentPane().add(iNb);
              tempoI.getContentPane().add(idB);
              tempoI.getContentPane().add(nBb);
              tempoI.getContentPane().add(nBToB);
              tempoI.getContentPane().add(oKl);
              //LibraryClass.borrowBook(Book bk,Member m);
              tempoI.getContentPane().setSize(300,400);
              tempoI.setVisible(true);
         if(ae.getSource() == returnB)     {
    tempoI = new JInternalFrame("Return
    n Book",true,true);
              mainFrame.getContentPane().add(tempoI);
    tempoI.getContentPane().setLayout(new
    w FlowLayout());
              tempoI.getContentPane().add(iNb);
              tempoI.getContentPane().add(idB);
              tempoI.getContentPane().add(nBr);
              tempoI.getContentPane().add(nBTor);
              tempoI.getContentPane().add(oKr);
              tempoI.getContentPane().setSize(400,300);
              tempoI.setVisible(true);
              //Book.addBook(bNumber.getText(),bAuthor.getText(),bT
    tle.getText());
    class ClubLibrarySystem     {
         public static void main(String[] args)     {
         new Library();

  • Calling Action listener in Custom component

    Hello,
    I am currently developing my own component containing an hyper-link and I am stuck with the Renderer. What should I put in the href of my "a" tag (<a href="???">) in order to call an Action listener ? I would like my renderer to do something similar to <h:commandLink actionListener="#{myBean.myActionListener}".
    Could you help me?
    Gerald.</a>

    Hello,
    Did you achieve this??? I'm also planing to put very similar to your thought. If you have a solution on your requirement, pls mail me to [email protected]
    Thanks in Advance.
    regards,
    Ram

  • How to create a single action listener for a group of buttons

    hi there.. i am new at java and i have a problem with my applet..
    i am doing a virtual ticket programme..
    i have a tab that says books seats.. in the tab, i am suppose to create 50 buttons.
    i have done that already by using for (int i=1; i<=10;i++) 5 times for 50 buttons.
    but i do not know how to set an actionlistener in the for loop for each of these buttons..
    For example, if the user were to chose seat "no3" , a text area(already created) below will show something like "no3" and so on..
    how do i bind these buttons into one single action listener so i do not have to create 50 actionlisteners and buttons individually..
    appreciate the help..

    You're killing me.
    class MyFrame extends JFrame implements ActionListener
         JTextArea myTextArea = new JTextArea();
         JButton myButton = new JButton("My Button");
         JButton otherButton = new JButton("Other Button");
         MyFrame()
              super();
              myButton.addActionListener(this);
              otherButton.addActionListener(this);
              setLayout(new FlowLayout());
              add(myButton);
              add(otherButton);
              add(myTextArea);
         public void actionPerformed(ActionEvent e)
              Object source = e.getSource();
              if(source == myButton)
                   myTextArea.append("My Button Pressed\n");
              else if(source == otherButton)
                   myTextArea.append("Other Button Pressed\n");
    }

  • Custom button with action listener - will not invoke action listener

    Hi
    For whatever reason, I cannot find a concise example of a simple custom component that can invoke an action listener. The tutorials I've read so far either ignore this fundamental topic or only make the slightest make reference to it.
    The best I have come up with - in terms of a simple prototype is below... but, the action listener is never invoked.... Can someone tell me what I am missing (full code below). Hopefully, what is missing or incorrect will be obvious to you JSF experts out there.
    Thanks for any help!!
    -f
    tld
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
    <taglib>
      <tlib-version>0.01</tlib-version>
      <jsp-version>1.2</jsp-version>
      <short-name>jsfcustomcomponent</short-name>
      <uri>http://jsfcustomcomponent/</uri>
      <description><![CDATA[jsf custom component tags]]>  </description>
      <tag>
        <name>specialBtnTag</name>
        <tag-class>jsfcustomcomponent.SpecialBtnTag</tag-class>
        <attribute>
          <name>value</name>
          <required>true</required>
          <rtexprvalue>true</rtexprvalue>
          <description><![CDATA[button value]]></description>
        </attribute>
        <attribute>
          <name>actionListener</name>
          <required>true</required>
          <rtexprvalue>true</rtexprvalue>
          <description><![CDATA[action listener]]> </description>
        </attribute>
      </tag>
    </taglib>
    SpecialBtnComponent
    package jsfcustomcomponent;
    import javax.faces.component.*;
    import javax.faces.context.*;
    import javax.faces.el.*;
    import javax.faces.event.*;
    public class SpecialBtnComponent
        extends UIComponentBase implements ActionSource
        public static final String COMPONENT_TYPE = "SpecialBtnComponent";
        public static final String RENDERER_TYPE = "SpecialBtnRenderer";
        public String getFamily()
            return COMPONENT_TYPE;
        public SpecialBtnComponent()
            super();
            setRendererType(SpecialBtnComponent.RENDERER_TYPE);
        private String value;
        public void setValue(String value, FacesContext facesContext)
            this.value = value;
        public String getValue()
            if (null != value)
                return value;
            ValueBinding _vb = getValueBinding("value");
            if (_vb != null)
                return (String) _vb.getValue(getFacesContext());
            else
                return null;
        private MethodBinding action = null;
        public MethodBinding getAction()
            return action;
        public void setAction(MethodBinding methodBinding)
            this.action = action;
        private MethodBinding actionListener = null;
        public MethodBinding getActionListener()
            return (this.actionListener);
        public void setActionListener(MethodBinding methodBinding)
            this.actionListener = actionListener;
        public boolean isImmediate()
            return false;
        public void setImmediate(boolean _boolean)
            //this.immediate = immediate;
        public void addActionListener(ActionListener actionListener)
            addFacesListener(actionListener);
        public ActionListener[] getActionListeners()
            return (ActionListener[]) getFacesListeners(ActionListener.class);
        public void removeActionListener(ActionListener actionListener)
            removeFacesListener(actionListener);
        public Object saveState(FacesContext context)
            Object values[] = new Object[5];
            values[0] = super.saveState(context);
            values[1] = value;
            values[2] = saveAttachedState(context, action);
            values[3] = saveAttachedState(context, actionListener);
            return ( (Object) (values));
        public void restoreState(FacesContext context, Object state)
            Object values[] = (Object[]) state;
            super.restoreState(context, values[0]);
            value = (String) values[1];
            action = (MethodBinding) restoreAttachedState(context, values[2]);
            actionListener = (MethodBinding) restoreAttachedState(context, values[3]);
        public void broadcast(FacesEvent event) throws AbortProcessingException
            super.broadcast(event);
            if (event instanceof ActionEvent)
                FacesContext context = getFacesContext();
                MethodBinding mb = getActionListener();
                if (mb != null)
                    mb.invoke(context, new Object[]
                              {event});
                ActionListener listener = context.getApplication().getActionListener();
                if (listener != null)
                    listener.processAction( (ActionEvent) event);
        public void queueEvent(FacesEvent e)
            if (e instanceof ActionEvent)
                if (isImmediate())
                    e.setPhaseId(PhaseId.APPLY_REQUEST_VALUES);
                else
                    e.setPhaseId(PhaseId.INVOKE_APPLICATION);
            super.queueEvent(e);
    SpecialBtnRenderer
    package jsfcustomcomponent;
    import java.util.*;
    import javax.faces.component.*;
    import javax.faces.context.*;
    import javax.faces.event.*;
    import javax.faces.render.*;
    public class SpecialBtnRenderer
        extends Renderer
        String value;
        public SpecialBtnRenderer()
        public void decode(FacesContext context, UIComponent component)
            Map requestMap = context.getExternalContext().getRequestParameterMap();
            String clientId = component.getClientId(context);
            SpecialBtnComponent specialBtnComponent = (SpecialBtnComponent) component;
            String value = (String) requestMap.get(clientId);
            if (null != value)
                specialBtnComponent.setValue(value, context);
            ActionEvent actionEvent = new ActionEvent(specialBtnComponent);
            specialBtnComponent.queueEvent(actionEvent);
        public void encodeEnd(FacesContext context, UIComponent component) throws java.io.IOException
            SpecialBtnComponent specialBtnComponent = (SpecialBtnComponent) component;
            ResponseWriter writer = context.getResponseWriter();
            String clientId = component.getClientId(context);
            value = (String) component.getAttributes().get("value");
            if (value == null)
                value = "defaultValue";
            buildSpecialBtn(writer, value, clientId, specialBtnComponent);
        private void buildSpecialBtn(ResponseWriter writer, String value, String clientId, SpecialBtnComponent component) throws java.io.IOException
            writer.startElement("table", component);
            writer.startElement("tbody", component);
            writer.startElement("tr", component);
            writer.startElement("td", component);
            value = String.valueOf(value);
            writer.startElement("input", component);
            writer.writeAttribute("type", "submit", null);
            writer.writeAttribute("name", clientId, "clientId");
            writer.writeAttribute("value", value, null);
            writer.endElement("input");
            writer.endElement("td");
            writer.endElement("tr");
            writer.endElement("tbody");
            writer.endElement("table");
    SpecialBtnTag
    package jsfcustomcomponent;
    import javax.faces.component.*;
    import javax.faces.el.*;
    import javax.faces.webapp.*;
    import com.sun.faces.util.*;
    public class SpecialBtnTag
        extends UIComponentTag
        public String value = null;
        public String actionListener = null;
        public String getComponentType()
            return SpecialBtnComponent.COMPONENT_TYPE;
        public String getRendererType()
            return SpecialBtnComponent.RENDERER_TYPE;
        protected void setProperties(UIComponent component)
            super.setProperties(component);
            if (! (component instanceof SpecialBtnComponent))
                throw new IllegalStateException("Component " + component.toString() +
                                                " not expected type.  Expected: jsfcustomcomponent.SpecialBtnComponent.  Perhaps you�re missing a tag?");
            SpecialBtnComponent specialBtnComponent = (SpecialBtnComponent) component;
            if (value != null)
                if (isValueReference(value))
                    ValueBinding vb = Util.getValueBinding(value);
                    specialBtnComponent.setValueBinding("value", vb);
                else
                    throw new IllegalStateException("The value for �value� must be a ValueBinding.");
            if (actionListener != null)
                if (isValueReference(actionListener))
                    ValueBinding vb = Util.getValueBinding(actionListener);
                    specialBtnComponent.setValueBinding("actionListener", vb);
                else
                    throw new IllegalStateException("The value for �actionListener� must be a ValueBinding.");
        public void release()
            super.release();
            value = null;
            actionListener = null;
        public void setValue(String value)
            this.value = value;
        public String getValue()
            return this.value;
        public void setActionListener(String actionListener)
            this.actionListener = actionListener;
        public String getActionListener()
            return this.actionListener;
    jsp1.jsp
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
    <%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
    <%@taglib uri="http://jsfcustomcomponent/" prefix="j"%>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    <link rel="stylesheet" type="text/css" href="./stylesheet.css" title="Style">
    </head>
    <body>
    <f:view>
      <h:form id="form01">
        <h:outputText value="test special button with action listener"/>
        <j:specialBtnTag value="#{specialBtnBacking.specialBtnValue}" actionListener="#{specialBtnBacking.specialBtnActionListener}"/>
        <h:messages/>
        <h:outputText value="#{specialBtnBacking.outcome}"/>
      </h:form>
    </f:view>
    </body>
    </html>
    SpecialBtnBacking
    package specialbtn;
    import javax.faces.context.*;
    import javax.faces.event.*;
    public class SpecialBtnBacking
        private FacesContext context;
        public SpecialBtnBacking()
            this.setSpecialBtnValue("Special Button with action listener");
        private String specialBtnValue;
        public String getSpecialBtnValue()
            return this.specialBtnValue;
        public void setSpecialBtnValue(String specialBtnValue)
            this.specialBtnValue = specialBtnValue;
        private String outcome="actionlistener NOT invoked: click specialBtn above to test";
        public String getOutcome()
            return outcome;
        public void setOutcome(String outcome)
            this.outcome = outcome;
        public void specialBtnActionListener(ActionEvent evt)
            System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Jsp1Backing/specialBtnActionListener()!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            this.outcome="***action listener invoked!!!***";
    faces-config.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN" "http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
    <faces-config>
      <managed-bean>
        <managed-bean-name>specialBtnBacking</managed-bean-name>
        <managed-bean-class>specialbtn.SpecialBtnBacking</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
      </managed-bean>
      <component>
        <component-type>SpecialBtnComponent</component-type>
        <component-class>jsfcustomcomponent.SpecialBtnComponent</component-class>
        <component-extension>
          <renderer-type>SpecialBtnRenderer</renderer-type>
        </component-extension>
      </component>
      <render-kit>
        <renderer>
          <component-family>SpecialBtnComponent</component-family>
          <renderer-type>SpecialBtnRenderer</renderer-type>
          <renderer-class>jsfcustomcomponent.SpecialBtnRenderer</renderer-class>
        </renderer>
      </render-kit>
    </faces-config>
    web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
      <display-name>pagerWEB</display-name>
      <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.faces</url-pattern>
      </servlet-mapping>
      <jsp-config>
        <taglib>
          <taglib-uri>http://jsfcustomcomponent/</taglib-uri>
          <taglib-location>/WEB-INF/jsfcustomcomponent.tld</taglib-location>
        </taglib>
      </jsp-config>
      <servlet>
        <description>Added by JBuilder to compile JSPs with debug info</description>
        <servlet-name>debugjsp</servlet-name>
        <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
        <init-param>
          <param-name>classdebuginfo</param-name>
          <param-value>true</param-value>
        </init-param>
        <load-on-startup>3</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>debugjsp</servlet-name>
        <url-pattern>*.jsp</url-pattern>
      </servlet-mapping>
    </web-app>

    got it working....
    The changes were:
    in "SpecialBtnRenderer"...
    --new--
                        mb.invoke(context, new Object[1]);
    --old--
                        mb.invoke(context, new Object[0]);
    in "SpecialBtnTag"...
    --new--
    import javax.faces.event.ActionEvent;
    --new--
                    MethodBinding mb = FacesContext.getCurrentInstance().getApplication().createMethodBinding(specialBtnListener, new Class[]{ActionEvent.class});
    --old--
                    MethodBinding mb = FacesContext.getCurrentInstance().getApplication().createMethodBinding(specialBtnListener, null);
    -Below is the entire application, again -- for those (like myself) who need concrete examples...
    I hope this helps someone else! --f
    jsp1.jsp
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
    <%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
    <%@taglib uri="http://jsfcustomcomponent/" prefix="j"%>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    <link rel="stylesheet" type="text/css" href="./stylesheet.css" title="Style">
    </head>
    <body>
    <f:view>
        <h:messages/>
      <h:form id="form01">
        <h:outputText value="test special button with action listener"/>
        <j:specialBtnTag value="#{specialBtnBacking.specialBtnValue}" specialBtnListener="#{specialBtnBacking.specialBtnActionListener}"/>
        <h:outputText value="#{specialBtnBacking.outcome}"/>
      </h:form>
    </f:view>
    </body>
    </html>
    SpecialBtnBacking
    package specialbtn;
    import javax.faces.context.*;
    import javax.faces.event.*;
    public class SpecialBtnBacking
        private FacesContext context;
        public SpecialBtnBacking()
            this.setSpecialBtnValue("Special Button with action listener");
        private String specialBtnValue;
        public String getSpecialBtnValue()
            return this.specialBtnValue;
        public void setSpecialBtnValue(String specialBtnValue)
            this.specialBtnValue = specialBtnValue;
        private String outcome = "actionlistener NOT invoked: click specialBtn above to test";
        public String getOutcome()
            return outcome;
        public void setOutcome(String outcome)
            this.outcome = outcome;
        public void specialBtnActionListener(ActionEvent evt)
            System.out.println("\n\n");
            System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Jsp1Backing/specialBtnActionListener()!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Jsp1Backing/specialBtnActionListener()!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Jsp1Backing/specialBtnActionListener()!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Jsp1Backing/specialBtnActionListener()!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Jsp1Backing/specialBtnActionListener()!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n");
            this.outcome = "***action listener invoked!!!***";
    jsfcustomcomponent.tld
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
    <taglib>
      <tlib-version>0.01</tlib-version>
      <jsp-version>1.2</jsp-version>
      <short-name>jsfcustomcomponent</short-name>
      <uri>http://jsfcustomcomponent/</uri>
      <description><![CDATA[jsf custom component tags]]>  </description>
      <tag>
        <name>specialBtnTag</name>
        <tag-class>jsfcustomcomponent.SpecialBtnTag</tag-class>
        <attribute>
          <name>value</name>
          <required>true</required>
          <rtexprvalue>true</rtexprvalue>
          <description><![CDATA[button value]]></description>
        </attribute>
        <attribute>
          <name>specialBtnListener</name>
          <required>true</required>
          <rtexprvalue>true</rtexprvalue>
          <description><![CDATA[action listener]]> </description>
        </attribute>
      </tag>
    </taglib>
    faces-config.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN" "http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
    <faces-config>
      <managed-bean>
        <managed-bean-name>specialBtnBacking</managed-bean-name>
        <managed-bean-class>specialbtn.SpecialBtnBacking</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
      </managed-bean>
      <component>
        <component-type>SpecialBtnComponent</component-type>
        <component-class>jsfcustomcomponent.SpecialBtnComponent</component-class>
        <component-extension>
          <renderer-type>SpecialBtnRenderer</renderer-type>
        </component-extension>
      </component>
      <render-kit>
        <renderer>
          <component-family>SpecialBtnComponent</component-family>
          <renderer-type>SpecialBtnRenderer</renderer-type>
          <renderer-class>jsfcustomcomponent.SpecialBtnRenderer</renderer-class>
        </renderer>
      </render-kit>
    </faces-config>
    SpecialBtnComponent.java
    package jsfcustomcomponent;
    import javax.faces.component.*;
    import javax.faces.context.*;
    import javax.faces.el.*;
    import javax.faces.event.*;
    public class SpecialBtnComponent
        extends UIComponentBase implements ActionSource
        public static final String COMPONENT_TYPE = "SpecialBtnComponent";
        public static final String RENDERER_TYPE = "SpecialBtnRenderer";
        public String getFamily()
            return COMPONENT_TYPE;
        public SpecialBtnComponent()
            super();
            setRendererType(SpecialBtnComponent.RENDERER_TYPE);
        private String value;
        public void setValue(String value, FacesContext facesContext)
            this.value = value;
        public String getValue()
            if (null != this.value)
                return this.value;
            ValueBinding _vb = getValueBinding("value");
            if (_vb != null)
                return (String) _vb.getValue(getFacesContext());
            else
                return null;
        private MethodBinding specialBtnListener = null;
        public MethodBinding getActionListener()
            return (this.specialBtnListener);
        public void setActionListener(MethodBinding actionListener)
            this.specialBtnListener = actionListener;
        public Object saveState(FacesContext context)
            Object values[] = new Object[3];
            values[0] = super.saveState(context);
            values[1] = saveAttachedState(context, this.specialBtnListener);
            values[2] = this.value;
            return (values);
        public void restoreState(FacesContext context, Object state)
            Object values[] = (Object[]) state;
            super.restoreState(context, values[0]);
            this.specialBtnListener = (MethodBinding) restoreAttachedState(context, values[1]);
            this.value = (String) restoreAttachedState(context, values[2]);
        public void broadcast(FacesEvent event) throws AbortProcessingException
            super.broadcast(event);
            if (event instanceof ActionEvent)
                FacesContext context = getFacesContext();
                MethodBinding mb = this.getActionListener();
                if (mb != null)
                    try
                        mb.invoke(context, new Object[]
                                  {event});
                    catch (EvaluationException ex)
                        System.out.println("SpecialBtnComponent/broadcast(FacesEvent event)...EvaluationException encountered - ex.getMessage()=" + ex.getMessage());
                        ex.printStackTrace();
                ActionListener actionListener = context.getApplication().getActionListener();
                if (actionListener != null)
                    actionListener.processAction( (ActionEvent) event);
        public void queueEvent(FacesEvent e)
            if (e instanceof ActionEvent)
                e.setPhaseId(PhaseId.INVOKE_APPLICATION);
            super.queueEvent(e);
        public MethodBinding getAction()
            return null;
        public void setAction(MethodBinding methodBinding)
        public boolean isImmediate()
            return false;
        public void setImmediate(boolean _boolean)
        public void addActionListener(ActionListener actionListener)
            addFacesListener(actionListener);
        public ActionListener[] getActionListeners()
            return (ActionListener[]) getFacesListeners(ActionListener.class);
        public void removeActionListener(ActionListener actionListener)
            removeFacesListener(actionListener);
    SpecialBtnTag.java
    package jsfcustomcomponent;
    import javax.faces.component.*;
    import javax.faces.el.*;
    import javax.faces.webapp.*;
    import com.sun.faces.util.*;
    import javax.faces.context.FacesContext;
    import javax.faces.event.ActionEvent;
    public class SpecialBtnTag
        extends UIComponentTag
        public String value = null;
        public String specialBtnListener = null;
        private SpecialBtnComponent specialBtnComponent;
        public SpecialBtnTag()
            super();
        public String getComponentType()
            return SpecialBtnComponent.COMPONENT_TYPE;
        public String getRendererType()
            return SpecialBtnComponent.RENDERER_TYPE;
        protected void setProperties(UIComponent component)
            super.setProperties(component);
            if (! (component instanceof SpecialBtnComponent))
                throw new IllegalStateException("Component " + component.toString() +
                                                " not expected type.  Expected: jsfcustomcomponent.SpecialBtnComponent.  Perhaps you�re missing a tag?");
            specialBtnComponent = (SpecialBtnComponent) component;
            if (value != null)
                if (isValueReference(value))
                    ValueBinding vb = Util.getValueBinding(value);
                    specialBtnComponent.setValueBinding("value", vb);
                else
                    throw new IllegalStateException("The value for �value� must be a ValueBinding.");
            if (specialBtnListener != null)
                if (isValueReference(specialBtnListener))
                    MethodBinding mb = FacesContext.getCurrentInstance().getApplication().createMethodBinding(specialBtnListener, new Class[]{ActionEvent.class});
                    ( (SpecialBtnComponent) component).setActionListener(mb);
                else
                    MethodBinding mb = Util.createConstantMethodBinding(specialBtnListener);
                    ( (SpecialBtnComponent) component).setActionListener(mb);
        public void release()
            super.release();
            value = null;
            specialBtnListener = null;
        public void setValue(String value)
            this.value = value;
        public String getValue()
            return this.value;
        public void setSpecialBtnListener(String specialBtnListener)
            this.specialBtnListener = specialBtnListener;
        public String getSpecialBtnListener()
            return this.specialBtnListener;
    SpecialBtnRenderer
    package jsfcustomcomponent;
    import java.util.*;
    import javax.faces.component.*;
    import javax.faces.context.*;
    import javax.faces.event.*;
    import javax.faces.render.*;
    import javax.faces.el.MethodBinding;
    import javax.faces.el.*;
    public class SpecialBtnRenderer
        extends Renderer
        String value;
        public SpecialBtnRenderer()
            super();
        public void decode(FacesContext context, UIComponent component)
            try
                Map requestMap = context.getExternalContext().getRequestParameterMap();
                String clientId = component.getClientId(context);
                SpecialBtnComponent specialBtnComponent = (SpecialBtnComponent) component;
                String value = (String) requestMap.get(clientId);
                if (null != value)
                    specialBtnComponent.setValue(value, context);
                    MethodBinding mb = specialBtnComponent.getActionListener();
                    if (mb != null)
                        System.out.println("SpecialBtnRenderer/decode...mb.getExpressionString()=" + mb.getExpressionString());
                        //mb.invoke(context, new Object[0]);
                        mb.invoke(context, new Object[1]);
                    ActionEvent actionEvent = new ActionEvent(specialBtnComponent);
                    specialBtnComponent.queueEvent(actionEvent);
            catch (EvaluationException ex)
                ex.printStackTrace();
        public void encodeEnd(FacesContext context, UIComponent component) throws java.io.IOException
            SpecialBtnComponent specialBtnComponent = (SpecialBtnComponent) component;
            ResponseWriter writer = context.getResponseWriter();
            String clientId = component.getClientId(context);
            value = (String) component.getAttributes().get("value");
            if (value == null)
                value = "defaultValue";
            buildSpecialBtn(writer, value, clientId, specialBtnComponent);
        private void buildSpecialBtn(ResponseWriter writer, String value, String clientId, SpecialBtnComponent component) throws java.io.IOException
            writer.startElement("table", component);
            writer.startElement("tbody", component);
            writer.startElement("tr", component);
            writer.startElement("td", component);
            value = String.valueOf(value);
            writer.startElement("input", component);
            writer.writeAttribute("type", "submit", null);
            writer.writeAttribute("name", clientId, "clientId");
            writer.writeAttribute("value", value, null);
            writer.endElement("input");
            writer.endElement("td");
            writer.endElement("tr");
            writer.endElement("tbody");
            writer.endElement("table");
    web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
      <display-name>pagerWEB</display-name>
      <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.faces</url-pattern>
      </servlet-mapping>
      <jsp-config>
        <taglib>
          <taglib-uri>http://jsfcustomcomponent/</taglib-uri>
          <taglib-location>/WEB-INF/jsfcustomcomponent.tld</taglib-location>
        </taglib>
      </jsp-config>
    </web-app>

  • Fragement page hangs on action listener in task flow

    I have a scenario that I have a home page and it has a command button(button1) on clicking of which it replaces the main region through the help of task flow. Now this new page has another command button(button2) which navigates to the invoking page(after execution of some action listener).
    The problem comes in when we try to click on the button2, then the page hangs by itself. This however works when we do a page refresh.
    Any ideas of why this strange thing is happening?

    ... not with the information you provide. I assume that the case evaluation is based on invalid data.
    Frank

  • How to add action listener to internal frame?

    I have frame Main where I am trying to add action listener.
    Action listener should be listening button in frame Menu.
    I think it should be:
    Menu frame = new Menu();
    frame.btn_start.addActionListener(this);but it seems to be doing absolutely nothing.
    If I try to add in menu:
    btn_start.addActionListener(new Main());it generates: java.lang.StackOverflowError
    What should I do? Please help noob :)

    To get better help sooner, post a [_Short, Self Contained, Compilable and Executable, Example Program (SSCCE)_|http://mindprod.com/jgloss/sscce.html] that clearly demonstrates your problem.
    You're quite possible adding the ActionListener to the wrong component. And constructing a new instance of a class within the constructor is likely the cause of your StackOverflowError.
    db

  • Action listener problem

    I have created the following code and i want the "btnCreate" to open the frame eqstring, i have tried to implement the action listener and it compiles but when i run it the button does nothing
    pnlCreate.add(btnCreate);
    pnlSimpleExample.add(btnSimpleExample);
    pnlHardExample.add(btnHardExample);
    pnlTitle.add(new Label("MAIN MENU"));
    pnlTitle.setFont(new Font("Arial", Font.BOLD, 36));
    // Setup Main Frame
    f.getContentPane().setLayout(new BorderLayout());
    f.getContentPane().add(pnlCreate, BorderLayout.SOUTH);
    f.getContentPane().add(pnlSimpleExample, BorderLayout.WEST);
    f.getContentPane().add(pnlHardExample, BorderLayout.EAST);
    f.getContentPane().add(pnlTitle, BorderLayout.NORTH);
    this.setSize(300, 300);
    btnCreate.addActionListener(
    new ActionListener()
         public void actionPerformed(ActionEvent e)
         eqstring mainFrame = new eqstring();
         }

    I think warnerja is stressed and really thinks you
    should check out this
    [url=http://forum.java.sun.com/rewards.jspa?&threadID=
    5150158&messageID=9562382&dukes=10&doActions=rewardtru
    e&actionButton=Reward+Duke+Stars]very helpful Java
    tool that you can put your code into and itwill tell you what you did wrong.
    :-)

  • Thread in action listener

    Anyway, back to something that matters.....
    public void StartSqueezing()
    NozzleReady=false;
    NozzleInUse=true;
    NozzleNotInUse=false;
    Runnable run1 = new Runnable() { public void run()
    do{
    LitresDispensedPerTransaction =+ 0.10;
    try { Thread.sleep(200);}
    catch(InterruptedException ex) {}
    while (NozzleInUse == true );
    Thread thrd1 = new Thread(run1);
    thrd1.start();
    I have put this is the action listener of a button and it wont work....any ideas???
    Edward

    Quit multi-posting. You already have a posting on the topic.
    Not only that you haven't listened to any advice given in that topic so don't expect any further help.
    a) still no "Code" tags
    b) variable name still don't follow standards
    If you want us to read you code then make an effor to make it readable.
    You've already been given a link to the Swing tutorial, I suggest you take the time to read the section on "How to use Action Listeners".
    This posting is now closed.

  • Action listener activation in many phases

    I need action listener (methods) to be activated in many phases. I.e., when the user clicks a submit button, I want code to be executed (in my case) after the validation phase and after (during) the invoke application phase. In earlier version of the standard, I would just register 2 listeners, returning the appropriate getPhaseId() value. Since this method is removed from the current standard, things get more complicated.
    QUESTION: Why in heavens name was this method removed from the standard? I suppose, because it is difficult to support with listener methods (in contrast to instances)? Bit of a rough solution, no? Or am I missing something?
    I have a solution now, I think, that is based on getting the action event immediate, and requeuing the event again and again.
    In the JSP, in the JSF form, I have a submit button as follows:
    <h:commandButton id="buttonId" value="ButtonText"
                     actionListener="#{handler.buttonListener}"
                     immediate="true"/>The method Handler.buttonListener is:
      public final void buttonListener(ActionEvent ae) {
        LOG.debug("Handler. buttonListener called ("
                  + "ActionEvent.getPhaseId() = " + ae.getPhaseId()
                  + "; ActionEvent.getComponent() = " + ae.getComponent()
                  + ")");
        PhaseId phaseId = ae.getPhaseId();
        if (phaseId.equals(PhaseId.APPLY_REQUEST_VALUES)) {
          LOG.debug("-- processing during " + ae.getPhaseId());
          // meaningful stuff here
          // prepare for execution in next phase
          ae.queue();
            /* this sets phase id to the current phase, so it is extremely important that
             * we set the necessary phase id AFTER queuing the event */
          ae.setPhaseId(PhaseId.PROCESS_VALIDATIONS);
          LOG.debug("-- ActionEvent (getPhaseId() = " + ae.getPhaseId() + ") queued");     
        else if (phaseId.equals(PhaseId.PROCESS_VALIDATIONS)) {
          LOG.debug("-- processing during " + ae.getPhaseId());
          // meaningful stuff here
          // prepare for execution in next phase
          ae.queue();
          /* this sets phase id to the current phase, so it is extremely important that
           * we set the necessary phase id AFTER queuing the event */
          ae.setPhaseId(PhaseId.INVOKE_APPLICATION);
          LOG.debug("-- ActionEvent (getPhaseId() = " + ae.getPhaseId() + ") queued");     
        else if (phaseId.equals(PhaseId.INVOKE_APPLICATION)) {
          LOG.debug("-- processing during " + ae.getPhaseId());
          // meaningful stuff here
        LOG.debug("Handler. buttonListener done");
      }The /* */ comment in the code is there because the queue methods (on the event as well as the component) set the phase id of the event to the current phase. If I set the phase id of the event before queuing it, that setting is undone, and I get an infinite loop! This is weird, and my solution is at least shaky: it doesn't feel stable across JSF implementations and future releases. I could not find a queue method that leaves the phase id alone.
    QUESTION: am I missing something?
    The output however is:
    Mar 21, 2005 12:51:11 PM org.exadel.jsf.PhaseTracker beforePhase
    INFO: BEFORE RESTORE_VIEW 1
    Mar 21, 2005 12:51:11 PM org.exadel.jsf.PhaseTracker afterPhase
    INFO: AFTER RESTORE_VIEW 1
    Mar 21, 2005 12:51:11 PM org.exadel.jsf.PhaseTracker beforePhase
    INFO: BEFORE APPLY_REQUEST_VALUES 2
    12:51:12,119 DEBUG Handler:550 - Handler.buttonListener called
          (ActionEvent.getPhaseId() = APPLY_REQUEST_VALUES 2;
           ActionEvent.getComponent() = javax.faces.component.html.HtmlCommandButton@33b99a)
    12:51:12,171 DEBUG Handler:556 - -- processing during APPLY_REQUEST_VALUES 2
    12:51:12,184 DEBUG Handler:564 - -- ActionEvent (getPhaseId() = PROCESS_VALIDATIONS 3) queued
    12:51:12,189 DEBUG Handler:580 - Handler.buttonListener done
    12:51:12,220 DEBUG Handler:550 - Handler.buttonListener called
         (ActionEvent.getPhaseId() = PROCESS_VALIDATIONS 3;
          ActionEvent.getComponent() = javax.faces.component.html.HtmlCommandButton@33b99a)
    12:51:12,255 DEBUG Handler:567 - -- processing during PROCESS_VALIDATIONS 3
    12:51:12,256 DEBUG Handler:574 - -- ActionEvent (getPhaseId() = INVOKE_APPLICATION 5) queued
    12:51:12,257 DEBUG Handler:580 - Handler.buttonListener done
    12:51:12,265 DEBUG Handler:550 - Handler.buttonListener called
        (ActionEvent.getPhaseId() = INVOKE_APPLICATION 5;
         ActionEvent.getComponent() = javax.faces.component.html.HtmlCommandButton@33b99a)
    12:51:12,267 DEBUG Handler:577 - -- processing during INVOKE_APPLICATION 5
    12:51:12,268 DEBUG Handler:580 - Handler.buttonListener done
    Mar 21, 2005 12:51:12 PM org.exadel.jsf.PhaseTracker afterPhase
    INFO: AFTER APPLY_REQUEST_VALUES 2
    Mar 21, 2005 12:51:12 PM org.exadel.jsf.PhaseTracker beforePhase
    INFO: BEFORE RENDER_RESPONSE 6
    Mar 21, 2005 12:51:12 PM org.exadel.jsf.PhaseTracker afterPhase
    INFO: AFTER RENDER_RESPONSE 6The info is generated by a phase listener I found somewhere (sorry for the lack of reference here to the author). As you can see, I get 3 consecutive calls of my listener method, but they are all during the apply request values phase, and we jump from the apply request values phase immediately to the render response phase, skipping all the other phases, although my listener is actually called 3 times.
    QUESTION: what the fuck? What is happening here, and more important, how can I fix it?

    I am in touch with IBM about any patch they might have for this. I just thought I'd post details from what I researched.
    Basically I found that if I had CommandButton and/or CommandLink components on my page and clicked them for a total greater than 15 times, the application just quit reacting to any of the clicks. After writing a PhaseListener I discovered that after 15 clicks the JSF lifecycle was going straight from the Restore View (1) to Render Response (6) phase instead of going through the ones in between.
    I downloaded the JSF source code and tracked down the magic number 15. As mentioned earlier in this forum it has to do with the number of views per session. In the Sun JSF-RI com.sun.faces.application.StateManagerImpl class
    the number of views is defaulted to 15. When the number of views hits the max the oldest view is deleted. Somehow I don't think they are deleting the oldest view or else why my app quits after 15 clicks I do not know. Anyway this is a known issue with the Sun JSF-RI and documented in their Release Notes.
    Depending on the JSF implementation there may or may not be a workaround. I mean to say the the workaround is not part of the JSF spec but Sun's implementation has a feature where you can configure the com.sun.faces.NUMBER_OF_VIEWS_IN_SESSION value in the web.xml file under the <context-param> tag. If you set the value sufficiently high you lower the risk of the app quitting on you (like a user may be unlikely to make 100 or even 50 clicks on the same page). You might also want to set the state to be saved on the server by setting javax.faces.STATE_SAVING_METHOD to server in another <context-param> tag. Somehow setting this state to client caused errors (NullPointerException) in our app in one of the Faces classes itself.
    Hope this helps someone out there.

  • JTextField action listener

    Hi All,
         I have added an action listener to a TextField,im printing the text entered in textfiled by pressing the enter key of keyboard.
          public void actionPerformed(ActionEvent ae) {
                   System.out.println(jtf.getText());
             } my question is as an when i enterd the text in the textfield i want to printit . please help me to solve this.
    Thanks

    Yannix wrote:
    Add a keyListener in your JTextField.
    http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html
    I've always thought that it is better to use solutions that use a higher level of abstraction compared to solutions that use a lower level. If so, then using key Binding may be a better solution. If this is wrong, please let me know. You can learn about key Bindings here:
    http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html
    One statement in this tutorial compares key bindings to keylisteners:
    An alternative to key bindings is using key listeners. Key listeners have their place as a
    low-level interface to keyboard input, but for responding to individual keys key bindings are more
    appropriate and tend to result in more easily maintained code. Key listeners are also difficult if
    the key binding is to be active when the component doesn't have focus. Some of the advantages
    of key bindings are they're somewhat self documenting, take the containment hierarchy into
    account, encourage reusable chunks of code (Action objects), and allow actions to be easily
    removed, customized, or shared. Also, they make it easy to change the key to which an action
    is bound. Another advantage of Actions is that they have an enabled state which provides an
    easy way to disable the action without having to track which component it is attached to.
    In the future Swing related question should be posted in the Swing forum.
    http://forum.java.sun.com/forum.jspa?forumID=57
    Agree 100%

  • ADF TUTORIAL: PROBLEMS WITH "Export Collection Action Listener"

    hello all,
    environment:
    windows xp
    jedev 11.1.1.3.0
    firefox 3.6.13
    tutorial: Developing Ajax-Based User Interfaces with JSF: An Introduction to ADF Faces Rich Client Components
    url: http://st-curriculum.oracle.com/obe/jdev/obe11jdev/ps1/adf_richclient/adfrichclient.htm
    mainstep: "working with menus"
    substep: number 5 "add collection action listener"
    until the step "working with menus" works everthing fine. after i added the collection action listener and saved my work, the webapplication will not open. i see only a blank page and no error message.
    when i delete the action listener works everything fine again.
    how can i fix this issue? thx to everyone.
    best regards
    gunnar

    I'm not sure if this is going to help anyone , but if you're stuck at that point of the tutorial , try to drop the "Export Collection Action Listener" onto the menuItem "Export To Excel" not under it;
    So the xml under the source tab should look something like this :
    <f:facet name="menus">
    <af:menu text="My Options" id="m2" detachable="true">
    <af:commandMenuItem text="Export To Excel" id="cmi1">
    <af:exportCollectionActionListener type="excelHTML"
    exportedId="t1"/>
    </af:commandMenuItem>
    <af:commandMenuItem text="Show Specials" id="cmi2">
    <af:showPopupBehavior popupId=":::p1"/>
    </af:commandMenuItem>
    </af:menu>
    Hope this helped somebody .

Maybe you are looking for