ActionListener as an innerclass
I am unsure when I should make ActionListener an inner class and when I should implement ActionListener. Which is better or does it depend? RIght now I have it as an inner class.
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button 1 was clicked");
I was thinking of making GUI components that aggregate
some GUI primitives such as textfields and labels.
Those GUI components would listen to the events
generated by their primitives and in turn launch
"higher level" events to the actual Controller. Would
you advise against that?No. That sounds perfectly sensible. I think it's OK to put things that only the GUI cares about in ActionaListeners. For example I don't see any harm in putting a close listener in a GUI if there's nothing else that cares about that event. If I understand you correctly I've done that and I think it works very well. I actually think it makes sense to convert GUI events into meaningful business events. Instead of 'menu action performed' I would fire a event contains a clear message like 'new file selected'. For small components this can all be done as inner classes but when the Component gets large, I find it's better to break things down. You might just have one class that manages these things per component or less.
Take for example a search component that is basically
a label and a textfield and maybe a button, they would
be put on a Panel (not a swing Panel, but the
framework is swing'ish even though it's a webapp)
which would then send a searchEvent to my top level
controller.Sounds good.
Just thinking of ways to save my project that has
already been butchered by my co-workers...
(You wouldn't believe it, comparing strings with ==,
using the String copy constructor, using different
brace styles depending on their mood I guess...)Check out this gem I found is some code yesterday:
String value = map.get(key);
if (!value.equals(null))
else
}
Similar Messages
-
InnerClass Actionlistener problem
hello,
i am stuck on this piece of code and i think somebody here will be able to help me out :).
i have these classes.
ButtonPanel, Test.
in the buttonpanel i have a few buttons, but the actionlistener is an innerClass in Test.
when i want to add one of my actionlisteners in my ButtonPanel class the compiler cannot resolve symbol.
this is a snippet of code:
the buttons in buttonpanel class:
btnStart = new JButton("Start");
btnStart.addActionListener(new startActionListener());
btnStop = new JButton("Stop");
btnStop.addActionListener(new stopActionListener());
btnTest = new JButton("Test");
btnTest.addActionListener(new testActionListener());
The actionlisteners in Test class:
public class startActionListener implements ActionListener{
public void actionPerformed(ActionEvent e){
java.awt.Toolkit.getDefaultToolkit().beep();//werkt niet
public class stopActionListener implements ActionListener{
public void actionPerformed(ActionEvent e){
java.awt.Toolkit.getDefaultToolkit().beep();//werkt niet
public class testActionListener implements ActionListener{
public void actionPerformed(ActionEvent e){
java.awt.Toolkit.getDefaultToolkit().beep();//werkt niet
so basically its just how do use actionlisteners in the class that extends from the JFrame, in stead of in de ButtonPanel class where the buttons are?There are several options.
If the classes don't at all refer to the class their nested in (as your examples seem to be), then just make them top-level, and refer to them anywhere you want.
Or you could create anonymous inner classes, with identical functonality, in your ButtonPanel.
Or you could add the listeners in a different place (say in a method of Test).
The way you should go, depends on the details of the implementation.
When you post code, please wrap it in [code][/code] tags. -
Actionlistener in different class then the button
hello,
i am stuck on this piece of code and i think somebody here will be able to help me out :).
i have these classes.
ButtonPanel, Test.
in the buttonpanel i have a few buttons, but the actionlistener is an innerClass in Test.
when i want to add one of my actionlisteners in my ButtonPanel class the compiler cannot resolve symbol.
this is a snippet of code:
the buttons in buttonpanel class:
btnStart = new JButton("Start");
btnStart.addActionListener(new startActionListener());
btnStop = new JButton("Stop");
btnStop.addActionListener(new stopActionListener());
btnTest = new JButton("Test");
btnTest.addActionListener(new testActionListener());The actionlisteners in Test class:
public class startActionListener implements ActionListener{
public void actionPerformed(ActionEvent e){
java.awt.Toolkit.getDefaultToolkit().beep();//werkt niet
public class stopActionListener implements ActionListener{
public void actionPerformed(ActionEvent e){
java.awt.Toolkit.getDefaultToolkit().beep();//werkt niet
public class testActionListener implements ActionListener{
public void actionPerformed(ActionEvent e){
java.awt.Toolkit.getDefaultToolkit().beep();//werkt niet
}so basically its just how do use actionlisteners in the class that extends from the JFrame, in stead of in de ButtonPanel class where the buttons are?URgent help need.
i need to link the page together : by clicking the button on the index page.
it will show the revelant class file. I have try my ationPerformed method to the actionlistener, it cannot work.
Thanks in advance.
// class mtab
// the tab menu where it display the gui
import javax.swing.*;
import java.awt.*;
public class mtab {
private static final int frame_height = 480;
private static final int frame_width = 680;
public static void main (String [] args){
JFrame frame = new JFrame ("Mrt Timing System");
frame.setDefaultCloseOperationJFrame.EXIT_ON_CLOSE);
frame.setSize(frame_width,frame_height);
JTabbedPane tp = new JTabbedPane ();
tp.addTab("Mrt Timing System", new sample());
frame.setResizable(false);
frame.getContentPane().add(tp);
frame.setSize(680,480);
frame.show();
// index page
// class sample
import java.awt.*;
import java.awt.event.*;
import java.awt.Image;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.text.*;
import javax.swing.border.*;
class sample extends JPanel implements ActionListener
//button
private JButton TimingButton;
private JButton ViewButton;
private JButton FrequencyButton;
private JButton calculateButton;
private CardLayout mycard;
private JPanel SelectXPanel;
private JPanel SelectYPanel;
private JPanel SelectZPanel;
private JPanel bigFrame, mainPane;
// constructor
public sample() {
super(new BorderLayout());
//create the object
//create button and set it
TimingButton = new JButton("MRT Timing Calculator");
TimingButton.addActionListener(this);
ViewButton = new JButton("View First and Last Train");
ViewButton.addActionListener(this);
FrequencyButton = new JButton("Show the Train Frequency");
FrequencyButton.addActionListener(this);
// Layout
//Lay out the button in a panel.
JPanel buttonPane = new JPanel(new GridLayout(3,0));
buttonPane.add(TimingButton);
buttonPane.add(ViewButton);
buttonPane.add(FrequencyButton);
// Layout the button panel into another panel.
JPanel buttonPane2 = new JPanel(new GridLayout(0,1));
buttonPane2.add(buttonPane);
tfrequency x = new tfrequency();
fviewl2 y = new fviewl2 ();
timing z = new timing ();
JPanel SelectXPanel = new JPanel(new GridLayout(0,1));
SelectXPanel.add(x);
JPanel SelectYPanel = new JPanel(new GridLayout(0,1));
SelectYPanel.add(y);
JPanel SelectZPanel = new JPanel(new GridLayout(0,1));
SelectZPanel.add(z);
// Layout the button by putting in between the rigid area
JPanel mainPane = new JPanel(new GridLayout(3,0));
mainPane.add(Box.createRigidArea(new Dimension(0,1)));
mainPane.add(buttonPane2);
mainPane.add(Box.createRigidArea(new Dimension(0,1)));
mainPane.setBorder(new TitledBorder("MRT Timing System"));
// x = new tfrequency();
// The overall panel -- divide the frame into two parts: west and east.
JPanel bigFrame = new JPanel(new GridLayout(0,2));
bigFrame.add(mainPane, BorderLayout.WEST);
//bigFrame.add(x,BorderLayout.EAST); // this is where i want to link the page
// this page being the index page. there being nothing to display.
add(bigFrame);
//Create the GUI and show it. For thread safety,
public void actionPerformed (ActionEvent e){
if (e.getSource() == TimingButton ){
JPanel bigFrame = new JPanel(new GridLayout(0,2));
bigFrame.add(mainPane, BorderLayout.WEST);
bigFrame.add(SelectZPanel,BorderLayout.EAST);
add(bigFrame);
else if (e.getSource() == ViewButton ){
JPanel bigFrame = new JPanel(new GridLayout(0,2));
bigFrame.add(mainPane, BorderLayout.WEST);
bigFrame.add(SelectYPanel,BorderLayout.EAST);
add(bigFrame);
else if (e.getSource() == FrequencyButton ){
JPanel bigFrame2 = new JPanel(new GridLayout(0,2));
bigFrame.add(mainPane, BorderLayout.WEST);
bigFrame.add(SelectXPanel,BorderLayout.EAST);
add(bigFrame);
// Train Frequency Page
// class fviewl2
import java.awt.*;
import java.awt.event.*;
import java.awt.Image;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.text.*;
import javax.swing.border.*;
class fviewl2 extends JPanel implements ActionListener
//Labels to identify the fields
private JLabel stationLabel;
private JLabel firstLabel;
private JLabel lastLabel;
//Strings for the labels
private static String station = "MRT Station:";
private static String first = "First Train Time:";
private static String last = "Last Train Time:";
//Fields for data entry
private JFormattedTextField stationField;
private JFormattedTextField firstField;
private JFormattedTextField lastField;
//button
private JButton homeButton;
private JButton cancelButton;
private JButton calculateButton;
public fviewl2()
super(new BorderLayout());
//create the object
//Create the Labels
stationLabel = new JLabel(station);
firstLabel = new JLabel (first);
lastLabel = new JLabel (last) ;
//Create the text fields .// MRT Station:
stationField = new JFormattedTextField();
stationField.setColumns(10);
stationField.setBounds(300,300,5,5);
//Create the text fields // First Train Time:
firstField = new JFormattedTextField();
firstField.setColumns(10);
firstField.setBounds(300,300,5,5);
//Create the text fields //Last Train Time:
lastField = new JFormattedTextField();
lastField.setColumns(10);
lastField.setBounds(300,300,5,5);
//Tell accessibility tools about label/textfield pairs, matching label for the field
stationLabel.setLabelFor(stationField);
firstLabel.setLabelFor(firstField);
lastLabel.setLabelFor(lastField);
//create button and set it
homeButton = new JButton("Home");
//homeButton.addActionListener(this);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
calculateButton = new JButton("Get Time");
// Layout
//MRT Station Label // insert into the panel
JPanel StationPane = new JPanel(new GridLayout(0,1));
StationPane.add(stationLabel);
//MRT Station input field // insert into the panel
JPanel StationInput = new JPanel(new GridLayout(0,1));
StationInput.add(stationField);
//Get Time Button // insert into the panel
JPanel GetTime = new JPanel(new GridLayout(0,1));
GetTime.add(calculateButton);
//Lay out the labels in a panel.
JPanel FlabelL = new JPanel(new GridLayout(0,1));
FlabelL.add(firstLabel);
FlabelL.add(lastLabel);
// Layout the fields in a panel
JPanel FFieldL = new JPanel(new GridLayout(0,1));
FFieldL.add(firstField);
FFieldL.add(lastField);
//Lay out the button in a panel.
JPanel buttonPane = new JPanel(new GridLayout(1,0));
buttonPane.add(homeButton);
buttonPane.add(cancelButton);
// Layout all components in the main panel
JPanel mainPane = new JPanel(new GridLayout(4,2));
mainPane.add(StationPane);
mainPane.add(StationInput);
mainPane.add(Box.createRigidArea(new Dimension(0,1)));
mainPane.add(GetTime);
mainPane.add(FlabelL);
mainPane.add(FFieldL);
mainPane.add(Box.createRigidArea(new Dimension(0,1)));
mainPane.add(buttonPane);
mainPane.setBorder(new TitledBorder("View First and Last Train"));
JPanel leftPane = new JPanel(new GridLayout(1,0));
leftPane.add(Box.createRigidArea(new Dimension(0,1)));
leftPane.add(mainPane);
leftPane.add(Box.createRigidArea(new Dimension(0,1)));
JPanel hahaFrame = new JPanel(new GridLayout(0,1));
hahaFrame.add(Box.createRigidArea(new Dimension(0,1)));
hahaFrame.setBorder(BorderFactory.createEmptyBorder(30, 10, 80, 150));
hahaFrame.add(Box.createRigidArea(new Dimension(0,1)));
JPanel bigFrame = new JPanel();
bigFrame.add(hahaFrame, BorderLayout.NORTH);
bigFrame.add(leftPane, BorderLayout.CENTER);
add(bigFrame, BorderLayout.CENTER);
//Create the GUI and show it. For thread safety,
private void cancelButtonClicked()
stationField.setText("");
firstField.setText("");
lastField.setText("");
public void actionPerformed (ActionEvent e){
if (e.getSource() == cancelButton){
cancelButtonClicked();
} -
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!!
-
Passing innerclass name as parameter
Hi,
How i can pass inner class name as parameter which is used to create object of inner class in the receiving method (class.formane(className))
Hope somebody can help me.
Thanks in advance.
PremMake the inner class as a parameter. An outer class object would also be required to create an inner class object.
OuterClass outerClass=new OuterClass();
InnerClass innerClass=outerClass.new InnerClass(); -
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.
Maybe you are looking for
-
Received Error 1602 while updating to 6.1.2
I Was Upgrading to 6.1.2 When Suddenly i Get The Message, Error 1602, Cannot Restore. So I Try Restoring It Again, But The Same Problem Keeps Coming Up. And My Ipod Touch Wont Even Switch On Now. What Do I Do? And Yes, I've Tried Putting It In DFU Mo
-
Object GC'ed out of JNDI?
Folks, We've experienced some bizarre behavior within one of our EJB's and its interactions with JNDI during our performance testing effort. We've developed a theory, and we're currently developing a test case for it, but I wanted to post it here and
-
Hi everyone I have serious problem with facebook app (both, from BB World and Android .bar). After launch, message appears: "Serious problem. Try later" My device is: Z10 STL 100-2 10.2.0.424 OS version: 10.2.0.1791 radio: 10.2.0.1972 webkit: 10.2.0.
-
when i active my mac pro all i get is a white screen and it loading and when it fully load its turn off , and it keep on doing the same thing for hours
-
HT204053 i have an used i phone and don't have the apple id how do i change it
i have an used i phone and don't have the apple id how do i change it