ActionListener of Jbutton Question

Hi there,
I am trying to perform a command via JButton by adding an ActionListener to the frame'instance' of my Pointframe:
public class MainClass {
  public static void main(String[] args)  {
  try {
  byte[] datasend = new byte[50];
  byte[] tempdatareceive= new byte[1000];
  int incomingPackageSize = 0;
  //create instance of GUI
  Pointframe frame = new Pointframe();
  frame.pack();
  frame.show();
  //add Action Listener stuff
      ActionListener SendStream = new ActionListener()
      public void actionPerformed( ActionEvent e ) {
      System.out.println("this works");
  frame.jButton1.addActionListener( SendStream );
  //create Socket to Connect to EmScon-Server
  Socket connectToEsServer = new Socket ("192.168.0.5",700);
  //create Output Stream to send data to Server
  DataOutputStream StreamtoEsServer
  = new DataOutputStream(connectToEsServer.getOutputStream());
  //create Input Stream to send data to Server
  DataInputStream StreamfromEsServer
  = new DataInputStream(connectToEsServer.getInputStream());
................Sending commands like above to the console works fine so far.
But as long as i start to try invoking variable relatedcommands.
public class MainClass {
  public static void main(String[] args)  {
  try {
  byte[] datasend = new byte[50];
  byte[] tempdatareceive= new byte[1000];
  int incomingPackageSize = 0;
  //create instance of GUI
  Pointframe frame = new Pointframe();
  frame.pack();
  frame.show();
  //add Action Listener stuff
      ActionListener SendStream = new ActionListener()
      public void actionPerformed( ActionEvent e ) {
     StreamtoEsServer.write(datasend);
  frame.jButton1.addActionListener( SendStream );
  //create Socket to Connect to EmScon-Server
  Socket connectToEsServer = new Socket ("192.168.0.5",700);
  //create Output Stream to send data to Server
  DataOutputStream StreamtoEsServer
  = new DataOutputStream(connectToEsServer.getOutputStream());
  //create Input Stream to send data to Server
  DataInputStream StreamfromEsServer
  = new DataInputStream(connectToEsServer.getInputStream());
................I receive errmessages like:
"MainClass.java": Error #: 480 : local variable datasend is accessed from within inner class; needs to be declared final
"MainClass.java": Error #: 300 : variable StreamtoEsServer not found in anonymous class of method main(java.lang.String[])
Can please somebody bring light into that?
What is the best way to implement such stuff in general?
Any ideas are greatly appreciated.
Best regards,
stonee

Hi,
try instantiaitng your variable datasend as private variable in the class outside your main-method

Similar Messages

  • Stupid JButton Question

    Really 2 questions
    1) Ive noticed in the tutorials a high level object in which JButton objects are placed all implement ActionListener, and correspondingly implement
    public void actonPerformed(ActionEvent e)
    somewhere
    Ive been going over some code I wrote a while ago (I forgot how to do all this stuff for my new app from then till now) and I noticed I was always doing
    someButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    executeSomeMethod();
    I realize that if all the buttons invoke independent methods it is probably better to use the second method.
    In the application I am currently developing the buttons are used to select parameters for the method invoked. Im thinking the first method might be better -- I am asking if this is the case, and if it is best to follow the tutorials (I was thinking they might be a bit old, so maybe are out of date)
    This leads up to question 2).
    The buttons select which items to remove from an internal list. Each button ids an item. How do I identify the button when the actionPerformed method is invoked? I know about setActionCommand().
    Q 2a is: Is there a better way to id the button? Each Button is associated with a Card (as in a poker deck), so the cards/buttons are IDd by a byte for suite, and a byte for value. I would like to avoid comparing strings if possible.
    Thanx in advance.

    // Action Command can be anything
    JButton[] but = new JButton[totalButtonCount]; // an array could be used (Vector = best)
    for(int x = 0; x < but.length; x++) {
        but[x] = new JButton(buttonText);
        but[x].setActionCommand("but " + x); // a string with the current index
        addButton(but[x], location);
    // So when parsing
    public void actionPerformed(ActionEvent e) {
       Object source = e.getSource();
        if(source instanceof JButton) {
             JButton but = (JButton) source;
            for(int x = 0; x < totalButtonCount; x++) {
                 if(but.getActionCommand().equals(but[x].getActionCommand) );
                     fireButtonAction(but.getActionCommand());
    } Is this of any help?
    ICE

  • ActionListener with JButton and JMenu

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

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

  • Add ActionListener to JButton

    Hi, i am creating some buttons to be added to a grid layouy content pane. The buttons are added like this:
    for (int i = 0; i < 400; i++)
    gamePanel.add(new JButton("" + i));
    How do i add an action listener to each button?

    I don't really understand what your problem is but here goesJPanel gamePanel = new JPanel(new GridLayout(400, 1));
    ActionListener actionListener = new ActionListener() {
         public void actionPerformed(ActionEvent e) {
              Object source = e.getSource();
              if (source instanceof JButton) {
                   System.out.println("button " + ((JButton)source).getText() + " clicked");
    for (int i = 0; i < 400; i++) {
         JButton button = new JButton("" + i);
         button.addActionListener(actionListener);
         gamePanel.add(button);
    }

  • JButton question

    How do you change the background color of a JButton? For instance, I want the button to be the normal gray by default, then when you click it I would like it to turn Yellow.
    Any ideas?
    Thanks in advance.

    JButton jb = new JButton("Button");
    jb.setBackground(Color.YELLOW);
    jb.setForeground(Color.GREEN);Then take action once the button has been pushed.
    Lance

  • JButton question, with clarification

    here is what i want for my JButton:
    | 1 |
    and here is what is happening:
    | ... |
    the reason I think what is happeneing is happening is because the size of the button is too small, so it is not displaying the "1" inside it.
    the trivial solution of increase the size of the button to allow the label to display is useless for me. I need the size to be 32x32 pixels.
    how do i FORCE the label to display. i have tried messing with the fonts, with the layout, everything.
    plz help.
    thnx.

    All you need to do is set the border to a minimal size, i.e.
         Dimension d = new Dimension (size, size);
              but.setPreferredSize (d);
              // but.setSize (size, size);
              Insets i = new Insets (1,1,1,1);
              but.setMargin (i);
    Here is my whole test program:
    import java.awt.*;
    import javax.swing.*;
    public class ButtonTest extends JPanel {
    JButton but = new JButton ("1");
    public ButtonTest (int size) {
         Dimension d = new Dimension (size, size);
              but.setPreferredSize (d);
              // but.setSize (size, size);
              Insets i = new Insets (1,1,1,1);
              but.setMargin (i);
    add (but);
    public void printSize () {
         Dimension d = but.getSize();
         System.out.println ("width = " +
                                  d.width + " height = " + d.height);
    public static void main (String [] args) {
    JFrame frame = new JFrame ("Border Test");
    Integer s = new Integer (args[0]);
    ButtonTest ats = new ButtonTest(s.intValue());
    frame.getContentPane().add("Center", ats);
    frame.pack();
    //frame.setSize (100, 100);
    frame.setVisible (true);
    ats.printSize();

  • Another JButton question

    if I use a button image as my JButton, can I still write text over the image?
    consider this:
    JButton bttn = new JButton("a button");
    bttn.setIcon( new javax.swing.ImageIcon("d_eclipse.jpg") );will "a button" still be displayed over the image?

    Can be. There are methods in AbstractButton that control the appearance.
    Check out the API for javax.swing.AbstractButton setHorizontalTextPosition(), setHorizontalAlignment(), setVerticalTextPosition(), setVerticalAlignment().
    http://java.sun.com/j2se/1.4/docs/api/javax/swing/AbstractButton.html

  • Question on retrieving data from a JTable

    I have created a custom table model by following some examples. I will problably remove this though and just use the default model. I just wanted to find out a couple of things about the code. If the cells update automatically, why is there a setValueAt method? I dont see anywhere in the listener where this method is used.
         public class InteractiveTableModelListener implements TableModelListener {
         public void tableChanged(TableModelEvent evt) {
          if (evt.getType() == TableModelEvent.UPDATE) {
              int column = evt.getColumn();
              int row = evt.getFirstRow();
              System.out.println("row: " + row + " column: " + column);
              table.setColumnSelectionInterval(column + 1, column + 1);
              table.setRowSelectionInterval(row, row);
         }My second question is about retrieving the data. I need to get the data out of the table, create an object from it and send it too my database. This is my getValueAt method
         public Object getValueAt(int row, int column) {
             UpdateEventSetGet record = (UpdateEventSetGet)dataVector.get(row);
             switch (column) {
                 case POSITION_INDEX:
                    return record.getPosition();
                 case FNAME_INDEX:
                    return record.getFirstname();
                 case LNAME_INDEX:
                    return record.getLastname();
                 case TIME_INDEX:
                    return record.getTime();
                 default:
                    return new Object();
         }I just have a couple of questions about this. What is the best way to loop in order to retrieve all of the data from the table, as i presume the above method only retrieves one cell. And secondly, my constructor in my set/get class does not require any parameters (this is how it was for some reason)
         public UpdateEventSetGet() {
         position = "";
         firstName = "";
         lastName = "";
         timeSet = "";
         }The way it is above, can i retrieve four objects (as that what the getValueAt methods returns), pass them into this constructor to end up with just 1 object?
    cheers for the help

    hope this helps
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Vector;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
    * @author dayananda.bv
    public class TableModelTest extends JFrame implements ActionListener{
        private JButton jButton1;
        private JScrollPane jScrollPane1;
        private JTable jTable2;
        Vector vec = new Vector();
        DefaultTableModel dtm;
        /** Creates a new instance of TableModelTest */
        public TableModelTest() {
            jButton1 = new JButton("Get Data");
            jButton1.addActionListener(this);
            jTable2 = new JTable();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            jButton1.setText("jButton1");
            int j = 0;
            for(int i=0;i<10;i++){
            Vector v = new Vector();
                v.addElement(j++);
                v.addElement(j++);
                v.addElement(j++);
                v.addElement(j++);   
                vec.addElement(v);
            Vector colNames = new Vector();
            colNames.addElement("A");
            colNames.addElement("B");
            colNames.addElement("C");
            colNames.addElement("D");
            dtm = new DefaultTableModel(vec, colNames);
            jTable2.setModel(dtm);
            jScrollPane1 = new JScrollPane(jTable2);
            getContentPane().add(jScrollPane1,BorderLayout.CENTER);
            getContentPane().add(jButton1,BorderLayout.SOUTH);
            pack();
            setVisible(true);
        public void actionPerformed(ActionEvent e){
            Vector data = dtm.getDataVector();
            for(int i=0;i<data.size();i++){
                Vector row = (Vector)data.get(i);
                System.out.println(row);
        public static void main(String args[]){
            new TableModelTest();
    }

  • Changing a JButton color...

    This is probably a simple question to most of you out there. I apologise in advance.
    I am writing a kind of robot simulator program for a university project, at the moment all I need is for the buttons in the centre window to change colour on click and remain that colour. I cannot get it to work and was wondering if anyone had any not too complicated suggestions.
    The place I have the problem is in the action performed area.
    My code looks like this:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class RoboSim extends JFrame implements ActionListener
        private JButton button1, button2, button3, button4, button5, squareButton;
        private JPanel panel1;
        private JLabel squareLabel, directionLabel;
        private JTextField squareField, directionField;
        public static void main(String[] args)
            RoboSim frame = new RoboSim();
            frame.setSize(500, 450);
            frame.createGUI();
            frame.setVisible(true);
        private void createGUI()
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            Container window = getContentPane();
            window.setLayout(new BorderLayout() );
              Toolkit toolkit = Toolkit.getDefaultToolkit();
                 Image icon = toolkit.getImage(getClass().getResource("icon.gif"));
                 setIconImage(icon);
                 //EAST PANEL START
            JPanel eastPanel = new JPanel();
            eastPanel.setPreferredSize(new Dimension(100, 500));
            eastPanel.setLayout(new FlowLayout());
           button1 = new JButton("Forward");
           eastPanel.add(button1);
           button1.addActionListener(this);
           button2 = new JButton("  Rotate ");
           eastPanel.add(button2);
           button2.addActionListener(this);
           button3 = new JButton("   Clear  ");
           eastPanel.add(button3);
           button3.addActionListener(this);
           button4 = new JButton("    Exit    ");
           eastPanel.add(button4);
           button4.addActionListener(this);
           button5 = new JButton("  About  ");
           eastPanel.add(button5);
           button5.addActionListener(this);
            eastPanel.setBackground(Color.GRAY);
            window.add(eastPanel, BorderLayout.EAST);
            //EAST PANEL END
            //SOUTH PANEL START
            JPanel southPanel = new JPanel();
            southPanel.setLayout(new FlowLayout());
           squareLabel = new JLabel("Square ");
           southPanel.add(squareLabel);
           squareField = new JTextField(3);
           southPanel.add(squareField);
           directionLabel = new JLabel("Direction ");
           southPanel.add(directionLabel);
           directionField = new JTextField(3);
           southPanel.add(directionField);
            southPanel.setBackground(Color.GRAY);
            window.add(southPanel, BorderLayout.SOUTH);
            //SOUTH PANEL END
            //CENTRE PANEL START
            JPanel centrePanel = new JPanel();
            centrePanel.setLayout(new GridLayout(10,10));
              for (int square = 0; square <= 99; square++)
                   squareButton = new JButton();
                   squareButton.addActionListener(this);                    
                   squareButton.setBackground(Color.GREEN);
                   centrePanel.add(squareButton);
            centrePanel.setBackground(Color.LIGHT_GRAY);
            window.add(centrePanel, BorderLayout.CENTER);
            //CENTRE PANEL END
        public void actionPerformed(ActionEvent event)
             Object source = event.getSource();
            if (source == squareButton)
                   // I CANNOT WORK OUT WHAT TO PUT HERE
            if (source == button5)
                 JOptionPane.showMessageDialog(null,"� RoboSim \n "+
                 "Created By !Removed for post! \n "+
                 "!Removed for post! \n "+
                 "!Removed for post!");
              if (source == button4)
                 System.exit(0);
            if (source == button3)
            if (source == button2)
            if (source == button1)
    }

    Im not sure I understand the last bit of help, how do
    I apply the ActionListener to all 100 of the buttons?You already are "applying" the same listener to all the 100 buttons, the listener being your "RoboSim" instance.
    The problem with your code (at least the problem camickr targetted) is this line:
    if (source == squareButton)That's because "squareButton" will be only one of the one hundred buttons, as a matter of fact the last one created.
    But, on the other hand, you have to check the source in that ActionListener because the event could also come from other sources than those one hundred buttons.
    So, what camickr suggested was that you create:
    - one ActionListener for the 100 buttons, and only for those, so that, when it gets invoked, you know the event comes from one of these buttons
    - another ActionListener for the other events, wherein you check the source. For that you can keep the one you already have.
    You can easily create EventListeners as anonymous inner classes. See examples here: http://java.sun.com/docs/books/tutorial/uiswing/events/generalrules.html#innerClasses.
    For an overview, see this: http://java.sun.com/docs/books/tutorial/uiswing/events/index.html.

  • Opening new forms using jbutton

    Hi i'm new to java, and i am currentley building an interface which has three buttons(cars,vans,red car). I have managed to create a class that opens a new window when the car button is clicked. However i am unsure of how to create different windows for when the other buttons are clicked.
    Heres my code ive based it on an example i found on here.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    public class Interface extends JPanel implements ActionListener {
    JDialog dialog;
    public Interface(JFrame f)
    dialog = new JDialog(f, "dialog");
    dialog.getContentPane().add(new JLabel("hello world", JLabel.CENTER));
    dialog.setSize(400,300);
    dialog.setLocation(425,200);
    public void actionPerformed(ActionEvent e)
    if(!dialog.isVisible())
    dialog.setVisible(true);
    else
    dialog.toFront();
    public JPanel getPanel()
    JPanel panel = new JPanel();
    JPanel selectPanel = new JPanel();
    JPanel ControlPanel = new JPanel();
    selectPanel.setBorder(BorderFactory.createCompoundBorder(
    BorderFactory.createTitledBorder("Select Piece Type:"),
    BorderFactory.createEmptyBorder(5,5,5,5)));
    JButton cars = new JButton("Cars");
    cars.addActionListener(this);
    JButton vans = new JButton("Vans");
    JButton redcar = new JButton("Red Car");
    selectPanel.add(cars);
    selectPanel.add(vans);
    selectPanel.add(redcar);
    panel.add(selectPanel);
    return panel;
    public static void main(String[] args)
    JFrame f = new JFrame();
    Interface ae = new Interface(f);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(ae.getPanel(), "North");
    f.setSize(400,200);
    f.setLocation(200,200);
    f.setVisible(true);
    Thanks for any help

    Thanks for the reply, i am now having trouble adding buttons to the dialog box. This is the code i am using:
    dialog = new JDialog(f, "dialog");
            dialog.getContentPane().add(new JLabel("hello world", JLabel.CENTER));
            dialog.setSize(400,300);
            dialog.setLocation(425,200);
            JButton buttonQuestion = new JButton( "Question" );
            dialog.getContentPane().add(buttonQuestion);For some reasson this turns the whole dialog pane into a button. So all i get is a dialog box with question in the middle. What i need is the hello world label to be displayed, with the questin button underneath
    Thanks for any help

  • How do i use jbutton for mutiple frames(2frames)???

    im an creating a movie database program and i have a problem with the jButtons on my second frame i dont know how to make them work when clicked on. i managed to make the jButtons work on my first frame but not on the second....
    here is that code so far----
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    * real2.java
    * Created on December 7, 2007, 9:00 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    * @author J
    public class real2 extends JPanel  implements ActionListener{
        private JButton addnew;
        private JButton help;
        private JButton exit;
        private JFrame frame1;
        private JButton save;
        private JButton cancel;
        private JButton save2;
        private JLabel moviename;
        private JTextField moviename2;
        private JLabel director;
        private JTextField director2;
        private JLabel year;
        private JTextField year2;
        private JLabel genre;
        private JTextField genre2;
        private JLabel plot;
        private JTextField plot2;
        private JLabel rating;
        private JTextField rating2;
        /** Creates a new instance of real2 */
        public real2() {
            super(new GridBagLayout());
            //Create the Buttons.
            addnew = new JButton("Add New");
            addnew.addActionListener(this);
            addnew.setMnemonic(KeyEvent.VK_E);
            addnew.setActionCommand("Add New");
            help = new JButton("Help");
            help.addActionListener(this);
            help.setActionCommand("Help");
            exit = new JButton("Exit");
            exit.addActionListener(this);
            exit.setActionCommand("Exit");
           String[] columnNames = {"First Name",
                                    "Last Name",
                                    "Sport",
                                    "# of Years",
                                    "Vegetarian"};
            Object[][] data = {
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)}
            final JTable table = new JTable(data, columnNames);
            table.setPreferredScrollableViewportSize(new Dimension(600, 100));
            table.setFillsViewportHeight(true);
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            add(scrollPane);
            GridBagConstraints c = new GridBagConstraints();
            c.weightx = 1;
            c.gridx = 0;
            c.gridy = 1;
            add(addnew, c);
            c.gridx = 0;
            c.gridy = 2;
            add(help, c);
            c.gridx = 0;
            c.gridy = 3;
            add(exit, c);
        public static void addComponentsToPane(Container pane){
            pane.setLayout(null);
            //creating the components for the new frame
            JButton save = new JButton("Save");
            JButton save2 = new JButton("Save and add another");
            JButton cancel = new JButton("Cancel");
            JLabel moviename= new JLabel("Movie Name");
            JTextField moviename2 = new JTextField(8);
            JLabel director = new JLabel("Director");
            JTextField director2 = new JTextField(8);
            JLabel genre = new JLabel("Genre");
            JTextField genre2 = new JTextField(8);
            JLabel year = new JLabel("year");
            JTextField year2 = new JTextField(8);
            JLabel plot = new JLabel("Plot");
            JTextField plot2 = new JTextField(8);
            JLabel rating = new JLabel("Rating(of 10)");
            JTextField rating2 = new JTextField(8);
            //adding components to new frame
            pane.add(save);
            pane.add(save2);
            pane.add(cancel);
            pane.add(moviename);
            pane.add(moviename2);
            pane.add(director);
            pane.add(director2);
            pane.add(genre);
            pane.add(genre2);
            pane.add(year);
            pane.add(year2);
            pane.add(plot);
            pane.add(plot2);
            pane.add(rating);
            pane.add(rating2);
            //setting positions of components for new frame
                Insets insets = pane.getInsets();
                Dimension size = save.getPreferredSize();
                save.setBounds(100 , 50 ,
                         size.width, size.height);
                 size = save2.getPreferredSize();
                save2.setBounds(200 , 50 ,
                         size.width, size.height);
                 size = cancel.getPreferredSize();
                cancel.setBounds(400 , 50 ,
                         size.width, size.height);
                 size = moviename.getPreferredSize();
                moviename.setBounds(100 , 100 ,
                         size.width, size.height);
                size = moviename2.getPreferredSize();
                moviename2.setBounds(200 , 100 ,
                         size.width, size.height);
                 size = director.getPreferredSize();
                director.setBounds(100, 150 ,
                         size.width, size.height);
                 size = director2.getPreferredSize();
                director2.setBounds(200 , 150 ,
                         size.width, size.height);
                size = genre.getPreferredSize();
                genre.setBounds(100 , 200 ,
                         size.width, size.height);
                 size = genre2.getPreferredSize();
                genre2.setBounds(200 , 200 ,
                         size.width, size.height);
                 size = year.getPreferredSize();
                year.setBounds(100 , 250 ,
                         size.width, size.height);
                size = year2.getPreferredSize();
                year2.setBounds(200 , 250 ,
                         size.width, size.height);
                 size = plot.getPreferredSize();
                plot.setBounds(100 , 300 ,
                         size.width, size.height);
                 size = plot2.getPreferredSize();
                plot2.setBounds(200 , 300 ,
                         size.width, size.height);
                size = rating.getPreferredSize();
                rating.setBounds(100 , 350 ,
                         size.width, size.height);
                 size = rating2.getPreferredSize();
                rating2.setBounds(200 , 350 ,
                         size.width, size.height);
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            frame.add(new real2());
            //Display the window.
            frame.setSize(600, 360);
            frame.setVisible(true);
            frame.pack();
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        public void actionPerformed(ActionEvent e) {
            if ("Add New".equals(e.getActionCommand())){
               frame1 = new JFrame("add");
               frame1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
               addComponentsToPane(frame1.getContentPane());
               frame1.setSize(600, 500);
               frame1.setVisible(true);
                //disableing first frame etc:-
                if (frame1.isShowing()){
                addnew.setEnabled(false);
                help.setEnabled(false);
                exit.setEnabled(true);
                frame1.setVisible(true);
               }else{
                addnew.setEnabled(true);
                help.setEnabled(true);
                exit.setEnabled(true);           
            if ("Exit".equals(e.getActionCommand())){
                System.exit(0);
            if ("Save".equals(e.getActionCommand())){
                // whatever i ask it to do it wont for example---
                help.setEnabled(true);
            if ("Save" == e.getSource()) {
                //i tried this way too but it dint work here either
                help.setEnabled(true);
    }so if someone could help me by either telling me what to type or by replacing what iv done wrong that would be great thanks...

    (1)Java class name should begin with a capital letter. See: http://java.sun.com/docs/codeconv/
            JButton save = new JButton("Save");
            JButton save2 = new JButton("Save and add another");
            // ... etc. ...(2)Don't redeclare class members in a method as its local variable. Your class members become eternally null, a hellish null.
    how to make them work when clicked on(3)Add action listener to them.

  • How at add closd function in the JButton??

    Hi, sir:
    I hope to add a closd function in the JButton, ie, like a JPanel or JFrame, there is a "X" sign icon on the right upper coner, when we click this X sign,
    whole window or JPanel or JFrame will be closed, here I hope to add a "x" sign in JButton, when I click it, itthis button b2 will be vanished.
    I update following code, but looks like not work, I hope Text and its icon on the leading Left, but closed sign is on the extreme end of right.
    Can guru help??
    Thanks
    import javax.swing.AbstractButton;
    import javax.swing.Icon;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.ImageIcon;
    import javax.swing.SwingConstants;
    import javax.swing.GroupLayout.Alignment;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    * ButtonDemo.java requires the following files:
    *   images/right.gif
    *   images/middle.gif
    *   images/left.gif
    public class ButtonDemo2 extends JPanel  implements ActionListener {
        protected JButton  b2,bclosed;
        public ButtonDemo2() {
             Icon closedIcon  = new ImageIcon("images/ActionButton/closed.PNG");
            ImageIcon middleButtonIcon = new ImageIcon("images/little.gif");
            JLabel label1 = new JLabel("Image and Text", middleButtonIcon, JLabel.CENTER);
            bclosed = new JButton(closedIcon);
            bclosed.setBorder(null);
            bclosed.setToolTipText("closed");
            b2 = new JButton("Middle button", middleButtonIcon);
            b2.setText("Middle button");
            b2.setVerticalTextPosition(AbstractButton.BOTTOM);
            b2.add(bclosed, -1);
            b2.setIcon(middleButtonIcon);
            b2.setHorizontalTextPosition(AbstractButton.LEFT);
            b2.setAlignmentX(LEFT_ALIGNMENT);
            b2.setMnemonic(KeyEvent.VK_M);
              b2.setToolTipText("This middle button does nothing when you click it.");
            //Add Components to this container, using the default FlowLayout.
            add(label1);
            add(b2);
        public void actionPerformed(ActionEvent e) {
            if ("disable".equals(e.getActionCommand())) {
                b2.setEnabled(false);
            } else {
                b2.setEnabled(true);
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("ButtonDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            ButtonDemo2 newContentPane = new ButtonDemo2();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    Thanks, I add as follows:
    package a.border;
    import javax.swing.AbstractButton;
    import javax.swing.Icon;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.ImageIcon;
    import javax.swing.SwingConstants;
    import javax.swing.GroupLayout.Alignment;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    * ButtonDemo.java requires the following files:
    *   images/right.gif
    *   images/middle.gif
    *   images/left.gif
    public class ButtonDemo2 extends JPanel  implements ActionListener {
        protected JButton  b2,bclosed;
        public ButtonDemo2() {
             Icon closedIcon  = new ImageIcon("images/ActionButton/closed.PNG");
            ImageIcon middleButtonIcon = new ImageIcon("images/little.gif");
            JLabel label1 = new JLabel("Image and Text", middleButtonIcon, JLabel.CENTER);
            bclosed = new JButton(closedIcon);
            bclosed.setBorder(null);
            bclosed.setToolTipText("closed");
            bclosed.setActionCommand("closed");
            b2 = new JButton("Middle button", middleButtonIcon);
            b2.setText("Middle button");
            b2.setVerticalTextPosition(AbstractButton.BOTTOM);
            b2.add(bclosed, -1);
            b2.setIcon(middleButtonIcon);
            b2.setHorizontalTextPosition(AbstractButton.LEFT);
            b2.setAlignmentX(LEFT_ALIGNMENT);
            b2.setMnemonic(KeyEvent.VK_M);
            bclosed.addActionListener(this);
            b2.setToolTipText("This middle button does nothing when you click it.");
            //Add Components to this container, using the default FlowLayout.
            add(label1);
            add(b2);
        public void actionPerformed(ActionEvent e) {
            if ("disable".equals(e.getActionCommand())) {
                b2.setEnabled(!b2.isEnabled());
            if             ("closed".equals(e.getActionCommand())) {
                  System.out.println("OK closed is pressed");
                  remove(b2);
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("ButtonDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            ButtonDemo2 newContentPane = new ButtonDemo2();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }But I cannot see the First Image I add in b2 such as little.gif and "Image and Text" on it, only I can see bclosed icon.
    what is wrong here??
    Thanks a lot
    Good weekend

  • Question on Files and Exceptions

    Hi everyone.
    I have a program that is supposed to let you use a JFileSearcher to find a text file, enter some search terms into a JTextArea and when you click a button it opens a new frame. The new frame is it's own class and its constructor requires a file object and an array of Strings. The problem I have is that it isn't reading the file right. I put my readFile() method inside a try clause as well as my Scanner object definition. But, for some reason an exception keeps getting thrown when it tries to execute the readFile() method, which obviously makes the rest of my program not work. Here's my code:
    FileSearcher.java
    * FileSearcher.java
    * Darren Gordon
    * @version 1.00 2008/10/18
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class FileSearcher extends JPanel implements ActionListener {
         private JButton find, results, clear;
         private JLabel lblTitle, lblFilePath, lblSearchTerms;
         private JTextField filePath;
         private JTextArea searchTerms;
         private JFileChooser finder;
         private File file;
         private boolean pickedFile = false;
         public static void main(String[] args) {
              new FileSearcher();
        public FileSearcher() {
             JFrame f = new JFrame("D-Train's String File-Searcher, preferred Edition");
             f.setSize(350, 300);
             f.setResizable(false);
             f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             makePanel();     
             f.add(this);
             f.setVisible(true);
        public void makePanel() {
             try {
                  UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
             } catch(Exception e) {
             JPanel top = new JPanel();
             lblTitle = new JLabel("String File-Searcher");
             lblFilePath = new JLabel("Chosen File:");
             filePath = new JTextField(30);
             find = new JButton("Find File");
             JPanel center = new JPanel();
             results = new JButton("Get Results");
             clear = new JButton("Clear Fields");
             lblSearchTerms = new JLabel("Search Terms - seperate with a semi-colon(;)");
             searchTerms = new JTextArea(5, 35);
             finder = new JFileChooser();
             find.addActionListener(this);
             results.addActionListener(this);
             clear.addActionListener(this);
             top.add(lblTitle);
             top.add(lblFilePath);
             top.add(filePath);
             top.add(find);
             top.setPreferredSize(new Dimension(300, 50));
             center.add(lblSearchTerms);
             center.add(searchTerms);
             center.add(results);
             center.add(clear);
             setLayout(new BorderLayout(5, 5));
             add(BorderLayout.NORTH, top);
             add(BorderLayout.CENTER, center);
        public String[] getSearchTerms() {
             String[] temp = searchTerms.getText().split(";");
             return temp;
        public void actionPerformed(ActionEvent e) {
             if(e.getSource() == find) {
                  int temp = finder.showOpenDialog(this);
                  if(temp == finder.APPROVE_OPTION) {
                       file = finder.getSelectedFile();
                       pickedFile = true;
                       filePath.setText(file.getAbsolutePath());     
             } else if(e.getSource() == clear) {
                  searchTerms.setText("");
             } else if(e.getSource() == results && pickedFile) {
                  new Results(file, getSearchTerms());
    }Results.java
    * @(#)Results.java
    * Darren Gordon
    * @version 1.00 2008/10/18
    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    import java.util.*;
    public class Results extends JPanel {
         private Scanner scan;
         private File file;
         private String[] document, searchTerms;
         private int[] wordsCount;
         private int counter = 0;
         private JLabel lblTitle;
         private JTextArea resultsBox;
         private JScrollPane scroll;
        public Results(File a, String[] s) {
             JFrame f = new JFrame("Search Results");
             f.setResizable(false);
             f.setSize(350, 200);
             searchTerms = s;
             wordsCount = new int[searchTerms.length];
             Arrays.fill(wordsCount, 0);
             file = a;
             try {
                  readFile();
             } catch(Exception e) {
                  System.out.println("File cannot be read.");
             makePanel();
             findResults();
             giveResults();
             f.add(this);
             f.setVisible(true);
        private void readFile() {
             try {
                  scan = new Scanner(file);
             } catch(Exception e) {
                  System.out.println("Unable to scan file.");
             while(scan.hasNextLine()) {
                  document[counter] = scan.nextLine();
                  counter++;
        private void findResults() {
             for(int i = 0; i < searchTerms.length; i++) {
                  for(int j = 0; j < counter; j++) {
                        wordsCount[i] = countOccurances(document[j], searchTerms);
    private int countOccurances(String line, String search) {
         boolean searching = true;
         int count = 0;
         int index = 0;
         while(searching) {
              index = line.indexOf(search);
              if(index == -1) {
                   searching = false;
              } else {
                   count++;
                   line = line.substring(index + search.length());
         return count;
    private void giveResults() {
         for(int i = 0; i < searchTerms.length; i++) {
              if(wordsCount[i] > 0) {
                   resultsBox.append("Search term " + searchTerms[i] + " appeared " + Integer.toString(wordsCount[i]) + " time(s).\n");
         resultsBox.append("\nThe rest of the search terms turned up no results.");
    private void makePanel() {
         try {     
              UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
         } catch(Exception e) {
         lblTitle = new JLabel("Search Results");
         resultsBox = new JTextArea(5, 30);
         resultsBox.setLineWrap(true);
         scroll = new JScrollPane(resultsBox, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
         add(lblTitle);
         add(scroll);
    }Any ideas why it won't run readFile()?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Ok, basic Exception handling:
    Never throw away useful information.
    You've got some empty catch blocks: Very, very bad!
    You've got some catch blocks that only print a generic message: Bad.
    Add at least "e.printStackTrace()" to every catch block.
    Then you will see exactly which error occurs and where it happend. That information helps a lot (hint: post it!).

  • Making JButton not respond when hour glass cursor

    Hi,
    I know how to change the cursor to the hour glass one but what I want is that JButtons will not responds to clicks from an hour glass cursor. The JButtons should only respond to clicks from the normal cursor.
    Does anyone know how to do this?
    Thanks,
    Jim

    Below is a solution for JDK 1.4 without threading.
    In the event handler of ActionLock the following happens:
    1. disable the button.
    2. repaint the button using paintImmediately().
    3. perform the search.
    4. post an "enable button" event on the event dispatching queue using invokeLater().
    5. handle possible clicks during the search. They are ignored since the button is disabled.
    6. the "enable button" event is handled on the event dispatching thread.
    Three comments:
    i) if step 2 is not done the paint event triggered by disabling the button will not be handled until just before step 6. Visually the button will thus not appear disable.
    ii) if step 4 is not done through invokeLater step 6 is done before step 5, thus the clicks will start new searches.
    iii) focus issues are solved by making the button not focusable.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ButtonTest
      public static void main(String[] args)
        JFrame frame = new JFrame("Button test");
        frame.getContentPane().add(new MButton(new SearchAction()));
        frame.pack();
        frame.show();
    class SearchAction extends AbstractAction
      public SearchAction()
        super("Search");
      public void actionPerformed(ActionEvent e)
        try
          Thread.currentThread().sleep(3000);  // Simulate time-consuming search
        catch (InterruptedException ex)
    class ActionLock implements ActionListener
      private ActionListener m_OriginalListener;
      private JButton m_button;
      public ActionLock(ActionListener listener, JButton button)
        m_OriginalListener = listener;
        m_button = button;
      public void actionPerformed(final ActionEvent e)
        m_button.setEnabled(false);
        m_button.paintImmediately(
            0, 0, m_button.getWidth(), m_button.getHeight());
        m_OriginalListener.actionPerformed(e);
        SwingUtilities.invokeLater(new Runnable()
          public void run()
            m_button.setEnabled(true);
    class MButton extends JButton
      public MButton(Action action)
        super(action);
        setFocusable(false);
      public void addActionListener(ActionListener listener)
        super.addActionListener(new ActionLock(listener, this));

  • Java - ActionListener on Button

    Hi,
    I am trying to add listener to my button in my applet although I am facing a problem. Namely my applet structure looks as follow;
    public class GUI extends JApplet implements ActionListener {
      private JButton jButtonCalculate;
      private ActionListener calculateButtonListener = new ActionListener()
           public void actionPerformed(ActionEvent e)
                if (e.getSource() != jButtonCalculate) {
                //DO SOMETHING
      public void init() {
      jButtonCalculate.addActionListener(calculateButtonListener);
    The listener for button is not working without putting the below code above the public void init():
    public GUI() {
          init();
    Could somebody tell me how to add listener to my button without the above change as after including it to my applet the listener is working although my InputVerifier method will be not working. I will be appreciate for your suggestions
    Thanks in advance

    It is working now, there was a small bug in my code not allowing me to do what I wanted
    Thanks for help

Maybe you are looking for

  • Down payments added to the net value

    Hello Experts, I have configured downpaymants as per my client requirement . I have entered manually the down payment condition type in the sales order but the down payment value has added to the net value. Is it standard system behaviour or please e

  • Iphone 5 not working..

    everytime i plug in my iphone 5 with the usb cord i get a pop up message saying driver has malfuctioned.. so i go check the driver and it says "unknown device" and " No drivers are installed for this device. If you are having problems with this devic

  • Security framework

    Hi, I would like to learn about the security (user authentication) implementation in OC4J. More specifically on how to extend the security API and implement a form-based authentication. Could you point me to any documentation, sample code about this?

  • Can I hide or lock (with password) access to the add-on manager?

    So users can't see what add-ons I have running? I don't want my (tech savvy) children knowing or being able to alter add-ons monitoring what they are viewing. I've caught my daughter looking at inappropriate stuff and she's a sneaky one so she tries

  • JobManager:getQueueConnectionFactory():Error:Could not dereference object

    We are getting this error everytime we add something to a watched folder Any ideas? 2009-09-09 14:45:25,610 ERROR [STDERR] Sep 9, 2009 2:45:25 PM com.adobe.idp.jobmanager.util.JobManagerUtil getQueueConnectionFactory SEVERE: JobManager:getQueueConnec