ActionListener/AbstractAction
Hello everyone,
Can someone tell me the best choice for action-event handling in swing?
Extends AbstractAction or implements ActionListener
Thanks for clarifying
abstractAction implements actionListener so if you extend it then you are infact implementing actionListener...
but AbstractAction has values like tooltip, text, icon, and others, and you can construct JButton or menus from AbsractAction,
this is good when you lets say you have a JMenuItem that dose somthing and you want the same thing to be on a JToolBar then just add the same AbsractAction to bot the JMenuItem and JToolBar then you will not have multiple
if(event.getSource()==button1)so i preffer the AbstractAction but i use it like this..
//Menu -> Help -> About
AbstractAction about=new AbstractAction(){
public void actionPerformed(ActionEvent e){aboutAction();}
Utils.setActionValues(about,"About",
new ImageIcon("about.gif"),KeyEvent.VK_A,
"Shows the about dialog",null,true);
//the Utils method is like this
* Sets the values of the input action
public static void setActionValues (Action action, String name, Icon icon,
int mnemonic, String description, KeyStroke accelerator,
boolean enabled)
action.putValue(Action.ACCELERATOR_KEY, accelerator);
action.putValue (Action.MNEMONIC_KEY, new Integer (mnemonic));
action.putValue (Action.NAME, name);
action.putValue (Action.SHORT_DESCRIPTION, description);
action.putValue (Action.SMALL_ICON , icon);
action.setEnabled (enabled);
}i would then use it like this
JMenu menu=new JMenu();
menu.add(about);
JToolBar toolBar =new JToolBar();
tooBar.add(about);hope this helps... you
Similar Messages
-
ActionListener as nested class, anonymous class etc.
I'm programing my own text editor and im trying to decide in what way to implement an ActionListener for JMenuItems.
I've got 3 possible ideas of how to implement it.
First way is to implement the ActionListener in the same class as the JMenu and use a switch statement or a fairly long if-else statement.
Second way is to create nested classes for each ActoinEvent.
public class OuterClass {
//Some random code here...
private class ActionClass implements ActionListener{
public void actionPerformed(ActionEvent e) {
//Random code.
}And final way is creating anonymous classes adding ActionListeners for each JMenuItem.
menuItem.addActionListener(new AbstractAction(){
public void actionPerformed(ActionEvent e) {
});But i can't decide on wich of these are the moste correct and accepted way.
Could someone point me to the right direction?
Edited by: Idono on Jun 3, 2010 7:36 PMthe only time you would do the first one would be if you wanted several ActionListeners to do the EXACT SAME THING.
Then you just write the "actionClass" one time, and have each Component use it.
private class ActionClass implements ActionListener{
public void actionPerformed(ActionEvent e) {
//Random code.
menuItem.addActionListener(new ActionClass());
menuItem1.addActionListener(new ActionClass());
menuItem2.addActionListener(new ActionClass());
menuItem3.addActionListener(new ActionClass());But (as the other person mentioned) usually you use anonymous classes because each component has different actions.
menuItem.addActionListener(new AbstractAction(){
public void actionPerformed(ActionEvent e) { ... }
menuItem1.addActionListener(new AbstractAction(){
public void actionPerformed(ActionEvent e) { ... }
menuItem2.addActionListener(new AbstractAction(){
public void actionPerformed(ActionEvent e) { ... }
}); -
Adding ActionListener to JMenu
Is it possible to add actionListener to Jmenu object
for example File, Format, Exit these are Menus added in the menuBar not menu items
on clicking the Exit the frame shuld get closed.
For detecting the action clicked on the Menu shall i use actionListener?
I have tried using MenuListener its getting invoked on selection
I dont want it on selection , I want the frame to be displayed only on clicking that menu.Alas, whilst a JMenu is-a JMenuItem (the Composite Pattern at work), it doesn't function entriely like on,
and registering ActionListeners with a JMenu doesn't work. Try MenuListener:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ActionExample {
public static void main(String[] args) {
Action sample = new SampleAction();
JMenu menu = new JMenu("Menu");
menu.setMnemonic(KeyEvent.VK_M);
menu.add(sample);
menu.addMenuListener(new SampleMenuListener());
JToolBar tb = new JToolBar();
tb.add(sample);
JTextField field = new JTextField(10);
field.setAction(sample);
JFrame f = new JFrame("ActionExample");
JMenuBar mb = new JMenuBar();
mb.add(menu);
f.setJMenuBar(mb);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(tb, BorderLayout.NORTH);
f.getContentPane().add(field, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
class SampleMenuListener implements MenuListener {
public void menuSelected(MenuEvent e) {
System.out.println("menuSelected");
public void menuDeselected(MenuEvent e) {
System.out.println("menuDeelected");
public void menuCanceled(MenuEvent e) {
System.out.println("menuCanceled");
class SampleAction extends AbstractAction {
public SampleAction() {
super("Sample");
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("alt S"));
putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_S));
putValue(SHORT_DESCRIPTION, "Just a sample action");
public void actionPerformed(ActionEvent evt) {
System.out.println("sample...");
} -
Can not add a picture to the JFrame from an ActionListener class
As topic says, I can not add a picture to the JFrame from an ActionListener class which is a class inside the JFrame class.
I have a Map.java class where I load an image with ImageIcon chosen with JFileChooser.
I my window class (main class), I have following:
class OpenImage_Listener implements ActionListener
public void actionPerformed(ActionEvent e)
int ans = open.showOpenDialog(MainProgram.this); // "open" is the JFileChooser reference
if(ans == open.APPROVE_OPTION)
File file = open.getSelectedFile();
MainProgram.this.add(new Map(file.getName()), BorderLayout.CENTER); // this line does not work - it does not add the choosen picture on the window,
//but if I add the picture outside this listener class and inside the MainProgram constructor, the picture apperas, but then I cannot use the JFileChooser.
showMessageDialog(MainProgram.this, fil.getName() ,"It works", INFORMATION_MESSAGE); // this popup works, and thereby the ActionListener also works.
}So why can�t I add a picture to the window from the above listener class?The SSCCE:
Ok, I think I solved it with the picture, but now I cannot add new components after adding the picture.
Look at the comment in the actionlistener class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class Test extends JFrame{
JButton b = new JButton("Open");
JFileChooser jfc = new JFileChooser(System.getProperty("user.dir"));
Picture pane;
Test(){
super("Main Program");
setLayout(new BorderLayout());
JPanel north = new JPanel();
add(north, BorderLayout.NORTH);
north.add(b);
b.addActionListener(new Listener());
setVisible(true);
setSize(500,500);
pane = new Picture("");
add(pane, BorderLayout.CENTER);
class Listener implements ActionListener {
public void actionPerformed(ActionEvent e){
int ans = jfc.showOpenDialog(Test.this);
if(ans == jfc.APPROVE_OPTION)
File file = jfc.getSelectedFile();
Test.this.add(new Picture(file.getName()), BorderLayout.CENTER);
pane.add(new JButton("NEW BUTTON")); // Why does this button not appear on the window???
pane.repaint();
pane.revalidate();
public static void main(String[] args)
Test t = new Test();
class Picture extends JPanel
Image pic;
String filename;
Picture(String filename)
setLayout(null);
this.filename = filename;
pic = Toolkit.getDefaultToolkit().getImage(filename);
protected void paintComponent(Graphics g)
super.paintComponent(g);
g.drawImage(pic,0,0,getWidth(),getHeight(),this);
revalidate();
} -
ActionListener not working with JFrame
Hi,
I've just rehashed an old bit of code to work with a new application but for some reason the JButton ActionListeners aren't working. However if I extend JDialog they work ok. The current code for JDialog is:-
* File: GUI.java
* @author ODL 3xx Distributed Systems - Team x
* @description This class provides a means for the user to
* interact with file server.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class GUI extends JDialog implements ActionListener, ApplicationConstants {
private JLabel label1, label2, label3, label4, label5;
private JTextField field1, field2, field3, field4, field5;
private JButton button1, button2, button3, button4, button5;
private Container container;
private Message sendFile;
private String id;
private String defaultText = "Enter file name here";
private ClientForGUI client;
private long timeStart, timeEnd;
public GUI(JFrame frame) {
super(frame, "File Server Actions", true);
client = new ClientForGUI(this);
try{
InetAddress addr = InetAddress.getLocalHost();
id = addr.getHostName() + Long.toString((new java.util.Date()).getTime());
if(client.connectToServer())
initGUI();
else{
JOptionPane.showMessageDialog(this, "Unable to connect to server", "Error", JOptionPane.WARNING_MESSAGE);
System.exit(0);
catch(UnknownHostException uhe){
System.out.println("Unknown Host Exception");
initGUI();
* Create the GUI
private void initGUI() {
container = this.getContentPane();
container.setLayout(null);
label1 = new JLabel("Upload File");
label2 = new JLabel("Rename File");
label3 = new JLabel("Delete File");
label4 = new JLabel("Create File");
label5 = new JLabel("Download File");
field1 = new JTextField();
field2 = new JTextField();
field3 = new JTextField();
field4 = new JTextField();
field5 = new JTextField();
button1 = new JButton("Upload");
button2 = new JButton("Rename");
button3 = new JButton("Delete");
button4 = new JButton("Create");
button5 = new JButton("Download");
label1.setBounds(10,10,80,20);
label2.setBounds(10,40,80,20);
label3.setBounds(10,70,80,20);
label4.setBounds(10,100,80,20);
label5.setBounds(10,130,80,20);
field1.setBounds(100,40,200,20);
field1.setText("Old name");
field2.setBounds(310,40,200,20);
field2.setText("New name");
field3.setBounds(100,70,410,20);
field3.setText(defaultText);
field4.setBounds(100,100,410,20);
field4.setText(defaultText);
field5.setBounds(100,130,410,20);
field5.setText(defaultText);
button1.setBounds(100,10,100,20);
button1.addActionListener(this);
button2.setBounds(520,40,100,20);
button2.addActionListener(this);
button3.setBounds(520,70,100,20);
button3.addActionListener(this);
button4.setBounds(520,100,100,20);
button4.addActionListener(this);
button5.setBounds(520,130,100,20);
button5.addActionListener(this);
container.add(label1);
container.add(button1);
container.add(label2);
container.add(field1);
container.add(field2);
container.add(button2);
container.add(label3);
container.add(field3);
container.add(button3);
container.add(label4);
container.add(field4);
container.add(button4);
container.add(label5);
container.add(field5);
container.add(button5);
setSize(640,200);
setResizable(false);
//Centre on the screen
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((d.getWidth() - getWidth()) / 2);
int y = (int) ((d.getHeight() - getHeight()) / 2);
setLocation(x,y);
setVisible(true);
private void sendMessageToServer(Message message){
message.setId(id);
timeStart = new java.util.Date().getTime();
try{
client.sendMessageToServer(message);
catch(IOException ioe){
System.out.println("Unable to send message to server");
* Perform some action based on user interaction
* @param ae - ActionEvent
public void actionPerformed(ActionEvent e){
Object o = e.getSource();
String name;
if(o == button1){
try{
JFileChooser fc = new JFileChooser();
fc.setVisible(true);
//return value is what the user presses in the open File dialog
int returnVal = fc.showOpenDialog(null);
//if they choose OK
if (returnVal == JFileChooser.APPROVE_OPTION) {
//file now references the selected
File file = fc.getSelectedFile();
//create a FileInputStream from file location
FileInputStream fis = new FileInputStream(file);
// Create the byte array to hold the data, the same size as the file
byte [] fileBytes = new byte[(int)file.length()];
// Read in the bytes from the file into the byte array
int offset = 0;
int numRead = 0;
while (offset < fileBytes.length &&
(numRead=fis.read(fileBytes, offset, fileBytes.length-offset)) >=
0) {
offset += numRead;
// Ensure all the bytes have been read in
if (offset < fileBytes.length) {
throw new IOException("Could not completely read file "+file.getName());
fis.close();
sendFile = new Message(SEND_FILE, fileBytes);
sendFile.setId(id);
sendFile.setFileName(file.getName());
byte [] myarray = ConvertData.messageToBytes(sendFile);
Message sendWarning = new Message(SEND_FILE_WARNING);
sendWarning.setFileName(file.getName());
sendWarning.setFileSize(myarray.length);
try{
sendMessageToServer(sendWarning);
catch(Exception excep){
System.out.println(excep);
catch(FileNotFoundException fnfe){
System.out.println("File Not Found Exception");
catch(java.io.IOException ioe){
System.out.println("IO Exception");
else if(o == button2){
name = field1.getText();
String name2 = field2.getText();
Message renameMessage = new Message(RENAME_FILE);
renameMessage.setFileName(name);
renameMessage.setFileRename(name2);
sendMessageToServer(renameMessage);
field1.setText("Old name");
field2.setText("New name");
else if(o == button3){
name = field3.getText();
Message deleteMessage = new Message(DELETE_FILE);
deleteMessage.setFileName(name);
sendMessageToServer(deleteMessage);
field3.setText(defaultText);
else if(o == button4){
name = field4.getText();
Message createMessage = new Message(CREATE_FILE);
createMessage.setFileName(name);
sendMessageToServer(createMessage);
field4.setText(defaultText);
else if(o == button5){
name = field5.getText();
Message downloadMessage = new Message(REQUEST_FILE);
downloadMessage.setFileName(name);
sendMessageToServer(downloadMessage);
field5.setText(defaultText);
public void processServerMessage(Message message){
switch(message.getMessageHeader()){
case SEND_FILE_WARNING:
//change the download size to file size plus max message size
client.setDownload((int)message.getFileSize(),true);
//turn message back around with acknowledgement header
message.setMessageHeader(SEND_FILE_ACK);
//send the message
try{
sendMessageToServer(message);
catch(Exception e){
System.out.println(e);
break;
//server has acknowledged that the client wishes to send a message
//so send the message
case SEND_FILE_ACK:
//send the message
try{
sendMessageToServer(sendFile);
catch(Exception e){
System.out.println(e);
break;
//server is sending the file to the client.
case SEND_FILE:
//reset the download size to default
client.setDownload(DEFAULT_MESSAGE_SIZE,false);
//get the file name
File f = new File(message.getFileName());
//create the file chooser
JFileChooser fc = new JFileChooser();
//set selected file as thoe one downloaded
fc.setSelectedFile(f);
//get the button hit by the user
int returnVal = fc.showSaveDialog(null);
//if button is OK
if (returnVal == JFileChooser.APPROVE_OPTION){
File temp = fc.getCurrentDirectory();
String [] files = temp.list();
java.util.List alist = java.util.Arrays.asList(files);
f = fc.getSelectedFile();
if(alist.contains(message.getFileName())){
if(JOptionPane.showConfirmDialog(null,
message.getFileName() + " already exists. Are you sure you want to overwrite this file?",
"Instant Messenger: Quit Program",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null) == JOptionPane.YES_OPTION) {
//f = fc.getSelectedFile();
System.out.println(f.toString());
//this is where the file is copied
try{
FileOutputStream fs = new FileOutputStream(f);
fs.write(message.getFile());
fs.close();
catch(IOException e){
System.out.println(e);
else fc.hide();
else{
System.out.println("Here " + f.toString());
try{
FileOutputStream fs = new FileOutputStream(f);
fs.write(message.getFile());
fs.close();
catch(IOException e){
System.out.println(e);
else fc.hide();
break;
case INFORMATION:
timeEnd = new java.util.Date().getTime();
Long rtrip = timeEnd - timeStart;
String str = Long.toString(rtrip);
double d = Double.valueOf(str).doubleValue();
String fullMessage = message.getMessage();
fullMessage += " The total time taken for the last request was " +
rtrip + " milliseconds" + " or roughly " + d/1000 + " seconds";
JOptionPane.showMessageDialog(null,fullMessage,"Information",JOptionPane.INFORMATION_MESSAGE);
break;
class TestGUI{
public static void main(String [] args){
JFrame frame = new JFrame();
GUI myGUI = new GUI(frame);
} If I change the GUI constructor to empty and extend JFrame instead of JDialog and change the call to super the ActionListener stops working. I've never known this problem before (i.e. I always use e.getSource()). I've even cast the object to a JButton to ensure that the right button is pressed and it is all ok.
Is there something fundamentally wrong when I make those simple changes to JFrame?
Regards,
ChrisI think rather the approach is your action handling in terms of the buttons. The giant actionPerformed method is difficult to read and maintain.
I would recommend the following things:
1. Split your ActionListener into multiple smaller listeners. There's not really even a reason for the GUI class to be an action listener. Instead of having GUI implement ActionListener and trying to keep all of the functionality in one place, use anonymous classes:
button3.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
name = field3.getText();
Message deleteMessage = new Message(DELETE_FILE);
deleteMessage.setFileName(name);
sendMessageToServer(deleteMessage);
field3.setText(defaultText);
button4.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
name = field4.getText();
Message createMessage = new Message(CREATE_FILE);
createMessage.setFileName(name);
sendMessageToServer(createMessage);
field4.setText(defaultText);
2. Only use the == operator on primitives. There are very few cases in which you can properly use the == operator on objects and, in every one of those cases I have experienced, the equals(Object) method produces the same result.
3. Name your variables more descriptively. There is really very little reason for your buttons to be named button1, button2, and so on. Give them names that mean something. For example, button1 should be named something like uploadFileButton or buttonUpload. That will give us significant information about what it is expected to do, whereas button1 does not. You may be able to remember what button1 does, but you wrote the code. I keep having to refer back to the instantiation of the button to get a hint as to what it does and, in a few months' time, so will you. :) The same goes for your labels and fields, as well.
I'm not sure why you aren't getting the behavior you want. However, have you checked to determine that the event source of the button click is actually the button when the whole thing is inside of a JFrame? I would expect it to be, but you never know. This is why I recommend using different ActionListeners for each button. That way, you can be sure of what caused the event.
Just my 2c. Good luck to you. :) -
Hi
i have coded a button and added a Actionlistner that when the button is pressed then it should repaint the dice.but I don't know why it is not working.
here i my code
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.ImageIcon;
public class Board {
JFrame frame;
//Image dice[] = new Image[2];
//int stick1,stick2,stick3,stick4,stick5;
//boolean begin = true;
Stick st = new Stick();
public static void main(String[] args) {
Board b = new Board();
b.go();
public void go() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("Senet");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jp = new JPanel();
JButton button = new JButton("Make Move");
button.addActionListener((ActionListener) new Stick());
Stick st = new Stick();
//frame.getContentPane().add(BorderLayout.EAST,button);
frame.getContentPane().add(BorderLayout.CENTER,jp);
jp.setBackground(Color.DARK_GRAY);
jp.setLayout(new BoxLayout(jp,BoxLayout.Y_AXIS));
Check c = new Check();
jp.add(c);
jp.add(st);
st.add(button);
st.setBackground(Color.WHITE);
//Display the window.
frame.setSize(600,500);
frame.setVisible(true);
/* public void actionPerformed(ActionEvent event){
st.repaint();
import javax.swing.*;
import java.awt.*;
import java.awt.Graphics.*;
import java.awt.event.*;
* @author Kokil Bhalerao
public class Stick extends JPanel implements ActionListener{
Image dice[] = new Image[2];
int stick1, stick2,stick3,stick4,stick5, result;
boolean begin = true;
public void actionPerformed(ActionEvent event){
repaint();
public void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
dice = new Image[2];
dice[0] = new ImageIcon("C:/Program Files/Java/images/stick2.gif").getImage();
dice[1] = new ImageIcon("C:/Program Files/Java/images/stick1.gif").getImage();
begin = false;
stick1 = (int)(Math.random() * 2 + 1);
stick2 = (int)(Math.random() * 2 + 1);
stick3 = (int)(Math.random() * 2 + 1);
stick4 = (int)(Math.random() * 2 + 1);
stick5 = (int)(Math.random() * 2 + 1);
setAll(stick1,stick2,stick3,stick4,stick5,begin);
// draw dice if they've clicked the roll button at least once
if (!begin)
g2.drawImage(dice[stick1 - 1], 20, 40,100,50,this);
g2.drawImage(dice[stick2 - 1], 120, 40,100,50,this);
g2.drawImage(dice[stick3 - 1], 220, 40,100,50,this);
g2.drawImage(dice[stick4 - 1], 320, 40,100,50,this);
g2.drawImage(dice[stick5 - 1], 420,40,100,50,this);
else
g2.drawString("Welcome to senet", 20, 60);
public void setImages(Image s[])
dice = s;
public void setAll(int s1,int s2,int s3,int s4,int s5,boolean b)
stick1 = s1;
stick2 = s2;
stick3 = s3;
stick4 = s4;
stick5 = s5;
begin = b;
public class Check extends JPanel{
public void paint(Graphics g) {
int row; // Row number, from 0 to 7
int col; // Column number, from 0 to 7
int x,y; // Top-left corner of square
Image bg = new ImageIcon("C:/Program Files/Java/images/piece1.gif").getImage();
for ( row = 0; row < 3; row++ ) {
for ( col = 0; col < 10; col++) {
x = col * 60;
y = row * 60;
g.setColor(Color.black);
g.drawRect(x, y, 60, 60);
g.setColor(Color.blue);
g.fillRect(x+1, y+1, 60, 60);
if( row == 0 )
g.drawImage(bg, x+5,y+5,40,40,Color.RED, this);
} // end for row
} // end paint()Please somebody help me with this.
Thanksthanks for the reply. but i don't know how i can do
that.So the code above is not yours ?
http://java.sun.com/docs/books/tutorial/java/index.html -
Strange error while using ActionListener with RichCommandLink
Hi,
I am using Technology preview 3.
I have RichTable bound to af:table in my JSF page.
I am showing database contents inside richTable.
Inside richTable i have one extra column in which i am showing remove link. So every row of table will have remove link. I have added ActionListener as inner class for the backing bean. and this actionlistener i am adding into RichCommandLink(remove link)
But when i click on remove link I am getting weired exception. And i am not able to get why this error is coming.
This problem occures whenever I use contentDelivery parameter with <af:table>
Here is the stack trace of the error.
java.lang.InstantiationException: com.backingBean.UpdateSampleTypeB
ackingBean$MyLinkActionListener
at java.lang.Class.newInstance0(Class.java:335)
at java.lang.Class.newInstance(Class.java:303)
at org.apache.myfaces.trinidad.bean.util.StateUtils$Saver.restoreState(S
tateUtils.java:286)
at org.apache.myfaces.trinidad.bean.util.StateUtils.restoreStateHolder(S
tateUtils.java:202)
at org.apache.myfaces.trinidad.bean.util.StateUtils.restoreList(StateUti
ls.java:257)
at org.apache.myfaces.trinidad.bean.PropertyKey.restoreValue(PropertyKey
.java:231)
at org.apache.myfaces.trinidad.bean.util.StateUtils.restoreState(StateUt
ils.java:148)
at org.apache.myfaces.trinidad.bean.util.FlaggedPropertyMap.restoreState
(FlaggedPropertyMap.java:194)
at org.apache.myfaces.trinidad.bean.FacesBeanImpl.restoreState(FacesBean
Impl.java:358)
at org.apache.myfaces.trinidad.component.UIXComponentBase.restoreState(U
IXComponentBase.java:881)
at org.apache.myfaces.trinidad.component.UIXComponentBase.processRestore
State(UIXComponentBase.java:861)
at org.apache.myfaces.trinidad.component.TreeState.restoreState(TreeStat
e.java:96)
at org.apache.myfaces.trinidad.component.UIXComponentBase.processRestore
State(UIXComponentBase.java:855)
at org.apache.myfaces.trinidad.component.TreeState.restoreState(TreeStat
e.java:96)
at org.apache.myfaces.trinidad.component.UIXComponentBase.processRestore
State(UIXComponentBase.java:855)
at javax.faces.component.UIComponentBase.processRestoreState(UIComponent
Base.java:1154)
at org.apache.myfaces.trinidad.component.TreeState.restoreState(TreeStat
e.java:96)
at org.apache.myfaces.trinidad.component.UIXComponentBase.processRestore
State(UIXComponentBase.java:855)
at org.apache.myfaces.trinidad.component.TreeState.restoreState(TreeStat
e.java:96)
at org.apache.myfaces.trinidad.component.UIXComponentBase.processRestore
State(UIXComponentBase.java:855)
at org.apache.myfaces.trinidad.component.TreeState.restoreState(TreeStat
e.java:96)
at org.apache.myfaces.trinidad.component.UIXComponentBase.processRestore
State(UIXComponentBase.java:855)
at org.apache.myfaces.trinidad.component.TreeState.restoreState(TreeStat
e.java:96)
at org.apache.myfaces.trinidad.component.UIXComponentBase.processRestore
State(UIXComponentBase.java:855)
at javax.faces.component.UIComponentBase.processRestoreState(UIComponent
Base.java:1154)
at org.apache.myfaces.trinidadinternal.application.StateManagerImpl.rest
oreView(StateManagerImpl.java:487)
at com.sun.faces.application.ViewHandlerImpl.restoreView(ViewHandlerImpl
.java:287)
at javax.faces.application.ViewHandlerWrapper.restoreView(ViewHandlerWra
pper.java:193)
at org.apache.myfaces.trinidadinternal.application.ViewHandlerImpl.resto
reView(ViewHandlerImpl.java:258)
at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl._restoreView(Li
fecycleImpl.java:438)
at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl._executePhase(L
ifecycleImpl.java:229)
at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl.execute(Lifecyc
leImpl.java:155)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:244)
at com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterC
hain.java:65)
at oracle.adfinternal.view.faces.webapp.rich.SharedLibraryFilter.doFilte
r(SharedLibraryFilter.java:135)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterL
istChain.doFilter(TrinidadFilterImpl.java:284)
at oracle.adfinternal.view.faces.webapp.rich.RegistrationFilter.doFilter
(RegistrationFilter.java:69)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterL
istChain.doFilter(TrinidadFilterImpl.java:284)
at oracle.adfinternal.view.faces.activedata.ADSFilter.doFilter(ADSFilter
.java:74)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterL
istChain.doFilter(TrinidadFilterImpl.java:284)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl._invoke
DoFilter(TrinidadFilterImpl.java:208)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl._doFilt
erImpl(TrinidadFilterImpl.java:165)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl.doFilte
r(TrinidadFilterImpl.java:138)
at org.apache.myfaces.trinidad.webapp.TrinidadFilter.doFilter(TrinidadFi
lter.java:92)
at com.evermind.server.http.EvermindFilterChain.doFilter(EvermindFilterC
hain.java:15)
at oracle.adf.library.webapp.LibraryFilter.doFilter(LibraryFilter.java:1
18)
at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletReque
stDispatcher.java:611)
at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(Ser
vletRequestDispatcher.java:362)
at com.evermind.server.http.HttpRequestHandler.doDispatchRequest(HttpReq
uestHandler.java:915)
at com.evermind.server.http.HttpRequestHandler.doProcessRequest(HttpRequ
estHandler.java:821)
at com.evermind.server.http.HttpRequestHandler.processRequest(HttpReques
tHandler.java:626)
at com.evermind.server.http.HttpRequestHandler.processRequest(HttpReques
tHandler.java:599)
at com.evermind.server.http.HttpRequestHandler.serveOneRequest(HttpReque
stHandler.java:383)
at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.ja
va:161)
at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.ja
va:142)
at oracle.oc4j.network.ServerSocketReadHandler$ClientRunnable.run(Server
SocketReadHandler.java:275)
at oracle.oc4j.network.ServerSocketAcceptHandler.procClientSocket(Server
SocketAcceptHandler.java:237)
at oracle.oc4j.network.ServerSocketAcceptHandler.access$800(ServerSocket
AcceptHandler.java:29)
at oracle.oc4j.network.ServerSocketAcceptHandler$AcceptHandlerHorse.run(
ServerSocketAcceptHandler.java:878)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExec
utor.java:650)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor
.java:675)
Can anybody please provide any help on this?
Regards,
HirenHi Simon,
I am using addActionListener method of RichCommandLink
Here is how i am trying to use it.
public class backingBean {
private RichTable table;
public backingBean() {
RichColumn rc = new RichColumn();
RichCommandLink cmd = new RichCommandLink();
MyActionListener listener = new MyActionListener();
cmd.addActionListener(listener);
public RichTable getTable() {
return table;
class MyActionListener implements ActionListener {
public void processAction (ActionEvent actionEvent) throws AbortProcessingException {
// Processing related to edit components of backing bean
Hiren -
Can I use a for loop to add anonymous ActionListener objects?
I have a setListener() method that has the following inside:
for(int k = 0; k < buttons.length; k++)
buttons[k].addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
g2.setColor(colors[k]);
}I have a JButton array and a Color array and I was hoping I could add them quickly in one shot rather than manually adding an anonymous ActionListener 9 times (I have 9 components). It tells me I need to make k final for an inner class and when I tested it by removing the for loop and keeping k as a final integer, it works. Is there a medium such that I can achieve what I want more or less while respecting Java's syntax?
Any input would be greatly appreciated!
Thanks in advance!s3a wrote:
The local variable exists on the stack for as long as the method is executing. Once the method ends, that variable no longer exists. The newly created object, however, can continue to exist long after the method has ended. So when it's referring to variable X, it cannot refer to the same X as the one in the method, because that variable may no longer exist.Sorry for picking on little details but I am still not fully satisfied.
Earlier I questioned if the local variable changed, but now let's say that that variable no longer exists at all, why does that even matter if the inner class copied the value and is keeping it for itself? What do you mean? The variable that existed in the method ceased to exist when the method ended. The inner class, however, can continue to live on, and can continue to refer to what we see as the same variable. However, it obviously can't be the same variable, since, in the world of the inner class, it still exists, while in the world of the method, it does not.
This is completely independent of whether the variable changes or not. Regardless or whether the variable changes we still need two copies--one that goes away when the method's stack frame is popped, and one that lives on as long as the inner object does.
Then, because there are two copies, the designers decided that the variable has to be final, so that they wouldn't have to mess with the complexity of keeping two variables in sync.
That explanation leads me to believe that there is no copy and that there is some kind of "permanent umbilical cord" between the inner class and the local variable.Wrong. There has to be a copy. How else could the inner class keep referring to it after the method ends?
Also, does marking it as final force it to be a permanent constant "variable" even if it's not a field "variable"? Or, similarly, does making a "variable" final make Java pretend that it is a field "variable"?Making a variable final does exactly one thing: It means the value can't change after it's been initialized. This is true of both fields and locals.
As for the "pointless" byte-counting, I really don't see how it's confusing unless you're an absolute beginner. If I see somebody using a byte, I assume they have a real reason to do so, not pointless byte-hoarding. Then when I see that it's just a loop counter, I wonder WTF they were thinking, and have to spend some time determining if there's a valid reason, or if they're just writing bad code. Using a byte for a loop counter is bad code.
I could then ask, why are people not using long instead of int and saying that that's using int is too meticulous?Part of it is probably historical. Part of it is because at 4 bytes, and int is exactly on word on the vast majority of hardware that Java has targeted since it came out. 8-byte words are becoming more common (64-bit hardware) but still in the minority. -
How can I associate an ActionListener with a specific button
I modified the code a lot. Everything works except that it does not associate the actionListener with the button. It will do the action when the window is minimized or maximized, but not when the button is clicked.
//July 2, 2011
//Multiplication Tables
import java.applet.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MultTables extends JApplet implements ActionListener
//Create Variables for Multiplication Problems
int factorX = 1;
int factorY = 1;
int productZ = 1;
int productReply;
//Create the TextField
JTextField answer = new JTextField(10);
//Create Labels and buttons
JLabel productZLabel = new JLabel(factorX + " * " + factorY + " = ");
JButton checkAnswer = new JButton("Check Answer");
//Create a container
Container con = getContentPane();
FlowLayout flow = new FlowLayout();
public void init()
//What goes init? What needs to be added to the interface?
con.setLayout(flow);
//Add Components and create interface
con.add(productZLabel);
con.add(answer);
con.add(checkAnswer);
//Add ActionListener to button
checkAnswer.addActionListener(this);
public void actionPerformed(ActionEvent e)
productZ = factorX * factorY;
String productReplyString = (answer.getText());
productReply = (Integer.valueOf(productReplyString));
for(int sub = 1; sub <= 9; ++sub);
if (productReply == productZ)
JLabel correct = new JLabel("That is correct!");
con.remove(productZLabel);
con.remove(answer);
con.remove(checkAnswer);
con.add(correct);
++factorX;
else
JLabel incorrect = new JLabel("The correct answer is " + productZ);
con.remove(productZLabel);
con.remove(answer);
con.remove(checkAnswer);
con.add(incorrect);
++factorX;
}EJP wrote:
Are you sure you're running that code? It should work. ActionListeners don't respond to min/max events.Yup. But the repaint triggered by resizing updates the display.
db -
Action / actionListener in h:commandButton with managed beans
I have a problem with a backing bean whose method is not invoked when i click it. I've seen some posts on here about this yet, I still don't understand what I am doing wrong, if anything.
Some context...I've modeled my application after 'jcatalog' from this article:
http://www.javaworld.com/javaworld/jw-07-2004/jw-0719-jsf.html . It's simpler than the article -- I'm not using Spring/Hibernate and the persistence is the file system. For each business object (Resource), there's a backing bean (ResourceBean).
In short, I can't get the backing bean to respond to the button event for 'Add' bound to addAction. This is just like the jcatalog 'createProduct' impl -- which doesn't use the (FacesEvent fe ) approach.
Anyway, I would appreciate anyone's help to get past this.
-Lorinda
(Below are the codes...)
Here's my beans-config.xml:
<!-- view -->
<managed-bean>
<description>
Managed bean that is used as an application scope cache
</description>
<managed-bean-name>applicationBean</managed-bean-name>
<managed-bean-class>
com.intalio.qa.tcm.view.beans.ApplicationBean
</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
<managed-property>
<property-name>viewServicesManager</property-name>
<value>#{viewServicesManagerBean}</value>
</managed-property>
</managed-bean>
<managed-bean>
<description>
View service manager impl for business services
</description>
<managed-bean-name>viewServicesManagerBean</managed-bean-name>
<managed-bean-class>
com.intalio.qa.tcm.view.beans.ViewServicesManagerBean
</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
</managed-bean>
<managed-bean>
<description>
Backing bean that contains product information.
</description>
<managed-bean-name>resourceBean</managed-bean-name>
<managed-bean-class>
com.intalio.qa.tcm.view.beans.ResourceBean
</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
(Note, the applicationBean uses view services manager. The manager is used by the ResourceBean. (It's initialized by the h:output dummy variable reference at the top of my .jsp page)). I can see the initialization in the debug trace.
Here's the resource bean:
import java.util.ArrayList;
import java.util.List;
import javax.faces.FacesException;
import javax.faces.model.SelectItem;
import com.intalio.qa.exceptions.DuplicateIdException;
import com.intalio.qa.exceptions.TCMException;
import com.intalio.qa.tcm.model.Resource;
import com.intalio.qa.tcm.view.builders.ResourceBuilder;
import com.intalio.qa.tcm.view.util.FacesUtils;
* Resource backing bean.
public class ResourceBean extends RootBean {
* The Resource id
private String id;
* The Resource name
private String name;
* Description
private String description;
* the resource type id associated with the Resource
private String resourceTypeId;
// the resource type id associated with the Resource
private List resourceTypeIds;
* @return Returns the resourceTypeIds.
public List getResourceTypeIds() {
return resourceTypeIds;
* @param resourceTypeIds The resourceTypeIds to set.
public void setResourceTypeIds(List resourceTypeIds) {
this.resourceTypeIds = resourceTypeIds;
* Default constructor.
public ResourceBean() {
super();
init();
* Initializes ResourceBean.
* @see RootBean#init()
protected void init() {
try {
LOG.info("ResourceBean init()");
if (id != null) {
Resource resource = viewServicesManager.getResourceService().getResourceById(id);
ResourceBuilder.populateResourceBean(this, resource);
} catch (TCMException ce) {
String msg = "Could not retrieve Resource with id of " + id;
LOG.info(msg, ce);
throw new FacesException(msg, ce);
* Backing bean action to update Resource.
* @return the navigation result
public String updateAction() {
LOG.info("updateAction is invoked");
try {
// Resource Resource = ResourceBuilder.createResource(this);
// LOG.info("ResourceId = " + Resource.getId());
// viewServicesManager.getResourceService().updateResource(Resource);
//remove the ResourceList inside the cache
//FacesUtils.resetManagedBean(BeanNames.RESOURCE_LIST_BEAN);
} catch (Exception e) {
String msg = "Could not update Resource";
LOG.error(msg, e);
FacesUtils.addErrorMessage(msg + ": Internal Error.");
return NavigationResults.FAILURE;
LOG.info("Resource with id of " + id + " was updated successfully.");
return NavigationResults.SUCCESS;
* Backing bean action to create a new Resource.
* @return the navigation result
public String addAction() {
LOG.info("addAction is invoked");
try {
Resource resource = ResourceBuilder.createResource(this);
LOG.info("between");
viewServicesManager.getResourceService().saveResource(resource);
} catch (DuplicateIdException de) {
String msg = "This id already exists";
LOG.info(msg);
FacesUtils.addErrorMessage(msg);
return NavigationResults.RETRY;
} catch (Exception e) {
String msg = "Could not save Resource";
LOG.error(msg, e);
FacesUtils.addErrorMessage(msg + ": Internal Error");
return NavigationResults.FAILURE;
String msg = "Resource with id of " + id + " was created successfully.";
LOG.info(msg);
return NavigationResults.SUCCESS;
* Backing bean action to delete Resource.
* @return the navigation result
public String deleteAction() {
LOG.info("deleteAction is invoked");
try {
// Resource Resource = ResourceBuilder.createResource(this);
// viewServicesManager.getResourceService().deleteResource(Resource);
//remove the ResourceList inside the cache
// FacesUtils.resetManagedBean(BeanNames.RESOURCE_LIST_BEAN);
} catch (Exception e) {
String msg = "Could not delete Resource. ";
LOG.error(msg, e);
FacesUtils.addErrorMessage(null, msg + "Internal Error.");
return NavigationResults.FAILURE;
String msg = "Resource with id of " + id + " was deleted successfully.";
LOG.info(msg);
FacesUtils.addInfoMessage(msg);
return NavigationResults.SUCCESS;
public String getId() {
return id;
* Invoked by the JSF managed bean facility.
* <p>
* The id is from the request parameter.
* If the id is not null, by using the id as the key,
* the Resource bean is initialized.
* @param newQueryId the query id from request parameter
public void setId(String newId) {
id = newId;
public String getName() {
return name;
public void setName(String newName) {
name = newName;
public String getDescription() {
return description;
public void setDescription(String newDescription) {
description = newDescription;
public String getResourceTypeId() {
return resourceTypeId;
public void setResourceTypeId(String newResourceTypeId) {
resourceTypeId = newResourceTypeId;
public String toString() {
return "id=" + id + " name=" + name;
Here's the jsp:
<f:subview id="resourcesCombinedView_subview">
<h:form id="createResourceForm" target="dataFrame">
<h:outputText value="#{applicationBean.dummyVariable}" rendered="true" />
<div align="center">
<head>
<link href="../../css/stylesheet.css" rel="stylesheet" type="text/css">
<FONT color="#191970" size="4" face="Arial">Resources View</FONT>
</head>
<table style="margin-top: 2%" width="35%" cellpadding="10">
<div align="left">
<FONT color="#191970" size="3" face="Arial">Update Resources </FONT>
</div>
<tr>
<td align="center" valign="top" align="center" style="" bgcolor="white" />
<table>
<tbody>
<tr>
<td align="left" styleClass="header" width="100" />
<td align="left" width="450"/>
</tr>
<tr>
<td align="right" width="100"><h:outputText value="Id" /></td>
<td align="left" width="450"><h:inputText
value="#{resourceBean.id}" id="id" required="true" /> <h:message
for="id" styleClass="errorMessage" /></td>
</tr>
<tr>
<td align="right" width="100"><h:outputText value="Name" /></td>
<td align="left" width="450"><h:inputText
value="#{resourceBean.name}" id="name" required="true" /> <h:message
for="name" styleClass="errorMessage" /></td>
</tr>
<tr>
<td align="right" width="100" valign="bottom"><h:outputText
value="Type" /></td>
<td align="left" width="550">
<h:selectOneMenu
value="#{resourceBean.resourceTypeId}" id="resourceTypeId">
<f:selectItem itemValue="" itemLabel="Select Resource Type" />
<f:selectItem itemValue="database" itemLabel="Database" />
<f:selectItem itemValue="external application"
itemLabel="External Application" />
<f:selectItem itemValue="internal"
itemLabel="Intalio|n3 Products" />
<f:selectItem itemValue="os" itemLabel="Operating System" />
</h:selectOneMenu> <h:outputText
value="#{resourceBean.resourceTypeId}" /> <h:message
for="resourceTypeId" styleClass="errorMessage" /></td>
</tr>
<tr>
<td align="right" width="100" valign="bottom"><h:outputText
value="Description" /></td>
<td align="left" width="450"><h:inputText
value="#{resourceBean.description}" id="description" size="96" />
<h:message for="description" styleClass="errorMessage" /></td>
</tr>
</tbody>
</table>
</h:form></td>
<!-- END DATA FORM -->
<!-- BEGIN COMMANDS -->
<td width="30%" align="left" valign="top"><h:form
id="buttonCommandsForm">
<h:panelGroup id="buttons">
<h:panelGrid columns="1" cellspacing="1" cellpadding="2"
border="0" bgcolor="white">
<h:commandButton value="Add"
style="height:21px; width:51px;font-size:8pt; font-color: black;"
actionListener="#{resourceBean.addAction}">
</h:commandButton>
<h:commandButton id="deleteCB" value="Delete"
style="height:21px; width:51px;font-size:8pt"
action="#{resourceBean.deleteAction}">
</h:commandButton>
<h:commandButton id="spaceFillerButton" tabindex="-1"
style="height:21px; width:51px;font-size:8pt;background-color: #ffffff;color: #ffffff;border: 0px;">
</h:commandButton>
<h:commandButton id="saveCB" value="Save"
style="height:21px; width:51px;font-size:8pt"
actionListener="#{resourceBean.saveAction}">
</h:commandButton>
<h:commandButton id="updateCB" value="Update"
style="height:21px; width:51px;font-size:8pt"
actionListener="#{resourceBean.updateAction}">
</h:commandButton>
</h:panelGrid>
</h:panelGroup>
</h:form> <!-- end buttons --></td>
</tr>
</table>
<HR align="center" size="2" width="60%" />
<!-- data table --></div>
</f:subview>Hey, anyway, have you note your jsp reference to the backing bean begins with a lowercase letter, and your backing bean class name begins with an uppercase letter?? I think that's it... I think, cause I'm too unexperienced in JSF.... Bye!!
-
ActionListener not working in JSF
Hi
The use case for my application is as follows:-
CommandToolbarButton - Clicked
Quick Logic in Backing Bean using ActionListener / LaunchListener
Popup Dialog opens up which has some data given by above code in Backing Bean
For this my code in jspx is
<af:toolbar>
<af:commandToolbarButton immediate="true"
icon="/ico_delete.gif"
launchListener="#{TestBean.launchListener}" partialSubmit="true">
<af:showPopupBehavior popupId="popupDialog"/>
</af:commandToolbarButton>
</af:toolbar>
<!--Pop -->
<af:popup id="popupDialog" contentDelivery="lazyUncached">
<f:subview id="popupSubview">
<jsp:include page="ShowPopup.jsff"/>
</f:subview>
</af:popup>
and code in the TestBean is
public void launchListener(LaunchEvent launchEvent) {
System.out.println("TEST");
// Add event code here...
But, I am not able to invoke this Listener as I am getting the TEST message. I even tried the same thing by writing a ActionListener as
public void actionListener(ActionEvent actionEvent) {
System.out.println("TEST");
// Add event code here...
Even this is not working. I have also tried to use <af:commandImageLink> instead of commandToolbarButton, but it is still not working.
Any help on this problem will be highly appreciated.Hi,
I guess, I couldn't explain my problem clearly, so re-posting the code and the query.
JSPX Page
<?xml version='1.0' encoding='windows-1252'?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
<jsp:directive.page contentType="text/html;charset=windows-1252"/>
<f:view>
<af:document>
<af:form>
<af:popup id="popupDialog">
<af:dialog title="Test Dialog">
<af:outputText value="TEST Dialog" />
</af:dialog>
</af:popup>
<af:outputText value="test"/>
<af:toolbar>
<af:commandToolbarButton immediate="true" icon="/ico_delete.gif"
launchListener="#{TestBean.launchListener}"
partialSubmit="true"
actionListener="#{TestBean.actionListener}">
<af:showPopupBehavior popupId="popupDialog"/>
</af:commandToolbarButton>
</af:toolbar>
</af:form>
</af:document>
</f:view>
</jsp:root>
Backing Bean
public void actionListener(ActionEvent actionEvent) {
System.out.println("actionListener called");
// Add event code here...
public void launchListener(LaunchEvent launchEvent) {
System.out.println("launchListener called");
// Add event code here...
I want to execute some code in one of these listeners, so that I can display corresponding data in
<af:popup id="popupDialog">
<af:dialog title="Test Dialog">
<af:outputText value="TEST Dialog" />
</af:dialog>
</af:popup>
I have tried keeping only one Listeners(from actionListner and launcListener), but it doesn't work.
Any help will be highly appreciated. -
What is the ActionListener.getSource for keyboard keys?
Hello,
I am building a small game where you move something in a JFrame by pressing the up/down/left/right arrow keys on your keyboard.
I presume I take care of this with eventhandling. I can sort of understand this topic because I use it with buttons. Then it goes like this:
ActionEventHandler event = new ActionEventHandler();
startButton.addActionListener( event );
exitButton.addActionListener( event );and
private class ActionEventHandler implements ActionListener
public void actionPerformed( ActionEvent e )
if ( e.getSource() == startButton )
Application.game();
else if ( e.getSource() == exitButton )
Application.exit();
}Now can I just add more if statements to this to test for keyboard strokes? If so, how do I program this? If you can help me, please be as specific as possible because I am pretty new to the game and most of the solutions I get from these boards I cannot use, because I don't know where to use them or how....
Thank you!I would use the KeyListener. It has three methods, keyPressed, keyReleased and keyTyped. For a game, I believe you are only interested in the first two. You can then from the KeyEvent find out what keys and modifiers are pressed and released.
-
A question about ActionListener and MouseListener
Hi,
my question here is when we should implement a MouseListener and when we should use ActionListener instead.
I know ActionEvent is fired when a action performed, for instance, a button was pressed down, but I think by implementing a MouseListener, we can use its mouseClicked(MouseEvent e) method to do the same job as the actionPerformed method.
So, what's the difference between a actionevent(button has been pressed down)and a mouse event(click on a button)? And when we should use them?Using the ActionListener actionCommand is the normal paradigm for button clicks.
ActionEvents, ChangeEvents etc are much higher-level than MouseEvents. And you should use the highest level of abstraction that provides sufficient specificity.
When adding MouseListener to an component you actully let the system do more work then needed.
( you have the mouseEntered, mousePressed, mouseClicked, mouseReleased, ..)
Every button click will "generate" three mouse events... pressed, released and clicked.
good luck! -
How do I invoke an ActionListener on a page when the page initially loads?
How do I invoke an ActionListener on a page when the page initially loads?
Page 1: A user clicks on a h:commandButton and is navigated to Page 2.
Page 2: When the page loads and goes through RESTORE_VIEW, APPLY_REQUESTS and RENDER_RESPONSE, I need to call an ActionListener in the managed bean for Page 2.
However, if the user comes in from any other page than Page 1, the ActionListener cannot be invoked intially when the page loads. The user has a choice to click on the h:commandButton on Page2 to invoke the ActionListener.
What is an example of invoking a method with the ActionListener signature in Java code?
Where would I put the code to invoke the ActionListener, in a beforePhase or afterPhase, constructor?
Thanks,
--ToddInteresting. You're right. It doesn't happen when I click away from this site and then return. Maybe I'm barking up the wrong tree. Maybe it's the specific website I was thinking of and not Firefox. Unfortunately, I have to use that site all the time for work. I'll try contacting their webmaster. Thanks for your help.
-
Best practice for backing bean population? (also, ActionListener RANT)
Hello,
I am about 3/4 of the way through development of a small to medium size JSF application. Sometimes I really like JSF, but much of the time I am left puzzled or frustrated for hours trying to find workarounds to JSF's bugs/glitches and design flaws.
For example, early on, I was impressed with how easily it was to invoke a method from a page using an actionlistener. Now that I'm actually building things with JSF, the actionlistener funtionality still seems cool, but incredibly half baked. I find myself using request parameters LIKE CRAZY to work around the fact that JSF doesnt support passing parameters directly to backing bean methods. This feels awkward and wrong considering the fact that JSF is intended to abstract the HTTP underpinnings. To add insult to injury, I often have to iterate through ALL of the request parameters looking for one that has an id with an ending matching my desired property name (since JSF appends it's own crap to the beginning). I don't like doing things in a hacky way. This seems very hacky, and I feel dirty doing it.
So, my first question is, what is the best practice for populating backing beans??? How do others accomplish this. I can think of several other approaches, but none feel less hacky.
Second, are there plans in the next spec (please say there are) to allow parameters to be passed to backing bean methods? If not, WHY THE HECK NOT?
Even though JSF expert group people have been conspicuously absent from this forum of late, I'd really appreciate responses from you as well.
Thank you for your thoughts.Hi BrownBear,
I've been using JSF for about 6 months now and I'd be glade to help as much as I can.
Concerning parameters, I'm not sure what your issue is but I use the f:param tag to pass them. If you could post an example of what you are trying to do, I could see exactly what your issue is. Maybe the f:param can't help you.
As for best practice for populating backing beans, I personaly try to let JSF do as much as possible. For example, if I have a backing bean with five properties, I make sure that they all are on the JSP page the bean serves. If one of the property is just there as an Id like, lets say, a Person ID (DB row key), then I put it on my JSP page as a hidden input field. I do the same with the properties that only for display, if I want them to be back in my bean when request comesback.
Hope this help some how. Please, feel free to ask specific questions related to your specific problem and I monitor this post and trnasfer to you the ;little JSF experience I have.
I'm pretty happy with JSF as it is but it sure needs improvements. :) What the heck, it's version 1.01 after all, and the next release should be a great one with the integration of JSTL.
Cheers
Maybe you are looking for
-
HI all pls give me diff btwn upload ws_upload and GUI Upload
HI All, pls give me difference between upload ws_upload and GUI Upload Thanks & regards . Bharat Kumar
-
How to monitor USER transactions
Hi Experts In Portal are there any chances to maintain user based on company codes. Is there any possibility to monitor the Portal USER activities (what are the transactions or reports & etc). Points will be revert back. Rgds Priya
-
A question on a build method in a Binary Tree Program
So I'm working on making 20 Questions in java and I'm supposed to make a construct that calls a build method. I'll post my code as I have it so far. The game is supposed to work so that there's an original question and then if the user selects yes, t
-
Error while generating new proxy-client
Hi, I'm trying to generate a proxy-client from the following WSDL file: https://www.anlagenkataster.de/opencms/services/ZuesService?wsdl=1.1 Unfortunately the generation aborts everytime I try saying: "Exception occurred in library handler Incorrect
-
UTL_SMTP mail with attachment( Problem in attaching zip file)
Hi All, I used the below code for sending email with attachment. but when i try to add the message body its not working in the sense its not attaching my file. when i commented that line its attaching the file. commented lines: -- utl_smtp.write_data