ActionListeners and ItemListener

Hi
I'm using some ItemListener to detect when things are selected from a list but require a button to open a new GUI window. However, when i try and compile, the compiler says i can't use ActionListeners and ItemListeners in the same class. Is this true? Any ways i can get around it?
Cheers

implements ItemListener and ActionListener
gives the following error messages:
ListTest.java:6: '{' expected
public class ListTest extends GUIFrame implements ItemListener and ActionListener
^
ListTest.java:100: '}' expected
^
ListTest.java:6: ListTest should be declared abstract; it does not define itemStateChanged(java.awt.event.ItemEvent) in ListTest
public class ListTest extends GUIFrame implements ItemListener and ActionListener
anymore ideas?

Similar Messages

  • How to use ActionListener and ItemListener in the same class

    Why can't I use both ActionListener and ItemListener in the same Class?
    I want to use a drop down list and an entry box on the same form.
    How? I'm having trouble compling......
    Thanks!
    CODE:
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Disp extends Applet implements ActionListener, ItemListener
    { TextField entry=new TextField(7);
    Button Enter=new Button("Enter");
    public void init()
    add(entry);
    add(Enter);
    entry.addActionListener(this);
    entry.requestFocus();
    Enter.addActionListener(this);
    public void actionPerformed(ActionEvent thisEvent)
    String answer=entry.getText();

    Simply get your Applet to implement both ActionListener and ItemListener.
    public class MyApplet extends Applet implements ActionListener, ItemListener
      public void init()
        itemWidget.addItemListener(this):
        actionWidget.addActionListener(this);
      public void actionPerformed(ActionEvent e)
        System.out.println("ACTION PERFORMED!");
      public void itemStateChanged(ItemEvent e)
        System.out.println("ITEM STATE CHANGED!");
    }Hope this helps.

  • ActionListeners and ActionEvents

    Alright guys I am building myself a GUI and am using ActionListeners and ActionEvents however I'm not exactly sure what these 2 things do. I know they are used for buttons seeing as all of my buttons implement them but what specifically do they do. How does the ActionListener link to the ActionEvent???

    Check this out:
    http://java.sun.com/docs/books/tutorial/uiswing/learn/index.html
    You definitely need an overview of event-based programming to get a start with Swing. Also, make sure you understand anonymous classes (a type of inner class), as they are used extensively throughout Swing (especially in sample code), and are quite confusing if you don't know what they are!
    Nick

  • ActionListeners and scope

    Hello,
    I have been trying to get my action listener to work so that it outputs the volume that is passed into. I want to limit the volume between 0 and 15 or there abouts. I have been reading books upon books to try and figure out where i have gone wrong but i just can't seem to figure it.
    Here is my code below. any help would be appreciated
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    * Gareth Leah
    class volumeControl extends JFrame {
    public class VolumeSensor {
    private int lowVolume;
    private int maxVolume;
    private int volume;
    //CONSTRUCTORS
    public VolumeSensor() {
    this(null,0, 15, 10);
    public VolumeSensor(String n, int lowVolume, int maxVolume, int volume) {
    this.lowVolume = lowVolume;
    this.maxVolume = maxVolume;
    this.volume = volume;
    //methods
    public int getlowVolume() {
    return lowVolume;
    public void setlowVolume(int lowVolume) {
    this.lowVolume = lowVolume;
    public int getmaxVolume() {
    return maxVolume;
    public void setmaxVolume(int maxVolume) {
    this.maxVolume = maxVolume;
    public int getVolume() {
    return volume;
    public void setVolume(int volume) {
    this.volume = volume;
    public boolean Mute(){
    return true;
    public volumeControl() {
    this.setTitle("Volume Controller");     
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel p = new JPanel();
    //--------Volume Label------------------------------
    JLabel Label = new JLabel("Volume");
    Label.setForeground(Color.black);
    Font font = new Font("Serif", Font.PLAIN, 15);
    Label.setFont(font);
    //--------Mute------------------------------
    JCheckBox Mute = new JCheckBox("Mute");
    Mute.setSelected(false);
    p = new JPanel();
    p.add(Mute);
    this.add(p, BorderLayout.SOUTH);
    //--------Volume------------------------------
    final JSlider volume = new JSlider(0,15,7);
    volume.setOrientation(SwingConstants.VERTICAL);
    volume.setToolTipText("Volume Control");
    volume.setPaintTicks(true);
    volume.setPaintLabels(true);
    //------------------Set it out---------------
    p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS));
    p.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
    p.add(Box.createHorizontalGlue());
    p.add(Label);
    p.add(volume,BorderLayout.CENTER);
    p.add(Box.createRigidArea(new Dimension(10, 0)));
    p.add(Mute);
    //actionlistener
    volume.addChangeListener(new ChangeListener() {
    +public void stateChanged(ChangeEvent slider) {+
    JSlider volume = (JSlider)slider.getVolume() ;
    if (slider.volume>15)
    System.out.println(volume);
    + +//int volume = (int)volume.getVolume();++
    ++// if (volume == 0) {++
    ++// if (lowVolume) Mute(false);++
    +} else {+
    System.out.println(volume);
    +}+
    +});+
    this.pack();
    this.setVisible(true);
    /* Test */
    public static void main(String[] arg) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    volumeControl v = new volumeControl();

    Thanks again! i feel like im starting to get the hang of this. I have changed my program to:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    * Gareth Leah
    class volumeControl extends JFrame {
    public class VolumeSensor {
        public boolean Mute(){
            return true;
            public volumeControl() {
            this.setTitle("Volume Controller");     
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel p = new JPanel();
             //--------Volume Label------------------------------
            JLabel Label = new JLabel("Volume");
            Label.setForeground(Color.black);
            Font font = new Font("Serif", Font.PLAIN, 15);
            Label.setFont(font);
             //--------Mute------------------------------
            JCheckBox Mute = new JCheckBox("Mute");
            Mute.setSelected(false);
            p = new JPanel();
            p.add(Mute);
            this.add(p, BorderLayout.SOUTH);
            //--------Volume------------------------------
            final JSlider volume = new JSlider(0,15,7);
            volume.setOrientation(SwingConstants.VERTICAL);
            volume.setToolTipText("Volume Control");
            volume.setPaintTicks(true);
            volume.setPaintLabels(true);
            //------------------Set it out---------------
            p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS));
            p.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
            p.add(Box.createHorizontalGlue());
            p.add(Label);
            p.add(volume,BorderLayout.CENTER);
            p.add(Box.createRigidArea(new Dimension(10, 0)));
            p.add(Mute);
            //actionlistener
           volume.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
            int volumeLevel = volume.getValue();
            if (volumeLevel<=15 || volumeLevel>=1)
                System.out.println(volumeLevel);
            this.pack();
            this.setVisible(true);
        /* Test */
        public static void main(String[] arg) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    volumeControl v = new volumeControl();         
    and i keep getting this compile error:
    compile:
    run:
    2009-07-28 13:14:24.975 java[23021] CFLog (0): CFMessagePort: bootstrap_register(): failed 1103 (0x44f), port = 0xe903, name = 'java.ServiceProvider'
    See /usr/include/servers/bootstrap_defs.h for the error codes.
    2009-07-28 13:14:24.975 java[23021] CFLog (99): CFMessagePortCreateLocal(): failed to name Mach port (java.ServiceProvider)
    i'm really not sure how to fix the compile error but i think im getting this jbox ok!

  • Inheritance based on USER column and JPQL based on @ManyToOne column

    I wanted to build a simple inheritence scheme for no other reason than to support a generalized table that I could manipulate in standard libraries and to extend that table with columns that might exist in various customer implementations. In the extra-ordinarily simple example that follows I created a base Parcel class; extend that with a ParcelBean which has a column specific to a user; and extend that further with a wrapper class that will include some Trinidad references that I want to keep completely away from the bean classes. In short, I wanted to put together an inheritence scheme for basic OO reasons, not because of any particular table structure.
    After some thought I figured that the best way to do this might be to use the Single-Table Strategy, especially after I discovered that I could fool the system by using the Oracle USER pseudo-column for my DiscriminatorColumn and use my schema name for the DiscriminatorValue.
    @Entity
    @Table(name = "PARCEL")
    @Inheritance
    @DiscriminatorColumn(name = "USER")
    public class Parcel {
      String parcelPin;
      public Parcel() {
      @Id
      @Column(name = "PARCELPIN", nullable = false)
      public String getParcelPin() {
        return parcelPin;
      public void setParcelPin(String parcelPin) {
        this.parcelPin = parcelPin;
    @Entity
    public class ParcelBean extends Parcel {
      LandUseType luc;
      public ParcelBean() {
      public void setLuc(LandUseType newluc) {
        this.luc = newluc;
      @ManyToOne
      @JoinColumn(name = "LUC")
      public LandUseType getLuc() {
        return luc;
    @Entity
    @DiscriminatorValue("CPC")
    public class ParcelRow extends ParcelBean {
      public ParcelRow() {
      public void doSomething(ActionEvent ae) {
        ; // Trinidad code
    }For a couple of weeks this has been working fine. Right up until I tried to a JPQL like the following:
    "select p from ParcelRow p where p.luc.cpcCode=12"The problem is that TOPLINK will generate SQL that prefixes USER with an alias (something it does not do if there isn't a foreign key reference involved). This won't work because Oracle SQL does not allow aliases on pseudo-columns
    select USER from PARCEL; -- return CPC
    select p.USER from PARCEL p; -- throws ORA-01747: invalid user.table.column specificationSo now I'm in a jam. I can't (read won't if you will) give up on my requirement for inheritence. I have multiple clients with the same basic legacy table with minor variations and I have tens of thousands of lines of code that work on the basic core table properties and I don't want to copy and paste. I could use interfaces, except that I would still have to extend the Beans with my Row classes so that I could add the JSF actionListeners (and other such stuff). I need to be able to select Lists of these Row classes with the JSF methods so that I can expose them as values to JSF/Trinidad/ADF Tables and it break every person pattern I enforce to mix JSF and JPA dependencies in the same class.
    Anyone out there have any ideas?
    Thanks Mark

    Of course a simple fix for this problem would be if the Oracle provider code was smart enough to recognize pseudo columns and to not prefix them with an alias.
    Is there any chance that this might be done before a final release?
    Mark

  • How to differentiate between Single click and double click event in List

    I am facing a problem while using list in awt.
    I want to execute some code on single click and other on double click but when double click event occurs it also executes the single click code.
    because i have added both actionlistener and itemlistener on the list.
    How to sort out this problem.
    please help me out.
    Thanks buddies.

    Hello Meeraj_Kanaparthi
    Thanks for helping i m giving u the code i have tried.
    Plz help me on this...
    Thanks........
    import java.awt.*;
    import java.awt.event.*;
    class CheckList extends Frame implements MouseListener
         List l1;
         int x;
         int y;
         CheckList()
         setSize(500,500);
         setLayout(new FlowLayout());
         l1=new List(10);
         add(l1);
         l1.add("Item 1");l1.add("Item 2");l1.add("Item 3");l1.add("Item 4");l1.add("Item 5");
         x=6;
         y=0;
         l1.addMouseListener(this);
    //     l1.addItemListener(this);
         show();
         public void execute(int y)
         if(y==1)
         {System.out.println("3");
              l1.remove(l1.getSelectedIndex());
         if(y==2)
         {System.out.println("4");
              l1.add("item " + x);
              x++;
         public void mousePressed(MouseEvent e)
              System.out.println("Pressed");
         public void mouseReleased(MouseEvent e)
              System.out.println("Released");
         public void mouseEntered(MouseEvent e) {}
         public void mouseExited(MouseEvent e) {}
         public void mouseClicked(MouseEvent e)
         if (e.getClickCount()==1)
              System.out.println("1");
              y=1;
         if (e.getClickCount() == 2)
         {System.out.println("2");
              y=2;
              execute(y);
         public void actionPerformed(ActionEvent ae)
         public void itemStateChanged(ItemEvent it)
         public static void main(String ag[])
         new CheckList();
    }

  • Missing method body or declare abstract error

    Hi!
    I have been working on this simple Java 1.3.1 program for three days now and cannot figure out what I am doing wrong. If anyone has done the "Building an Application" tutorial in the New to Java Programming Center, you might recognize the code. I am trying to set up a frame with panels first using the BorderLayout and then the FlowLayout within each section of the BorderLayout. It will have textfields and checkboxes. I am working on the code to retrieve the user input from the text boxes and also to determine which checkbox the user has checked. Here is my code: (ignore my irrelivent comments!)
    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    import java.awt.event.*;
    import java.awt.Color.*;
    import java.awt.Image.*;
    //Header Comment for a Routine/Method
    //This method gathers the input text supplied by the user from five text fields on the Current
    //Purchase tab of the tabbed pane of the MPGLog.java program. The way it gathers the text
    //depends on the current processing state, which it retrieves on its own. It saves the text to
    //a text file called textinput.txt.
    public class CollectTextInput extends JPanel implements ActionListener
    { // Begin class
         //Declare all the objects needed first.
         // These are the text fields
         private JTextField currentMileage;
         private JTextField numofGallonsBought;
         private JTextField dateofPurchase;
         private JTextField pricePerGallon;
         private JTextField gasBrand;
         // Declaring the Labels to go with each TextField
         private JLabel lblcurrentMileage;
         private JLabel lblnumofGallonsBought;
         private JLabel lbldateofPurchase;
         private JLabel lblpricePerGallon;
         private JLabel lblgasBrand;
         // Declaring the Checkboxes for the types of gas bought
         private JCheckBox chbxReg;
         private JCheckBox chbxSuper;
         private JCheckBox chbxUltra;
         private JCheckBox chbxOther;
         private JCheckBox chbxHigher;
         private JCheckBox chbxLower;
         // Declaring the Buttons and images needed
         private JButton enter;
         private JButton edit;
         //private JButton report; //Will be used later
         private JLabel bluecar;          //Used with the ImageIcon to create CRV image
         private JPanel carimage;     //Used in buildImagePanel method
         private JPanel datum;          //Used in buildDatumPanel method
         private JPanel gasgrade;     //Used in buildGasTypePanel method.
         //Declaring the Panels that need to be built and added
         //to the border layout of this panel.
         //private JPanel panlimages;
         //private JPanel panltextinputs;
         //private JPanel panlchkBoxes;
         // Class to handle functionality of checkboxes
         ItemListener handler = new CheckBoxHandler();
         // This is where you add the constructor for the class - I THINK!!
         public CollectTextInput()
         { // Opens collectTextInput constructor
              // Must set layout for collectTextInput here
              // Choosing a BorderLayout because we simply want to
              // add panels to the North, Center and South borders, which, by
              // default, will fill the layout with the three panels
              // we are creating
              setLayout(new BorderLayout());
              //Initialize the objects in the constructor of the class.
              //Initialize the textfields
              currentMileage = new JTextField();
              numofGallonsBought = new JTextField();
              dateofPurchase = new JTextField();
              pricePerGallon = new JTextField();
              gasBrand = new JTextField();
              // Initialize the labels that go with each TextField
              lblcurrentMileage = new JLabel("Enter the mileage at the time of gas purchase: ");
              lblnumofGallonsBought = new JLabel("Enter the number of gallons of gas bought: ");
              lbldateofPurchase = new JLabel("Enter the date of the purchase: ");
              lblpricePerGallon = new JLabel("Enter the price per gallon you paid for the gas: ");
              lblgasBrand = new JLabel("Enter the brand name of the gas: ");
              //Initialize the labels for the checkboxes.
              chbxReg = new JCheckBox("Regular ", true);
              chbxSuper = new JCheckBox("Super ");
              chbxUltra = new JCheckBox("Ultra ");
              chbxOther = new JCheckBox("Other: (Choose one from below) ");
              chbxHigher = new JCheckBox("Higher than Ultra ");
              chbxLower = new JCheckBox("Lower than Ultra ");
              //Initialize the buttons that go on the panel.
              enter = new JButton("Save Data");
              edit = new JButton("Edit Data");
              //Initialize the image that oges on the panel.
              bluecar = new JLabel("2002 Honda CR-V", new ImageIcon("CRVBlue.jpg"),JLabel.CENTER);
              // Now bring it all together by calling the other methods
              // that build the other panels and menu.
              buildImagePanel();
              buildDatumPanel();
              buildGasTypePanel();
              // Once the methods above build the panels, this call to add
              //  them will add the panels to the main panel's border
              // layout manager.
              add(datum, BorderLayout.NORTH);
              add(carimage, BorderLayout.EAST);
              add(gasgrade, BorderLayout.CENTER);
         } // Ends the constructor.
            // This method creates a panel called images that holds the car image.
         public void buildImagePanel();
         { // Opens buildImagePanel.
              // First, create the Panel
              carimage = new JPanel();
              //Second, set the color and layout.
              carimage.setBackground(Color.white);
              carimage.setLayout(new FlowLayout());
              // Third, add the image to the panel.
              carimage.add(bluecar);
         }// Closes buildImagePanel
         //This method creates a panel called datum that holds the text input.
         public void buildDatumPanel();
         { //Opens buildDatumPanel
              // First, create the Panel.
              datum = new JPanel();
              //Second, set the background color and layout.
              datum.setBackground(Color.white);
              datum.setLayout(new GridLayout(2, 4, 20, 20));
              //Third, add the textfields and text labels to the panel.
              datum.add(lblcurrentMileage);
              datum.add(currentMileage);
              datum.add(lblnumofGallonsBought);
              datum.add(numofGallonsBought);
              datum.add(lbldateofPurchase);
              datum.add(dateofPurchase);
              datum.add(lblpricePerGallon);
              datum.add(pricePerGallon);
              datum.add(lblgasBrand);
              datum.add(gasBrand);
              //Optionally - Fourth -set a border around the panel, including
              // a title.
              datum.setBorder(BorderFactory.createTitledBorder("Per Purchase Information"));
              //Fifth - Add listeners to each text field to be able to
              //  know when data is input into them.
              currentMileage.addActionListener(this);
              numofGallonsBought.addActionListener(this);
              dateofPurchase.addActionListener(this);
              pricePerGallon.addActionListener(this);
              gasBrand.addActionListener(this);
         }// Closes buildDatumPanel
         // This method builds a panel called gasTypePanel that holds the checkboxes.
         public void buildGasTypePanel()
         { // Opens buildGasTypePanel method
              // First, create the panel.
              gasgrade = new JPanel();
              // Second, set its background color and its layout.
              gasgrade.setBackground(Color.white);
              gasgrade.setLayout(new GridLayout(5, 1, 10, 20));
              // Third, add all the checkboxes to the panel.
              gasgrade.add(chbxReg);
              gasgrade.add(chbxSuper);
              gasgrade.add(chbxUltra);
              gasgrade.add(chbxOther);
              gasgrade.add(chbxHigher);
              gasgrade.add(chbxLower);
              //Optionally, - Fourth - set a border around the panel, including
              // a title.
              gasgrade.setBorder(BorderFactory.createTitledBorder("Gas Type Information"));
              // Fifth - CheckBoxes require a CheckBox Handler.
              // This is a method created separately
              // outside of the method where the checkboxes are added to
              // the panel or where the checkboxes are even created.
              // This method (CheckBox Handler) implements and ItemListener
              // and is a self-contained method all on its own. See
              // the CheckBox Handler methods following the
              // actionPerformed method which follows.-SLM
         } // Closes the buildGasTypePanel method
    // Create the functionality to capture and react to an event
    //   for the checkboxes when they are checked by the user and
    //   the text fields to know when text is entered. Also to react to the
    //   Enter button being pushed and the edit button being pushed.
    public void actionPerformed(ActionEvent evt)
    { // Opens actionPerformed method.
         if((evt.getSource() == currentMileage) || (evt.getSource() == enter))
              { // Opens if statement.
                // Retrieves the text from the currentMileage text field
                //  and assigns it to the variable currentMileageText of
                //  type String.
                String currentMileageText = currentMileage.getText();
                lblcurrentMileage.setText("Current Mileage is:    " + currentMileageText);
                // After printing text to JLabel, hide the text field.
                currentMileage.setVisible(false);
           } // Ends if statement.
          if((evt.getSource() == numofGallonsBought) || (evt.getSource() == enter))
              { // Opens if statement.
                // Retrieves the text from the numofGallonsBought text field
                //  and assigns it to the variable numofGallonsBoughtText of
                //  type String.
                String numofGallonsBoughtText = numofGallonsBought.getText();
                lblnumofGallonsBought.setText("The number of gallons of gas bought is:    " + numofGallonsBoughtText);
                // After printing text to JLabel, hide the text field.
                numofGallonsBought.setVisible(false);
           } // Ends if statement.
           if((evt.getSource() == dateofPurchase) || (evt.getSource() == enter))
                     { // Opens if statement.
                       // Retrieves the text from the dateofPurchase text field
                       //  and assigns it to the variable dateofPurchaseText of
                       //  type String.
                       String dateofPurchaseText = dateofPurchase.getText();
                       lbldateofPurchase.setText("The date of this purchase is:    " + dateofPurchaseText);
                       // After printing text to JLabel, hide the text field.
                       dateofPurchase.setVisible(false);
           } // Ends if statement.
           if((evt.getSource() == pricePerGallon) || (evt.getSource() == enter))
                            { // Opens if statement.
                              // Retrieves the text from the pricePerGallon text field
                              //  and assigns it to the variable pricePerGallonText of
                              //  type String.
                              String pricePerGallonText = pricePerGallon.getText();
                              lblpricePerGallon.setText("The price per gallon of gas for this purchase is:    " + pricePerGallonText);
                              // After printing text to JLabel, hide the text field.
                              pricePerGallon.setVisible(false);
           } // Ends if statement.
           if((evt.getSource() == gasBrand) || (evt.getSource() == enter))
                       { // Opens if statement.
                         // Retrieves the text from the gasBrand text field
                         //  and assigns it to the variable gasBrandText of
                         //  type String.
                         String gasBrandText = gasBrand.getText();
                         lblgasBrand.setText("The Brand of gas for this purchase is:    " + gasBrandText);
                         // After printing text to JLabel, hide the text field.
                         gasBrand.setVisible(false);
           } // Ends if statement.
           // This provides control statements for the Edit button. If the
           //  Edit button is clicked, then the text fields are visible again.
           if(evt.getSource() == edit)
           { // Opens if statement.
             // If the edit button is pressed, the following are set to
             //  visible.
                currentMileage.setVisible(true);
                numofGallonsBought.setVisible(true);
                dateofPurchase.setVisible(true);
                pricePerGallon.setVisible(true);
                gasBrand.setVisible(true);
         }// Closes if statement.
    } // Closes actionPerformed method.
         private class CheckBoxHandler implements ItemListener
         { // Opens inner class
              public void itemStateChanged (ItemEvent e)
              {// Opens the itemStateChanged method.
                   JCheckBox source = (JCheckBox) e.getSource();
                        if(e.getStateChange() == ItemEvent.SELECTED)
                             source.setForeground(Color.blue);
                        else
                             source.setForeground(Color.black);
                        }// Closes the itemStateChanged method
                   }// Closes the CheckBoxHandler class.
    } //Ends the public class collectTextInput classThe error I keep receiving is as follows:
    C:\jdk131\CollectTextInput.java:128: missing method body, or declare abstract
         public void buildImagePanel();
    ^
    C:\jdk131\CollectTextInput.java:142: missing method body, or declare abstract
         public void buildDatumPanel();
    ^
    2 errors
    I have looked this error up in three different places but the solutions do not apply to what I am trying to accomplish.
    Any help would be greatly appreciated!! Thanks!
    Susan

    C:\jdk131\CollectTextInput.java:128: missing methodbody, or declare ?abstract
    public void buildImagePanel();^
    C:\jdk131\CollectTextInput.java:142: missing methodbody, or declare abstract
    public void buildDatumPanel();Just remove the semicolons.
    Geesh! If I had a hammer I would be hitting myself over the head with it right now!!! What an obviously DUMB newbie mistake!!!
    Thanks so much for not making me feel stupid! :-)
    Susan

  • Help with creating a new window

    Hi there
    Could anyone help me with the coding to create a new window in java? Basically its when i click on a button a new window pops up
    thanks

    Icer_age828 wrote:
    Could anyone help me with the coding to create a new window in java? Basically its when i click on a button a new window pops upWe need more information on what you mean here, what you know and what you don't know. Do you understand the basics of Java? Are you talking about using Swing? If so, what exactly do you mean by a "new window"? You can create a simple dialog via the method JOptionPane.showMessage(...) method. Do you mean to create and show a new JDialog? JFrame? Do you know about ActionListeners and how to add them to jbuttons? Given your post, I think that your best bet would be to start going through the Sun Java Swing tutorial from the beginning. Look here .

  • Event Handling...advice

    Hi,
    I'm coding up a GUI application and i need to handle many ActionEvents and other events too. What i'm doing now is having my top level class implement the ActionListener and then making 'this' the action listener for all my action events. When it comes to knowing which component fired the event i use getSource() method from the ActionEvent class. I'm not sure whether this is a good practice coz for the moment i have like 15 if(e.getSource == someComponent) statements. If you guys could advise me on whether this is ok or i should have more ActionListeners and each one of them would handle one event for one component. The problem is that i hate inner classes coz they seem to make the code somehow difficult to read (my own opinion you could advise on that too), i also thought of making my class implements even more event listeners and this way i would just need to implement the abstract methods corresponding to each event class. Any help would be much appreciated

    I always use action commands... set the action command on a button, then check the action command in your actionPerformed method. The only reason I do that is so I can easily make another button, menu, etc perform the same action. Other then that I think that your practice is pretty common.

  • Urgent help on GUI

    Hello,
    I am a newbie to GUIs in java. I am writing an application that has 4 buttons.
    You can run the codes below to see how it looks.
    I need it to connect to an oracle server when the "Connect to Server" button is clicked
    If the connection is successful,It should set the text on lblStatus to "Connected", and the
    "Get sales amount" and "Close connection" buttons should be enabled, while the
    "Connect to server button be disable"
    Otherwise a dialog box should pop up, displaying "Cannot connect to server").
    If the "Get Sales amount" button is clicked, it should display a dialog box that will
    accept user input for a store name and it should display the corresponding sales
    value from the SALES table. If the user input is "all". It should display sale amount for all
    stores in the SALES table.
    If the "Close connection" button is clicked, it should close the connection to server
    and display appropraite information in the lblStatus bar.
    My codes
    ==================
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    public class ConnectorDemo{
    public static void main (String [] args) {
    //Create window,its size, panel and add the message to be displayed at the bottom
    JFrame frame = new JFrame("Java Coursework");
    frame.setSize(350,220);
    JPanel p = new JPanel(new BorderLayout());
    p.add(new JLabel("Not connected"),BorderLayout.SOUTH);
    // Create components,their equal sizes,locations and enable or disable them
    JButton buttonOne;
    buttonOne = new JButton("Connect to server");
    buttonOne.setSize(220,30);
    buttonOne.setEnabled(true);
    buttonOne.setLocation(80,20);
    JButton buttonTwo;
    buttonTwo = new JButton("Get Sales Amount");
    buttonTwo.setSize(220,30);
    buttonTwo.setEnabled(false);
    buttonTwo.setLocation(80,60);
    JButton buttonThree;
    buttonThree = new JButton("Close connection to server");
    buttonThree.setSize(220,30);
    buttonThree.setEnabled(false);
    buttonThree.setLocation(80,100);
    JButton buttonFour;
    buttonFour = new JButton("Exit");
    buttonFour.setSize(220,30);
    buttonFour.setEnabled(true);
    buttonFour.setLocation(80,140);
    buttonFour.addActionListener (new ButtonFourListener());
    // Add components to the window
    frame.getContentPane().add(buttonOne);
    frame.getContentPane().add(buttonTwo);
    frame.getContentPane().add(buttonThree);
    frame.getContentPane().add(buttonFour);
    frame.getContentPane().add(p);
    // Display window
    frame.setVisible(true);
    static class ButtonFourListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
    JButton buttonFour = (JButton) e.getSource();
    System.exit(0);
    }//End listener
    Database
    ================
    CREATE TABLE SALES(
         shop_name VARCHAR2(30),
         sale_amount INTEGER);
    INSERT INTO SALES VALUES('waitrose', 1500);
    INSERT INTO SALES VALUES('argos', 1500);
    INSERT INTO SALES VALUES('asda', 1500);
    INSERT INTO SALES VALUES('tesco', 1500);

    You're going to need to create ActionListeners for the buttons, just like the ActionListener for button 4, except you'll want to do different things when the buttons are pressed. Here's a tutorial on ActionListeners and handling events: http://java.sun.com/docs/books/tutorial/uiswing/learn/example2.html#handlingEvents

  • Panic! Possible to change Fontcolor in List in AWT?

    I really need to know if it is possible to change the font color in AWT for different list entries in th awt.List object.
    I managed to change the fonts with no problem, but the font color...
    I�m using my list as an own object which extends the panel. Is this the right way to do it or?
    If anyone has any hints or a piece of sample code (if it is possible) please let me know.
    //Peter
    //To call the Lists class from outside
    private void setupTheList()
    String[] str = {"2","4","","","","","","","","","","","","","","","","",""}; //Items to be added to the List.
    int[] sel = {1,4,7,8,9,13}; //Which are to be selected in the List
    li = new Lists(str,5,sel);
    class Lists extends Panel{
    List list;
    public void paint(Graphics g)
    Graphics g2;
    g2 = list.getGraphics();
    g2.setColor(Color.red);
    public Lists(String[] listItems, int listLength, int[] listItemSelected){
    list = new List(listLength,true);
    for(int i = 0; i < listItems.length; i++){
    list.add(new String(listItems));
    for(int j = 0; j < listItemSelected.length; j++){
    list.select(listItemSelected[j]);
    GridBagLayout gbl = new GridBagLayout();
    setLayout(gbl);
    add(list);

    Of course create your own list you need a scrollbar, canvas or panel, and implements Mouselistener, and ItemListener after that you draw what Color, image or text you want.

  • Handling events in combo box

    Hello,
    I'm very much confused about the handling events of JComboBox with ActionListener and ItemListener. Both are seemed similar to me. If anyone can explain me the differences, it would be helpful for me. Thanks everybody.

    ActionEvents are fired each time any item is selected, ItemEvents are only fired, if the selection changes.

  • Keep getting only 1 error

    Hello everyone,
    I am new to Java. I have a program that should change the background color when a button is clicked.
    I keep getting the same error no matter what I do.
    The error is "cannot resolve symbol
    symbol: variable e
    String arg = e.getActionCommand();
    The error is on the second string statement.
    Here is the code:
    import java.awt.*;
    import java.awt.event.*;
    public class Buttons extends Frame implements ActionListener,ItemListener
         public Buttons()
         //set the layout
         setLayout(new BorderLayout(20,5));
               //Add buttons and Choice
               Button north = new Button("Red");
               Button south = new Button("Yellow");
               Button east = new Button("Cyan");
               Button west = new Button("Magenta");
               Choice colors = new Choice();
         //Add buttons and Choice to the frame
         add(north, BorderLayout.NORTH);
         add(south, BorderLayout.SOUTH);
         add(east, BorderLayout.EAST);
         add(west, BorderLayout.WEST);
         add(colors, BorderLayout.CENTER);
         //populating the Choice component
         colors.add("Red");
         colors.add("Yellow");
         colors.add("Cyan");
         colors.add("Magenta");
         colors.add("White");
         //Add ActionListener to buttons and ItemListener to Choice component
         north.addActionListener(this);
         south.addActionListener(this);
         east.addActionListener(this);
         west.addActionListener(this);
         colors.addItemListener(this);
         //override the windowClosing event
         addWindowListener(
                  new WindowAdapter()
                  public void windowClosing(WindowEvent e)
                  System.exit(0);
         }// End of Constructor method
            public static void main(String[] args)
          // set frame properties
         Buttons f = new Buttons();
               f.setTitle("Button Application");
               f.setBounds(200,200,300,300);
         f.setVisible(true);
         f.setBackground(Color.RED);
                         public void actionPerformed(ActionEvent e)
                 String arg = e.getActionCommand();
                 if (arg == "Red")
                 setBackground(Color.RED);
                 if (arg == "Yellow")
                 setBackground(Color.YELLOW);
                 if (arg == "Cyan")
                 setBackground(Color.CYAN);
                 if (arg == "Magenta")
                 setBackground(Color.MAGENTA);
                 if (arg == "White")
                 setBackground(Color.WHITE);
         public void itemStateChanged(ItemEvent ie)
              String arg = e.getActionCommand();
              if (arg == "Red")
              setBackground(Color.RED);
              if (arg == "Yellow")
              setBackground(Color.YELLOW);
              if (arg == "Cyan")
              setBackground(Color.CYAN);
              if (arg == "Magenta")
              setBackground(Color.MAGENTA);
              if (arg == "White")
              setBackground(Color.WHITE);
    }

    Hello everyone,
    I have updated my code. It compiles now. The buttons work properly, but when a color from the Choice arrow is selected it changes the background color to white and it never changes unless I click a button.
    What am I doing wrong?
    import java.awt.*;
    import java.awt.event.*;
    public class Buttons extends Frame implements ActionListener,ItemListener
         public Buttons()
              //set the layout
              setLayout(new BorderLayout(20,5));
               //Add buttons and Choice
               Button north = new Button("Red");
               Button south = new Button("Yellow");
               Button east = new Button("Cyan");
               Button west = new Button("Magenta");
               Choice colors = new Choice();
         //Add buttons and Choice to the frame
         add(north, BorderLayout.NORTH);
         add(south, BorderLayout.SOUTH);
         add(east, BorderLayout.EAST);
         add(west, BorderLayout.WEST);
         add(colors, BorderLayout.CENTER);
         //populating the Choice component
         colors.add("Red");
         colors.add("Yellow");
         colors.add("Cyan");
         colors.add("Magenta");
         colors.add("White");
         //Add ActionListener to buttons and ItemListener to Choice component
         north.addActionListener(this);
         south.addActionListener(this);
         east.addActionListener(this);
         west.addActionListener(this);
         colors.addItemListener(this);
         //override the windowClosing event
         addWindowListener(
         new WindowAdapter()
              public void windowClosing(WindowEvent e)
                   System.exit(0);
         }// End of Constructor method
            public static void main(String[] args)
              // set frame properties
             Buttons f = new Buttons();
                   f.setTitle("Button Application");
                   f.setBounds(200,200,300,300);
             f.setVisible(true);
             f.setBackground(Color.RED);
                         public void actionPerformed(ActionEvent e)
                String arg = e.getActionCommand();
                if (arg == "Red")
                setBackground(Color.RED);
                if (arg == "Yellow")
               setBackground(Color.YELLOW);
               if (arg == "Cyan")
               setBackground(Color.CYAN);
               if (arg == "Magenta")
               setBackground(Color.MAGENTA);
               if (arg == "White")
               setBackground(Color.WHITE);
         public void itemStateChanged(ItemEvent ie)
              if (ie.getStateChange() == ItemEvent.SELECTED)
              setBackground(Color.RED);
              if (ie.getStateChange() == ItemEvent.SELECTED)
              setBackground(Color.YELLOW);
              if (ie.getStateChange() == ItemEvent.SELECTED)
              setBackground(Color.CYAN);
              if (ie.getStateChange() == ItemEvent.SELECTED)
              setBackground(Color.MAGENTA);
              if (ie.getStateChange() == ItemEvent.SELECTED)
              setBackground(Color.WHITE);
    }Thanks for your assistance

  • Forms don't submit when mixed w/ Javascript

    Greetings,
    I have a problem with a JSF application
    I have a JSF form with a number of text fields (h:inputText) and text areas. None are set to be required and all use the default validators, converters, etc. Each text element is bound to a String property of a backing bean. All works fine under 'normal' conditions. I submit the form, the values are all set on the backing bean, all is well.
    Next to one (or more) of the textfields, however, there is a "Select..." button (h:commandButton) with a javascript call on the 'onmousedown' event that launches a new window (this is a slightly modified version of the example found at http://forum.exadel.com/viewtopic.php?t=559 by Sergey Smirnov). The selected value in the popup window is used to set the value on the original form text field. Then the original form can be submitted.
    When I use one of these buttons to launch a new window (pop-up) with a JSF-based select list in it, I get unusual behavior. The syptoms I see are:
    1. If the popup list itself submits and refreshes (such as in the case of an indexed list, and the user selects a new index) the value is set properly on the 'opener' form, but when I submit the 'opener' form, the value reverts back to its previous (before the pop-up was launched) value.
    2. Especially with more than 1 pop-up on a form, I often see the case where I submit the form, and it simply refreshes itself, and all values are cleared from the form elements. My ActionListeners and other action events are never invoked. No messages are sent back to the page via the faces context. I get no notification of what went wrong.
    3. The behavior I get is hit or miss, sometimes it works well, other times it never works.
    4. Strangely, it seems that if I click more slowly, things tend to work better more often. Rapid clicking seems to make the failure much more likely.
    The Button looks like this:
    <h:inputText id="itemValue" value="#{item.value}"/>
    <h:inputHidden id="itemId" value="#{item.id}"/>
    <h:inputHidden id="itemTypeId" value="#{item.typeId}"/>
    <h:commandButton id="find" action="showList" value="Select..."
    onmousedown="showList(this,'itemValue', 'itemId', 'itemTypeId')"
    onclick="return false"/>
    The javascript showList() method registers the html components itemValue, itemId, and itemTypeId for callbacks, and launches a window using a pre-defined href value. Inside this window is a JSF page that lists all of the available items as h:commandLink objects. When one of the links is selected, the pop-up window calls a javascript function on the 'opener' window to set the itemValue, itemId, and itemTypeId values according to the selected item.
    function showList(action, nameFieldComponent, idFieldComponent, itemTypeIdComponent) {
    //url to the chooser.jsp file opened in the new window
    var href='<h:outputText value="#{bundle.chooser_javascript_href}" />';
    var features='<h:outputText value="#{bundle.chooser_javascript_window_properties}" />';
    <...snipped out details for brevity - resolves the form and component ids for callbacks >
    //open the new window
    winId=window.open(href,'chooserWindow',features);
    A javascript function in the chooser.jsp calls back and update() method, which sets the values on the name, id, and typeId form elements. All this works fine.
    It's AFTER all this, when I submit the form on the original page, that I get the errors.
    I suspect that somehow with more than 1 window open, I've managed to confuse the Faces navigation and view management - does anybody have any insights to help me solve the problem?
    Also, how can I better debug what is happening on the server when my action listener is never getting invoked?

    This is just a shot in the dark, but have you tried switching to client-side state saving?
    When you use server-side state saving, the JSF RI only keeps the state for one view around. If your pop-ups are created by JSF views, popping up one of them detroys the state for the main view on the server, which could cause the effects you describe. Switching to client-side state saving should solve this, because then the view state is held as hidden fields in each form instead, and hence, can't be destroyed.

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

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

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

Maybe you are looking for

  • Help, windows vista doesn't recognize iphone, can't restore

    Hello everyone, I'm having a problem syncing my iPhone 3g with iTunes to restore it. I received an iphone 3g 16gb from a friend because he didn't want to try to fix it. He told me it broke after he dropped it. Boots up to the apple logo and just stay

  • Tracking changes made to the finance quotation(CRMD_ORDER) line item

    Hi All, I want to track or identify changes made to the line item of a Finance quotation in Transaction CRMD_ORDER. User may change any where(any tab) at line item level. I found that CRM_ORDER_READ function module has one import parameter IV_ONLY_CH

  • Assign GL account to payment card error

    Frnds I am trying to post a billing doc form SD to FI and customer is paying by credit card, at the time of releasing the billing doc i am getting below error, please let me know if anyone had some thoughts on it. System Response     The system does

  • How to retrieve url attributes in a bsp ?

    Hi, I would like to create a BSP and then to be able to get and use an attribute from an url in it. Below an example because i think i'm not clear enough: I create a bsp ztest. And i want to access to this bsp with the following url: http(s):// Then,

  • EPM on solaris very slow and stops responding

    Hi, We installed EPM 11.1.2.2 using a single Managed server (EPMServer0) on Solaris with 32Gig memory and use the start.sh script to start all components. The applications runs fine initially but after second day it starts to slow down and then hangs