Adding actionlistener to menuItem
hi...i'm trying to add an actionListener to a menuItem. i looked at the tutorial on "how to use menus" but i cant seem to execute the menuitem. here's my code...
public class Controller implements ActionListener
GUI gui;
public Controller(GUI g)
gui = g;
gui.menuItem.addActionListener(this);
public void actionPerformed(ActionEvent e)
gui.menuItem = (JMenuItem)(e.getSource());
if (gui.menuItem.getText().equals("New Database"))
System.out.println("Hello");
}where the class GUI is where the menItems have been added to the menus. i'm just trying out for one menuItem first but i wont get the "hello" printed on the screen...can someone give me some assistance on this given that i havent used JMenuItems before...thx in advance...
As carnickr said we really need the source from GUI to be able to help you more. Even without looking at GUI it's apparent that you're methodology is lacking. Depending on design and requirements I can think of many different ways you might need to handle menu item actions. I can't think of a single one that would involve comparing the text, which is what you're doing.
First of all, adding a listener to a public field of a different class is inherently the product of a flawed design or bad design itself. Your code should look more like this:
JMenuItem newDatabase = new JMenuItem("New Database");
JMenuItem openDatabase = new JMenuItem("Open Database");
JMenuItem closeDatabase = new JMenuItem("Close Database");
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == newDatabase) {
System.out.println("New database clicked");
} else if (e.getSource() == openDatabase) {
System.out.println("Open database clicked");
} else fi (e.getSource() == closeDatabase) {
System.out.println("Close database clicked");
newDatabase.addActionListener(listener);
openDatabase.addActionListener(listener);
closeDatabase.addActionListener(listener);Obviously an anonymous class is not always appropriate. The important thing here is that you're comparing the reference to see if it's the same Object, not trying to compare the text. If you post GUI and a little more about what you're trying to do we can try and give you some pointers on how to design it better.
Similar Messages
-
Added actionListener, then GUI broke
Hi,
1. first i ran my menu GUI, it worked fine
2. then i added the actionListener code... now she no workie...
what did i do wrong???
ERROR MSG:
C:\jLotto\LotFrame.java:34: cannot resolve symbol
symbol : class ActionListener
location: class LottoFrame
new ActionListener(){
^
1 error
Tool completed with exit code 1
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import java.awt.Event;
import javax.swing.JOptionPane; //print menu trial run
public class LotFrame extends JFrame
// Constructor
public LotFrame(String title)
setTitle(title); // Set the window title
setDefaultCloseOperation(EXIT_ON_CLOSE); // handle exit operation
setJMenuBar(menuBar); // Add the menu bar to the window
//MAIN MENU
JMenu fileMenu = new JMenu("File"); // Create File menu
JMenu findMenu = new JMenu("Find");
// Construct the file pull down menu
newItem = fileMenu.add("New"); // Add New item
openItem = fileMenu.add("Open"); // Add Open item
closeItem = fileMenu.add("Close"); // Add Close item
fileMenu.addSeparator(); // Add separator
saveItem = fileMenu.add("Save"); // Add Save item
saveAsItem= fileMenu.add("Save As..."); // Add Save As item
fileMenu.addSeparator(); // Add separator
printItem.addActionListener(
new ActionListener(){
public void actionPerformed( ActionEvent e )
JOptionPane.showMessageDialog( LotFrame.this,
"adding actionListener at end of GUI setup",
"action at end", JOptionPane.PLAIN_MESSAGE);
}//end of actionPerformed
}//end of actionLinstener
);//endof .addActionListener
printItem = fileMenu.add("Print"); // Add Print item
menuBar.add(fileMenu); // Add the file menu
menuBar.add(findMenu);
}//end of constructor
private JMenuBar menuBar = new JMenuBar(); // Window menu bar
// File menu items
private JMenuItem newItem, openItem, closeItem, saveItem, saveAsItem, printItem;
}//end of class LotFramejava.awt.event.*;
import java.awt.Event; -
Adding actionListener to JComboBox
Hi there
I have added actionListener to a JComboBox. I only want the actionPerformed() get called when the user choose the item in the JComboBox, however, it also get called whenever I change the items in the JComboBox.
I have tried to call the ActionEvent.getID() method to identify the action, however, changing the items and choosing the item give me the same ID - 1001.
Has anyone got this problem before? How did you solve it?
Should I use other Listener for listening only the choosing event?
In advance thanks!
From
EdmondI had many problems using actionListeners with JComboBox because it gets called all the time, I have had much better luck using mouseListener and the events getClickCount() method for single and double click selections, this avoided many of the problems for me.
-
Adding actionlistener to JTextArea
I'm trying to add an actionListener to my JTextArea, so that when the user hits 'enter', the action occurs.
sort of like this:
JTextArea.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ??????) {
doSomethingToTextArea();
but I'm having problems (e.g. how to make enter the action event, and some problem that says JTextArea can't use actionlisteners???)
any ideas?
thanks,
n00bProgrammerLike serveral of the more complex swing gadgets the JTextarea uses model/view architecture. In this case the model behind the textarea is a Document, and the text change listener needs to be added to the Document, not the gadget itself. i.e. area.getModel().addDocumentListener();
However JTextArea still inherits the methods of java.awt.Component including addKeyListener(); -
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...");
} -
Adding actionListener to a button
pls i want to create an applet with buttons rectangle,circle,and polygon and having a textArea.when someone clicks on the rectangle buttons it draws a rectangle,on the circle buttons it draws a circle and on the polygon button it draws a polygon.pls i have already created the user interface how do i add the actionListeners to the respective buttons and reggister them.
Hi,
try something like this:
JButton jButton1 = new JButton("yourbutton");
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
someMethodThatDoesWhatYouNeed();
});this is just a way to do it, there are other ways, just look around in the forum to discover them.
JoY?TiCk -
Adding ActionListener to JPanel or equivalent
Hi all.
I am trying to add an actionListener for mouse clicks on a JPanel, ideally using something like this:
panel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
//do something
});However, JPanel does not implement addActionListener, and as far as I can see the only components which do are buttons, radio buttons and the like.
I tried extending JPanel to implement ActionListener, but had no success.
Is there an easy way to monitor for mouse clicks on a JPanel or container? Bearing in mind there will be several of these containers at different locations, so using a global mouse listener would not be useful.
ThanksHi all.
I am trying to add an actionListener for mouse clicks
on a JPanel, ideally using something like this:
panel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
//do something
});owever, JPanel does not implement addActionListener,
and as far as I can see the only components which do
are buttons, radio buttons and the like.
I tried extending JPanel to implement ActionListener,
but had no success.
Is there an easy way to monitor for mouse clicks on a
JPanel or container? Use a MouseListener.
Bearing in mind there will be
several of these containers at different locations,
so using a global mouse listener would not be
useful.So add individual MouseListeners to each container.
>
Thanks -
Adding actionListener to JOptionPane
how do you add an actionListener to a JOptionPane?
im using JOptionPane.showMessageDialog, and i want an event to happen when the user clicks on the "Okay" buttonCan you do something like this instead? Use a showConfirmDialog(...) istead of the showMessageDialog(...), then use the return value to determine which button the user pushed?
int retValue = JOptionPane.showConfirmDialog(parent, message, Title, JOptionPane.OK_CANCEL_OPTION );
if (retValue == JOptionPane.OK_OPTION)
doOkayEvent();
else
doNotOkayEvent(); -
Trouble adding actionlistener to a panel in a tabbed pane
Hi, please help me! this is the code i wrote, with the error given below:
CODE:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class tabslisten extends JApplet
JPanel RecPanel;
GridBagLayout gbl;
GridBagConstraints gbc;
public void init ()
FlowLayout flow;
flow = new FlowLayout();
Container content = getContentPane();
content.setLayout(new GridLayout());
JTabbedPane tabpane = new JTabbedPane();
content.add(tabpane, flow);
RecPanel = new JPanel();
recipientDetails();
tabpane.addTab("Recipient Details", null, RecPanel, "Recipient Details");
public void recipientDetails()
JLabel lblRecFName;
JLabel lblRecLName;
JTextField txtRecFName;
JTextField txtRecLName;
JButton btnValidate;
gbl = new GridBagLayout();
gbc = new GridBagConstraints();
RecPanel.setLayout(gbl);
lblRecFName = new JLabel("First Name");
lblRecLName = new JLabel("Last Name");
txtRecFName = new JTextField(8);
txtRecLName = new JTextField(5);
btnValidate= new JButton("Validate");
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.gridx = 1;
gbc.gridy = 8;
gbl.setConstraints(lblRecFName, gbc);
RecPanel.add(lblRecFName);
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.gridx = 4;
gbc.gridy = 8;
gbl.setConstraints(txtRecFName, gbc);
RecPanel.add(txtRecFName);
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.gridx = 1;
gbc.gridy = 11;
gbl.setConstraints(lblRecLName, gbc);
RecPanel.add(lblRecLName);
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.gridx = 4;
gbc.gridy = 11;
gbl.setConstraints(txtRecLName, gbc);
RecPanel.add(txtRecLName);
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.gridx = 4;
gbc.gridy = 32;
gbl.setConstraints(btnValidate, gbc);
RecPanel.add(btnValidate);
validateAction validateButton = new validateAction();
btnValidate.addActionListener(validateButton);
class validateAction implements ActionListener
public void actionPerformed(ActionEvent evt)
Object obj = evt.getSource();
if (obj == btnValidate)
String fName = txtRecFName.getText();
String lName = txtRecLName.getText();
if (fName.length()==0)
getAppletContext().showStatus("First Name not entered.");
return;
else if (lName.length()==0)
getAppletContext().showStatus("Last Name not entered.");
return;
else
getAppletContext().showStatus("Successful.");
ERROR:
tabslisten.java:90: Undefined variable: btnValidate
if (obj == btnValidate)
^
tabslisten.java:92: Undefined variable or class name: txtRecFName
String fName = txtRecFName.getText();
^
tabslisten.java:93: Undefined variable or class name: txtRecLName
String lName = txtRecLName.getText();
^
3 errors
Press any key to continue...
I'm sure I'm doing something really stupid, but I don't know what! ANY and ALL help will be appreciated! Thanks!I copied your program and ran it. It works fine. Make sure the three variables you made class variables are only defined in one place. (ie you moved them not copied them). Other than that I have no ideas.
With regards to naming conventions. My only comment is, take a look at the Java API.
1) classes have uppercased words. Examples from your program - JTextField, Container, FlowLayout, GridLayout...
2) methods and variable names don't upper case the first word - getContentPane(), setLayout()...
Here is the program that works for me:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FirstApplet extends JApplet
JPanel RecPanel;
GridBagLayout gbl;
GridBagConstraints gbc;
JTextField txtRecFName;
JTextField txtRecLName;
JButton btnValidate;
public void init ()
System.out.println("hello there");
FlowLayout flow;
flow = new FlowLayout();
Container content = getContentPane();
content.setLayout(new GridLayout());
JTabbedPane tabpane = new JTabbedPane();
content.add(tabpane, flow);
RecPanel = new JPanel();
recipientDetails();
tabpane.addTab("Recipient Details", null, RecPanel, "Recipient Details");
public void recipientDetails()
JLabel lblRecFName;
JLabel lblRecLName;
gbl = new GridBagLayout();
gbc = new GridBagConstraints();
RecPanel.setLayout(gbl);
lblRecFName = new JLabel("First Name");
lblRecLName = new JLabel("Last Name");
txtRecFName = new JTextField(8);
txtRecLName = new JTextField(5);
btnValidate= new JButton("Validate");
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.gridx = 1;
gbc.gridy = 8;
gbl.setConstraints(lblRecFName, gbc);
RecPanel.add(lblRecFName);
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.gridx = 4;
gbc.gridy = 8;
gbl.setConstraints(txtRecFName, gbc);
RecPanel.add(txtRecFName);
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.gridx = 1;
gbc.gridy = 11;
gbl.setConstraints(lblRecLName, gbc);
RecPanel.add(lblRecLName);
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.gridx = 4;
gbc.gridy = 11;
gbl.setConstraints(txtRecLName, gbc);
RecPanel.add(txtRecLName);
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.gridx = 4;
gbc.gridy = 32;
gbl.setConstraints(btnValidate, gbc);
RecPanel.add(btnValidate);
validateAction validateButton = new validateAction();
btnValidate.addActionListener(validateButton);
class validateAction implements ActionListener
public void actionPerformed(ActionEvent evt)
Object obj = evt.getSource();
if (obj == btnValidate)
String fName = txtRecFName.getText();
String lName = txtRecLName.getText();
if (fName.length()==0)
getAppletContext().showStatus("First Name not entered.");
return;
else if (lName.length()==0)
getAppletContext().showStatus("Last Name not entered.");
return;
else
getAppletContext().showStatus("Successful."); -
Adding Actionlistener to a cell in a JTable?
is this possible? how would i go among doing this?
use the ListSelectionListener.
In "valueChanged(ListSelectionEvent e)" you get the row with "e.getFirstIndex()". -
Attachment Problem in JavaMail API
Can anybody help me...
when 'm trying to attach a file to a mailing aplication(sending attachment),
an flurry of exceptions are occuring...
'm using win98 and JDK1.4
here is the code..can anybody provide a viable solution that works?
thanks in advance
* main1.java
* Created on August 20, 2002, 2:55 PM
* @author Shamik Ghosh
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.net.*;
import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class main1 extends javax.swing.JFrame implements ActionListener,ItemListener {
JMenuBar mbar;
JMenu file,other,help;
JMenuItem open,save,read_mail;
JFrame frame_f;
FileReader fr;
BufferedReader br;
boolean check;
String from_m,smtp_m,from_m1,smtp_m1,result,
s1,s2,from_server,from_host,to_file,which_file,attach_text;
File f;
/** Creates new form main1 */
public main1() {
initComponents();
setSize(550,500);
setResizable(false);
// ------------------------centering the display
int width=550; // note that "width" & "height" are keywords and
int height=500; // JAVA defined variables.
Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();
int x=(screen.width-width)/2;
int y=(screen.height-height)/2;
setBounds(x,y,width,height);
try{
fr=new FileReader("address.txt");
br=new BufferedReader(fr);
String s;
while((s=br.readLine()) !=null)
{jComboBox1.addItem(s);}
fr.close();
}catch(Exception e){ System.out.println(e);}
check_info();//calling the method to check the info
//jTextField1.setText(from_m);
//jTextField3.setText(smtp_m);
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
private void initComponents() {//GEN-BEGIN:initComponents
buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup2 = new javax.swing.ButtonGroup();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jTextField3 = new javax.swing.JTextField();
jComboBox1 = new javax.swing.JComboBox();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
jRadioButton3 = new javax.swing.JRadioButton();
jRadioButton4 = new javax.swing.JRadioButton();
jButton4 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jTextField4 = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea2 = new javax.swing.JTextArea();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
//actionlisteners
jButton1.addActionListener(this);
jButton2.addActionListener(this);
jButton3.addActionListener(this);
jButton4.addActionListener(this);
jButton5.addActionListener(this);
jButton6.addActionListener(this);
mbar=new JMenuBar();
setJMenuBar(mbar);
file=new JMenu("File");
other=new JMenu("Other");
help=new JMenu("Help");
mbar.add(file);
mbar.add(other);
mbar.add(help);
getContentPane().setLayout(null);
setTitle("MailMan :Designed and Programmed by Shamik Ghosh");
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
jLabel1.setText("From:");
getContentPane().add(jLabel1);
jLabel1.setBounds(30, 20, 32, 17);
jLabel2.setText("To:");
getContentPane().add(jLabel2);
jLabel2.setBounds(30, 60, 17, 17);
getContentPane().add(jTextField1);
jTextField1.setBounds(110, 20, 240, 21);
getContentPane().add(jTextField2);
jTextField2.setBounds(110, 60, 240, 21);
jLabel3.setText("Smtp Server:");
getContentPane().add(jLabel3);
jLabel3.setBounds(10, 100, 74, 17);
getContentPane().add(jTextField3);
jTextField3.setBounds(110, 100, 240, 21);
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { }));
jComboBox1.setToolTipText("Mail Addresses");
jComboBox1.setAutoscrolls(true);
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
getContentPane().add(jComboBox1);
jComboBox1.setBounds(110, 150, 240, 20);
jComboBox1.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
jButton1.setToolTipText("Send the message you have typed");
jButton1.setMnemonic('m');
jButton1.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
jButton1.setText("Send Mail");
getContentPane().add(jButton1);
jButton1.setBounds(370, 300, 160, 25);
//jButton2.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 12));
jButton2.setText("Save Info");
jButton2.setToolTipText("Save Settings for more mails");
jButton2.setMnemonic('I');
getContentPane().add(jButton2);
jButton2.setBounds(370, 340, 160, 25);
jButton3.setText("Clear ");
jButton3.setMnemonic('C');
jButton3.setToolTipText("Clear all text");
getContentPane().add(jButton3);
jButton3.setBounds(370, 380, 160, 27);
jLabel4.setText("Your Contact Addresses");
jLabel4.setFont(new java.awt.Font("Arial Narrow", 0, 12));
getContentPane().add(jLabel4);
jLabel4.setBounds(110, 130, 200, 15);
jRadioButton3.setText("Use Log File");
jRadioButton3.setMnemonic('L');
getContentPane().add(jRadioButton3);
jRadioButton3.setBounds(260, 310, 90, 25);
jRadioButton4.setText("No Log File");
//jRadioButton4.setMnemonic('N');
//getContentPane().add(jRadioButton4);
//jRadioButton4.setBounds(260, 340, 86, 25);
jButton4.setText("Undo Info");
jButton4.setMnemonic('U');
jButton4.setToolTipText("Undo settings");
getContentPane().add(jButton4);
jButton4.setBounds(260, 380, 87, 27);
getContentPane().add(jTextField4);
jTextField4.setBounds(20, 380, 210, 21);
jLabel5.setText("Attachment");
jLabel5.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
getContentPane().add(jLabel5);
jLabel5.setBounds(70, 360, 70, 15);
jButton5.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
jButton5.setText("Browse");
jButton5.setMnemonic('B');
jButton5.setToolTipText("Browse files for Attachment");
getContentPane().add(jButton5);
jButton5.setBounds(150, 350, 80, 25);
jButton6.setText("Attach & Send");
jButton6.setMnemonic('A');
jButton6.setToolTipText("Attach File & Send Mail");
getContentPane().add(jButton6);
jButton6.setBounds(260, 340, 86, 25);
jScrollPane1.setViewportView(jTextArea1);
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(370, 20, 160, 270);
jLabel10.setText("Type your mail:");
jLabel10.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
getContentPane().add(jLabel10);
jLabel10.setBounds(370, 5, 125, 10);
jScrollPane2.setViewportView(jTextArea2);
getContentPane().add(jScrollPane2);
jScrollPane2.setBounds(20, 200, 340, 90);
jLabel6.setText("(your ISP smtp)");
jLabel6.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 10));
getContentPane().add(jLabel6);
jLabel6.setBounds(10, 120, 70, 12);
jLabel7.setText("porgrammed and designed by : Shamik Ghosh");
jLabel7.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 10));
getContentPane().add(jLabel7);
jLabel7.setBounds(260, 410, 160, 12);
jLabel8.setText("[email protected]");
jLabel8.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 10));
getContentPane().add(jLabel8);
jLabel8.setBounds(420, 410, 80, 12);
jLabel9.setText("Msg.for the Mail Sent:");
jLabel9.setForeground(java.awt.Color.black);
jLabel9.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 10));
getContentPane().add(jLabel9);
jLabel9.setBounds(20, 180, 80, 12);
file.add(open=new JMenuItem("Open"));
open.setAccelerator(KeyStroke.getKeyStroke('O',Event.CTRL_MASK,true));
file.addSeparator();
file.add(save=new JMenuItem("Save"));
save.setAccelerator(KeyStroke.getKeyStroke('S',Event.CTRL_MASK,true));
file.addSeparator();
other.add(read_mail=new JMenuItem("Add Address"));
read_mail.setAccelerator(KeyStroke.getKeyStroke('A',Event.CTRL_MASK,true));
other.addSeparator();
//adding actionListener to menuitems
open.addActionListener(this);
save.addActionListener(this);
read_mail.addActionListener(this);
jComboBox1.addItemListener(this);
pack();
}//GEN-END:initComponents
public void itemStateChanged(ItemEvent ie)
String add_list;
add_list=String.valueOf(jComboBox1.getSelectedItem());
jTextField2.setText(add_list);
} // for item event source
public void actionPerformed(ActionEvent ae)
if(ae.getSource()==jButton1)
if(ae.getSource()==jButton1) {
SwingUtilities.invokeLater(new Runnable()
{ public void run()
sendMail();
if(ae.getSource()==jButton2) //save info
from_m =jTextField1.getText();
smtp_m =jTextField3.getText();
from_m1 =from_m+"\n";
smtp_m1 =jTextField3.getText();
result =from_m1+smtp_m1;
try{
byte buf[]=result.getBytes();
OutputStream fo=new FileOutputStream("info.txt");
for(int i=0;i<buf.length; i++ )
fo.write(buf);
fo.close();
}catch(Exception e){ System.out.println(e);}
jTextField1.setEditable(false);
jTextField3.setEditable(false);
if(ae.getSource()==jButton3) //clear
jTextArea1.setText(" ");
jTextArea2.setText(" ");
if(ae.getSource()==jButton4)//undo info
jTextField1.setEditable(true);
jTextField3.setEditable(true);
if(ae.getSource()==jButton5)//browse for attachment
try {
FileDialog file = new FileDialog (main1.this, "Load File", FileDialog.LOAD);
file.setFile ("*.*"); // Set initial filename filter
file.show(); // Blocks
String curFile;
if ((curFile = file.getFile()) != null) {
String filename = file.getDirectory() + curFile;
char[] data;
setCursor (Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
f = new File (filename);
try {
System.out.println("INSIDE TRY");
FileReader fin = new FileReader (f);
int filesize = (int)f.length();
data = new char[filesize];
fin.read (data, 0, filesize);
setCursor (Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
} catch (Exception exc) {}
jTextField4.setText(filename);
} catch(Exception e){}
if(ae.getSource()==jButton6)//send attachment & Mail
try{
sendmail2();
}catch(Exception e){}
if(ae.getSource()==open)//menu open
if(ae.getSource()==save)//menu save
if(ae.getSource()==read_mail)//menu read_mail
address_add();
} //actionperformed
public void sendmail2()
try {
//which_file,attach_text
from_server=jTextField3.getText();
from_host=jTextField1.getText();
to_file=jTextField2.getText();
which_file=jTextField4.getText();
attach_text=jTextArea1.getText();
//getting system property
Properties props=System.getProperties();
//setup mail server
props.put("mail.smtp.host",from_server);
//get session
Session session=Session.getInstance(props,null);
// Define message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from_host));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to_file));
message.setSubject("Hello JavaMail Attachment");
//define message part
BodyPart messageBodyPart=new MimeBodyPart();
// Fill the message
messageBodyPart.setText(attach_text);
// Create a Multipart
Multipart multipart = new MimeMultipart();
// Add part one
multipart.addBodyPart(messageBodyPart);
//attaching**********************************secon Part Attachment
//creating second body part
messageBodyPart=new MimeBodyPart();
DataSource source=new FileDataSource(which_file); //was filename
//setting data handler to the attachment
messageBodyPart.setDataHandler(new DataHandler(source));
//setting the filename
messageBodyPart.setFileName(which_file);
//adding part two
multipart.addBodyPart(messageBodyPart);
//put parts in the message
message.setContent(multipart);
//Sending msg
Transport.send(message);
}catch(Exception e){}
} //sendmail2
public void address_add()
addr=jTextField2.getText();
str_addr=addr+"\n";
//jComboBox1.addItem(" ");
jComboBox1.addItem(addr);
System.out.println("INSIDE WRITING METHOD");
try{
byte buf[]=str_addr.getBytes();
OutputStream f0=new FileOutputStream("address.txt",true);
for(int i=0;i<buf.length; i++ )
f0.write(buf[i]);
f0.close();
}catch(Exception e){ System.out.println(e);}
public void check_info()
try{
fr=new FileReader("info.txt");
br=new BufferedReader(fr);
while((s1=br.readLine()) !=null && (s2=br.readLine()) !=null)
jTextField1.setText(s1);
jTextField3.setText(s2);
break;
fr.close();
}catch(Exception e){ System.out.println(e);}
public void sendMail()
{ try
Socket s = new Socket(jTextField3.getText(), 25);
out = new PrintWriter(s.getOutputStream());
in = new BufferedReader(new
InputStreamReader(s.getInputStream()));
String hostName
= InetAddress.getLocalHost().getHostName();
send(null);
send("Host " + hostName);
send("Mail FROM: " + jTextField1.getText());
send("Rcpt TO: " + jTextField2.getText());
send("Data");
out.println(jTextArea1.getText());
send(".");
s.close();
catch (IOException exception)
{ jTextArea2.append("Error: " + exception);
String err="Message cannot be sent!"+"\n"
+"Please verify the setting(s)."+
"\n"+"Else there may be a NetWork Problem."+
"\n"+"Please verify and Try Again.";
JOptionPane.showMessageDialog(frame_f,err,"Message Transmission Failure",JOptionPane.ERROR_MESSAGE);
public void send(String s) throws IOException
{ if (s != null)
{ jTextArea2.append(s + "\n");
out.println(s);
out.flush();
String line;
if ((line = in.readLine()) != null)
jTextArea2.append(line + "\n");
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
// Add your handling code here:
}//GEN-LAST:event_jComboBox1ActionPerformed
/** Exit the Application */
private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
System.exit(0);
}//GEN-LAST:event_exitForm
* @param args the command line arguments
public static void main(String args[]) {
new main1().show();
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JLabel jLabel3;
private javax.swing.JTextField jTextField3;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel4;
private javax.swing.JRadioButton jRadioButton3;
private javax.swing.JRadioButton jRadioButton4;
private javax.swing.JButton jButton4;
private javax.swing.JTextField jTextField4;
private javax.swing.JLabel jLabel5;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea jTextArea2;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JLabel jLabel10;
private BufferedReader in;
private PrintWriter out;
private String addr,str_addr;
// End of variables declaration//GEN-END:variablesHi I have this problem which I believe you can help me resolve:
In my code, there are two lines:
message.setContent(messageBody, "text/html"); // this sets body of message
message.setContent(bodyPartObject); // this attaches a file
but it turns out that the second "setContent" statement over-writes the first one, so that I get no message in the body of the mail.
What can I do about it, shamik1? Thanks! -
Hi,
Is there a way to give to a menuitem a diferent reation while diferent forms are activated without adding/removing the menuitem or the ActionListener each time i swap the form?Define the "reaction" in the form. So your menu item code would look something like:
activeForm.reaction(); -
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 -
How to set icon on MenuItem, but not in JMenuItem?
saleemtol003 wrote:
You are right.It's not possible to set icon on menuItem.
I am talking about SystemTray in which I added PopupMenu with MenuItem.
but I need MenuItem with icon.Is there another way to solve this problem?Nope, just because you're adding a PopupMenu to a TrayIcon does not change the fact that MenuItems cannot have icons. -
Bug? Unable to add ActionListener using Anonymous class.
Hi,
I come accross one strange behaviour while adding ActionListener to RCF component.
I am trying to add the ActionListener in the managed bean using the Anonymous.
We can add the actionListener to a button using following methods. I am talking about the the first case. Only this case is not working. Rest other 2 cases are working properly.
Case 1:
class MyClass {
RichCommmandButton btnTest = new RichCommmandButton();
public MyClass(){
btnTest.addActionListener(new ActionListener(){
public void processAction(ActionEvent event){
Case 2:
class MyClass implements ActionListener {
RichCommmandButton btnTest = new RichCommmandButton();
public void processAction(ActionEvent event){
<af:button binding="#{myClassBean.btnTest}" actionListener="#{myClassBean.processAction}"/>
Case 3:
class MyClass implements ActionListener {
RichCommmandButton btnTest = new RichCommmandButton();
public void addActionLister(){
//Use EL to add processAction(). Create MethodBinding
FacesContext facesContext = FacesContext.getCurrentInstance();
ELContext elContext = facesContext.getELContext();
ExpressionFactory exprfactory = facesContext.getApplication().getExpressionFactory();
MethodExpression actionListener =
exprfactory.createMethodExpression(elContext, "#{myClassBean.processAction}", null, new Class[] { ActionEvent.class });
btnTest.setActionListener(actionListener);
public void processAction(ActionEvent event){
Java has provided good way to use the Anonymous classes while adding the listeners. It should work with the RCF also.
Some how i found the case 1 usefull, as i can have as many buttons in my screen and i can add the actionListener in one method. Also it is easy to read. I dont have to see the JSPX page to find the associated actionListener method.
Is it a bug or i am wrong at some point?
Any sujjestions are welcome.
- Sujay.Hello Sujay,
As I said in my previous reply, you can try with request scope. In JSF you shouldn't use the binding attribute very often. I agree that anonymous class is nice, but don't forget that you might be dealing with client state saving here so it cannot be perfectly compared with Swing that maintains everything in RAM. What I think happens with you currently is the following:
1. Bean is created and the button instance as well. The ActionListener is added to the button;
2. The view is rendered and while it is, the binding attribute is evaluated, resulting in the get method of your bean being called;
3. Since the method returns something different than null, the button instance created in 1. get used in the component tree;
4. The tree's state is saved on the client, since your class isn't a StateHolder, nor Serializable, the StateManager doesn't know how to deal with it so it gets discarded from the saved state and maybe from the component itself (would have to debug the render view phase to be sure);
5. The postback request arrives, the tree is restored. When the handler reaches the button, it call the bean that returns the same instance that was used in the previous tree (since not request scoped), which is BAD because the remaining of the tree is not made of the same object instances, but rather new deserialized ones. The component then gets updated from the client state saved in 4, this might also be where the listener get removed (again debugging would tell you this, but I would tend more with the previous possibility). Note that with a request scoped bean you would have to add the listener during the first get method call (by checking if the component is null) or in the constructor as you're doing right now. It would be a very clean way and you could give the request bean (and thus the listener) access to the conversation scoped bean through injection which is very nice as well.
6. The invoke application phase occurs and the listener is no longer there.
Btw, this isn't a rich client issue, more a specification one. I'm curious if it works in a simple JSF RI application, if it does then I guess it would be a bug in Trinidad and/or rich client state handling architecture (using FacesBean).
Regards,
~ Simon
Maybe you are looking for
-
I am using Lion and everything was working fine -- until I got a new mac and set the older one up for my husband and put his user account on the old mac. Now I can send ical invitations out and can get replies -- but if someone else originiates an in
-
Nano video output via headphone socket?
Can the new Nano video output to the TV via the headphone socket, like my iPod Video 80g? Thanks.
-
Inventory Management: Blocked stock coming up in OnHand
Hello Experts - We've implemented 2LIS_03_BF for our inventory management reports. However, the OnHand quantity is also picking up Blocked quantity. I used the same code as given by SAP. For a material, the OnHand quantity is 13 in our reports when t
-
IPod completely blanks out!!
My iPod Nano that I got in 2007 has been working completely fine until today, when I went to turn it on and nothing happened. I plugged it into the computer, which wouldnt regonize it at first, then after about 10 minutes told me that my iPod had bee
-
Sending word 2007 file in email
Hi All. I am trying to send a word 2007 (docx) file in email (via BCS). All other formats like PDF, DOC etc work perfectly fine. But DOCX gives me junk characters. I have tried to send the attachment in BIN, DOC, DOCX, RAW formats, but all have faile