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

Similar Messages

  • 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?

  • 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

  • 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.

  • ActionEvent method in separate class

    Hello. I am currently working on a larger project, and I'm wanting to split it into two classes, so it's easier to find my way around
    I want one class to contain the main class, and the GUI, and my Actions. (One for the actionListeners, and one for my inPutMaps)
    In the other class I want to have my methods, including the method that is run in both my Actions. (They only contain the method)
    I've tried doing this, but it gives me an error in both my ActionEvents.
    Here is the code.
    package pack;
    /* Imports */
    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.AbstractAction;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    public class file1 extends JFrame implements ActionListener {
        /* Initialization */
        public JButton xPress, aPress;
        public JTextField textField;
        /* My main method */
        public static void main (String[] Args) {
            file1 frame = new file1();
            frame.setSize(200,120);
            frame.createGUI();
            frame.setVisible(true);
        /* The interface */
        private void createGUI() {
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            Container window = getContentPane();
            window.setLayout(new FlowLayout());
            /* Creating an instance of the second file */
            file2 method = new file2();
            /* My button, that responds when you press x, or click it */
            xPress = new JButton("Press x");
            window.add(xPress);
            xPress.addActionListener(this);
            /* My button, that responds when you press a, or click it */
            aPress = new JButton("Press a");
            window.add(aPress);
            aPress.addActionListener(this);
            /* The inPutMap for my button. */
            xPress.getInputMap(JButton.WHEN_IN_FOCUSED_WINDOW)
                    .put(KeyStroke.getKeyStroke('x'), "changeText");
            aPress.getInputMap(JButton.WHEN_IN_FOCUSED_WINDOW)
                    .put(KeyStroke.getKeyStroke('a'), "changeText");
            /* The textfield that allows me to see
             if the button has been pressed */
            textField = new JTextField("Button hasn't been pressed");
            window.add(textField);
            /* The action that is invoked. This only
             * works when you press your keyboard */
            AbstractAction action = new AbstractAction("action") {
                public void actionPerformed(ActionEvent e) {
                    method.performAction(e);
            /* The actionMaps for my buttons
             * "changeText" is an actionMapKey
             * that connects it to an inPutMap
             * action is as an AbstractAction */
            xPress.getActionMap().put("changeText", action);
            aPress.getActionMap().put("changeText", action);
        /* The actionPerformed for my actionlisteners
         * This only works when you press the button with your mouse */
        public void actionPerformed(ActionEvent e) {
            method.performAction(e);
    }And the second class, with the method:
    package pack;
    import java.awt.event.ActionEvent;
    import javax.swing.JButton;
    import javax.swing.JTextField;
    public class file2 {
        public JButton xPress, aPress;
        public JTextField textField;
        /* The method that is run when either of the two
         * actionPerformed are run */
        public void performAction(ActionEvent e)
             Object source = e.getSource();
            if (source == xPress) {
                textField.setText("x has been pressed");
            if (source == aPress) {
                textField.setText("a has been pressed");
    }It gives me an error in both the ActionPerformed.

    Try this:
    public class file1 extends JFrame implements ActionListener {
        private file2 method;
        private void createGUI() {
            /* Creating an instance of the second file */
            method = new file2(this);
    import java.awt.event.*;
    public class file2 {
        private file1 file1;
        public file2(file1 file1) {
            this.file1 = file1;
        /* The method that is run when either of the two
         * actionPerformed are run */
        public void performAction(ActionEvent e) {
            Object source = e.getSource();
            if (source == file1.xPress) {
                file1.textField.setText("x has been pressed");
            if (source == file1.aPress) {
                file1.textField.setText("a has been pressed");
    }

  • How is constructing an ActionEvent used?

    This is a general question about ActionEvents. I don't really know that much about ActionListeners and such, I am still a newbie learner, but that way I usually use an ActionEvent is as such
    public void actionPerformed(ActionEvent e)
    {}However I've seen that you can construct an ActionEvent, with all sorts of initial properties, and I was just wondering if somebody could explain in what situation you would want to construct an ActionEvent object, and what that actually means. Also how do you fire this ActionEvent object that you have already created.
    Usually I have buttons which I add ActionListeners to, and then the ActionHandler will define that method I stated above. In this scenario, the ActionEvent is automatically fired somehow by the button when I press it. But if I create an ActionEvent object how would i use it, or fire it the same way a button knows how to fire an event. Thanks in advance

    You could create your own event in support of a custom component, for example.
    On how to fire the event see the api for javax.swing.event.EventListenerList. It has nice sample code.

  • 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 .

  • 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

  • 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");
    }

  • Should I care about BT not available? Or... Is Deep Sleep safe??

    As many others here from what I've seen, BT in not available from time to time. I would rather put my MB to sleep rather than shut it down completely. I've downloaded the Deep Sleep Widget and I'm thinking of using this every time BT becomes unavailable. It seems that BT is not available more and more these days.
    I don't use BT for anything and I'm wondering if it's safe to use Deep Sleep to put MB to bed each night.
    Is it OK to use DS on my MB when BT is MIA?
    Thanks

    So what does this mean? Does this mean that if I am
    going to spawn a thread which updates a Swing
    component, that any code which modifies that component
    (say setText, or setLocation, etc...), I should wrap
    those commands inside Runnable and pass them to
    SwingUtilities.invokeAndWait()???If the code that is updating the Swing component is not actually in the Swing thread, then you do have to do that. The Swing thread, by the way, is the one that calls your ActionListeners and other component listeners like them. So you can update Swing components directly from Swing listeners, but otherwise you have to do the invokeAndWait business.
    Do I only have to do this if I think there may be
    multiple threads accessing the Swing object at the
    same thing? I assume so...Yes. And remember that the Swing thread is one of those multiple threads; refer back to the previous comment.
    An example I'm dealing with is updating a
    JProgressBar. I create multiple threads at startup to
    get initial values. These commands take time and it is
    much faster to start them all at once rather than run
    them sequentially. However, each job then increments
    the JProgressBar when it completes. I figured this is
    as good example as any of violating this "Thead Safe"
    issue, since you have multiple threads trying to
    update a single Swing component.Yes, that's a good example.

  • 2 buttonhandlers in 1 class?

    Hi all,
    Just started at school with Java.
    So i'm learning ass much as a can, anyway i'm bizzy with making a calculator and when i press a button i learned @ school that you make a class:
    class button1 implements ActionListener {
    public void actionPerformed(ActionEvent e){
    action //etc...
    Oke this works fine with 1 button.
    But when I use multiple buttons they say at school for each button you've got to make a new class, so:
    class button1 implements ActionListener {
    public void actionPerformed(ActionEvent e){
    action //etc...
    class button2 implements ActionListener {
    public void actionPerformed(ActionEvent e){
    action //etc...
    etc...
    My question is: isn't it possible to put all the actions in 1 class?
    Like:
    class button1 implements ActionListener {
    public void button1(ActionEvent e){ //or sometthing
    action //etc...
    public void button2, etc, etc...
    So that i dont need to make 50 classes?
    Thanx in advance!
    Johan

    I have a similiar problem, except with my program i have two JButton's that have ActionListeners and two JTextFields that have ActionListeners. The information put into the two JTextFields has to be used when the either of the JButtons is pressed. My problem is I cannot get java to store the information inputed into the JTextFields so that the JButtons can use it once they are pressed. It really just an Addition/Subtraction calculator. here is the code i have so far that is not working. Im stumped on how to get the input from the two JTextFields to be stored so when the JButtons are pressed it uses that input to calculate the result. Please if you can offer any help it is greatly appreaciated.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.applet.*;
    public class IntegerCalculatorPanel extends JPanel{
    private JButton getsum, subtract;
    private JLabel operand1label, operand2label, operation, Result;
    private JTextField operand1, operand2;
    IntegerCalculator myCalculator = new IntegerCalculator(0,0);
    int value1, value2, result;
    public IntegerCalculatorPanel() {
    getsum = new JButton ("+");
    subtract = new JButton ("-");
    getsum.addActionListener (new ActionListen());
    subtract.addActionListener(new ActionListen());
    Result = new JLabel("Result");
    operation = new JLabel ("Enter second operand:");
    operand1label = new JLabel ("Enter first operand:");
    operand2label = new JLabel ("Enter second operand:");
    operand1 = new JTextField (10);
    operand2 = new JTextField (10);
    operand1label.setText("Enter first operand:");
    operand1.addActionListener(new ActionListen());
    operand2label.setText("Enter second operand:");
    operand2.addActionListener(new ActionListen());
    operation.setText("Select operation");
    Result.setText("Result:" + result);
    add(operand1label);
    add(operand1);
    add(operand2label);
    add(operand2);
    add(operation);
    add(getsum);
    add(subtract);
    add(Result);
    setPreferredSize (new Dimension(275, 100));
    setBackground (Color.yellow);
    setLayout (new FlowLayout());
    private class ActionListen implements ActionListener{
    public void actionPerformed(ActionEvent event)
    if (event.getSource() == getsum);
    Result.setText("Result:" + myCalculator.getsum());
    }

  • Displaying TOOL TIP message over an applet

    Hi,
    How to display a tooltip(hint) like message when the mouse moves over an applet. Here is the rough source code, Please do the needful.
    import java.applet.*;
    import java.awt.*;
    public class Dis extends Applet implements MouseListner
         public void init()
              setLayout(null);
              ButtonAb b = new ButtonAb("click me"); //this is another class that is being called here, this class extends Component, I have written all ActionListeners and MouseListeners in this class only
              b.add();
         //public void addMouseListener(MouseEvent me)
    When the mouse moves over the Button("click me"), a hint box or tooltip like message should be displayed. It is easy doing with VB or Swing, but I wanted to it with AWT. Please give me some source code also.
    Thanks in advance
    Uma

    There are several ways to implement tooltip in awt. I prefere a general ToolTip class that can be added to any Component, and that is easy to use:
    something like this:Button but;
    but = new Button("Push");
    add(but);
    new ToolTip(but, "Push this button if you want to push this button");The code above should add a ToolTip to the java.awt.Button, so that everytime the mouse hoovers over the button, the message gets displayed.
    The idea is to make a ToolTip that can be added to any java.awt.Component using one line of code only. How do one achive that? Ok, here is a pseudo implementation of the ToolTip class:class ToolTip extends java.awt.Canvas implements Runnable, MouseListener, MouseMotionListener
       private String m_strText;
       private Component m_Component;
       private Thread m_Thread;
       private int m_iX;
       private int m_iY;
       public ToolTip(Component comp, String strText);
          m_strText = strText;
          m_Component = comp;
          comp.addMouseMotionListener(this);
          comp.addMouseListener(this);
       public void run()
          try{
             Thread.sleep(500);
             // Here its time to display the tooltip:
             // We need to add it.
             Component comp = this;
             while((!comp instanceof Applet) &&
                     (!comp instanceof Frame))
                comp = comp.getParent();
             ((Container)comp).add(this);
             int x,y,w,h;
             x = m_iX+m_Component.getLocationOnScreen().x-comp.getLocationOnScreen.x;
             y = m_iY+m_Component.getLocationOnScreen().y - comp.getLocationOnScreen.y;
             h=30;
             w=getFontMetrics().stringWidth(m_strText);
             setBounds(x,y,w,h);
          cathc(InterruptedException e)
       public void mouseEntered(MouseEvent e)
          start(e.getX(), e.getY());
       private void start(int iX, int iY);
          m_iX = iX;
          m_iY = iY;
          m_Thread = new Thread(this);
          m_Thread.start();
       public void mouseExited(MouseEvent e)
          stop();
       public void mouseMoved(MouseEvent e)
          stop();
          start(e.getX(), e.getY());
       private void stop()
          if(m_Thread != null)
             m_Thread.interrupt();
          Container parent = getParent();
          if(parent != null)
             parent.remove(this);
       public void paint(Graphics g)
          g.drawString(m_strText, 0, 20);
          g.drawRect(0,0,getSize().width, getSize().height);
    }The baseclass could be changed to java.awt.Window.
    using Window gives the ToolTip the posibillity to extend beyond the borders of the Applet (or the Frame), but in IE it gives you the "warning applet window" displayed on the botton of every ToolTip.
    Ragnvald Barth
    Software engineer

  • Can U help me change "Paint.java" to MVC model

    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollBar;
    import javax.swing.JTextField;
    import javax.swing.ImageIcon;
    public class Paint extends Applet implements ActionListener, AdjustmentListener, MouseListener, MouseMotionListener
    private static final long serialVersionUID = 1L;
    private final int NO_OP = 0;
    private final int PEN_OP = 1;
    private final int LINE_OP = 2;
    private final int ERASER_OP = 3;
    private final int CLEAR_OP = 4;
    private final int RECT_OP = 5;
    private final int OVAL_OP = 6;
    private final int FRECT_OP = 7;
    private final int FOVAL_OP = 8;
    private final int SPLINE_OP = 9;
    private final int POLY_OP = 10;
    private int mousex = 0;
    private int mousey = 0;
    private int prevx = 0;
    private int prevy = 0;
    private boolean initialPen = true;
    private boolean initialLine = true;
    private boolean initialEraser = true;
    private boolean initialRect = true;
    private boolean initialOval = true;
    private boolean initialFRect = true;
    private boolean initialFOval = true;
    private boolean initialPolygon = true;
    private boolean initialSpline = true;
    private int Orx = 0;
    private int Ory = 0;
    private int OrWidth = 0;
    private int OrHeight = 0;
    private int drawX = 0;
    private int drawY = 0;
    private int eraserLength = 5;
    private int udefRedValue = 255;
    private int udefGreenValue = 255;
    private int udefBlueValue = 255;
    private int opStatus = PEN_OP;
    private int colorStatus = 1;
    private Color mainColor = new Color(0,0,0);
    private Color xorColor = new Color(255,255,255);
    private Color statusBarColor = new Color(166,166,255);
    private Color userDefinedColor = new Color(udefRedValue,udefGreenValue,udefBlueValue);
    private JButton penButton           = new JButton(new ImageIcon(getClass().getResource("pen.gif")));
    private JButton lineButton           = new JButton(new ImageIcon(getClass().getResource("line.gif")));
    private JButton eraserButton           = new JButton(new ImageIcon(getClass().getResource("eraser.gif")));
    private JButton clearButton = new JButton("Clear");
    private JButton rectButton           = new JButton(new ImageIcon(getClass().getResource("rec.gif")));
    private JButton ovalButton           = new JButton(new ImageIcon(getClass().getResource("oval.gif")));
    private JButton fillRectButton      = new JButton(new ImageIcon(getClass().getResource("fillrec.gif")));
    private JButton fillOvalButton      = new JButton(new ImageIcon(getClass().getResource("filloval.gif")));
    private JButton splineButton = new JButton("Spline");
    private JButton polygonButton = new JButton("Polygon");
    private JButton blackButton = new JButton("Black");
    private JButton blueButton = new JButton("Blue");
    private JButton redButton = new JButton("Red");
    private JButton greenButton = new JButton("Green");
    private JButton purpleButton = new JButton("Purple");
    private JButton orangeButton = new JButton("Orange");
    private JButton pinkButton = new JButton("Pink");
    private JButton grayButton = new JButton("Gray");
    private JButton yellowButton = new JButton("Yellow");
    private JButton userDefButton = new JButton("User-Def");
    private JScrollBar redSlider = new JScrollBar(Scrollbar.HORIZONTAL, 0, 1, 0, 255);
    private JScrollBar blueSlider = new JScrollBar(Scrollbar.HORIZONTAL, 0, 1, 0, 255);
    private JScrollBar greenSlider = new JScrollBar(Scrollbar.HORIZONTAL, 0, 1, 0, 255);
    private JTextField colorStatusBar = new JTextField(20);
    private JTextField opStatusBar = new JTextField(20);
    private JTextField mouseStatusBar = new JTextField(10);
    private JTextField redValue = new JTextField(3);
    private JTextField greenValue = new JTextField(3);
    private JTextField blueValue = new JTextField(3);
    private JLabel operationLabel = new JLabel(" Tool mode:");
    private JLabel colorLabel = new JLabel(" Color mode:");
    private JLabel cursorLabel = new JLabel(" Cursor:");
    private JPanel ToolbarPanel = new JPanel(new GridLayout(11,2,0,0));
    private JPanel drawPanel = new JPanel();
    private JPanel statusPanel = new JPanel();
    private JPanel udefcolPanel = new JPanel(new GridLayout(3,3,0,0));
    private JPanel udefdemcolPanel = new JPanel();
    private JPanel PicPanel               = new JPanel();
    public void init()
    setLayout(new BorderLayout());
    ToolbarPanel.add(blackButton);
    ToolbarPanel.add(blueButton);
    ToolbarPanel.add(redButton);
    ToolbarPanel.add(greenButton);
    ToolbarPanel.add(purpleButton);
    ToolbarPanel.add(orangeButton);
    ToolbarPanel.add(pinkButton);
    ToolbarPanel.add(grayButton);
    ToolbarPanel.add(yellowButton);
    ToolbarPanel.add(userDefButton);
    blueButton.setBackground(Color.blue);
    redButton.setBackground(Color.red);
    greenButton.setBackground(Color.green);
    purpleButton.setBackground(Color.magenta);
    orangeButton.setBackground(Color.orange);
    pinkButton.setBackground(Color.pink);
    grayButton.setBackground(Color.gray);
    yellowButton.setBackground(Color.yellow);
    userDefButton.setBackground(userDefinedColor);
    ToolbarPanel.add(penButton);
    ToolbarPanel.add(lineButton);
    ToolbarPanel.add(eraserButton);
    ToolbarPanel.add(clearButton);
    ToolbarPanel.add(rectButton);
    ToolbarPanel.add(ovalButton);
    ToolbarPanel.add(fillRectButton);
    ToolbarPanel.add(fillOvalButton);
    ToolbarPanel.add(splineButton);
    ToolbarPanel.add(polygonButton);
    ToolbarPanel.setBounds(0,0,100,300);
    ToolbarPanel.add(udefcolPanel);
    ToolbarPanel.add(udefdemcolPanel);
    udefcolPanel.add(redValue);
    udefcolPanel.add(redSlider);
    udefcolPanel.add(greenValue);
    udefcolPanel.add(greenSlider);
    udefcolPanel.add(blueValue);
    udefcolPanel.add(blueSlider);
    statusPanel.add(colorLabel);
    statusPanel.add(colorStatusBar);
    statusPanel.add(operationLabel);
    statusPanel.add(opStatusBar);
    statusPanel.add(cursorLabel);
    statusPanel.add(mouseStatusBar);
    colorStatusBar.setEditable(false);
    opStatusBar.setEditable(false);
    mouseStatusBar.setEditable(false);
    statusPanel.setBackground(statusBarColor);
    ToolbarPanel.setBackground(Color.white);
    drawPanel.setBackground(Color.white);
    add(statusPanel, "North");
    add(ToolbarPanel, "West");
    add(drawPanel, "Center");
    penButton.addActionListener(this);
    lineButton.addActionListener(this);
    eraserButton.addActionListener(this);
    clearButton.addActionListener(this);
    rectButton.addActionListener(this);
    ovalButton.addActionListener(this);
    fillRectButton.addActionListener(this);
    fillOvalButton.addActionListener(this);
    splineButton.addActionListener(this);
    polygonButton.addActionListener(this);
    blackButton.addActionListener(this);
    blueButton.addActionListener(this);
    redButton.addActionListener(this);
    greenButton.addActionListener(this);
    purpleButton.addActionListener(this);
    orangeButton.addActionListener(this);
    pinkButton.addActionListener(this);
    grayButton.addActionListener(this);
    yellowButton.addActionListener(this);
    userDefButton.addActionListener(this);
    redSlider.addAdjustmentListener(this);
    blueSlider.addAdjustmentListener(this);
    greenSlider.addAdjustmentListener(this);
    drawPanel.addMouseMotionListener(this);
    drawPanel.addMouseListener(this);
    // this.addMouseListener(this);
    // this.addMouseMotionListener(this);
    updateRGBValues();
    opStatusBar.setText("Pen");
    colorStatusBar.setText("Black");
    public void actionPerformed(ActionEvent e)
         penButton.setActionCommand("Pen");
         lineButton.setActionCommand("Line");
         eraserButton.setActionCommand("Eraser");
         rectButton.setActionCommand("Rectangle");
         ovalButton.setActionCommand("Oval");
         fillRectButton.setActionCommand("Filled Rectangle");
         fillOvalButton.setActionCommand("Filled Oval");
         if (e.getActionCommand() == "Pen")
         opStatus = PEN_OP;
         else if (e.getActionCommand() == "Line")
         opStatus = LINE_OP;
         else if (e.getActionCommand() == "Eraser")
         opStatus = ERASER_OP;
         else if (e.getActionCommand() == "Clear")
         opStatus = CLEAR_OP;
         else if (e.getActionCommand() == "Rectangle")
         opStatus = RECT_OP;
         else if (e.getActionCommand() == "Oval")
         opStatus = OVAL_OP;
         else if (e.getActionCommand() == "Filled Rectangle")
         opStatus = FRECT_OP;
         else if (e.getActionCommand() == "Filled Oval")
         opStatus = FOVAL_OP;
         else if (e.getActionCommand() == "Polygon")
         opStatus = POLY_OP;
         else if (e.getActionCommand() == "Spline")
         opStatus = SPLINE_OP;
         else if (e.getActionCommand() == "Black")
         colorStatus = 1;
         else if (e.getActionCommand() == "Blue")
         colorStatus = 2;
         else if (e.getActionCommand() == "Green")
         colorStatus = 3;
         else if (e.getActionCommand() == "Red")
         colorStatus = 4;
         else if (e.getActionCommand() == "Purple")
         colorStatus = 5;
         else if (e.getActionCommand() == "Orange")
         colorStatus = 6;
         else if (e.getActionCommand() == "Pink")
         colorStatus = 7;
         else if (e.getActionCommand() == "Gray")
         colorStatus = 8;
         else if (e.getActionCommand() == "Yellow")
         colorStatus = 9;
         else if (e.getActionCommand() == "User-Def")
         colorStatus = 10;
    initialPolygon = true;
    initialSpline = true;
    switch (opStatus)
    case PEN_OP : opStatusBar.setText("Pen");
    break;
    case LINE_OP : opStatusBar.setText("Line");
    break;
    case ERASER_OP: opStatusBar.setText("Eraser");
    break;
    case CLEAR_OP : clearPanel(drawPanel);
    break;
    case RECT_OP : opStatusBar.setText("Rectangle");
    break;
    case OVAL_OP : opStatusBar.setText("Oval");
    break;
    case FRECT_OP : opStatusBar.setText("Fill-Rectangle");
    break;
    case FOVAL_OP : opStatusBar.setText("Fill-Oval");
    break;
    case POLY_OP : opStatusBar.setText("Polygon");
    break;
    case SPLINE_OP: opStatusBar.setText("Spline");
    break;
    switch (colorStatus)
    case 1: colorStatusBar.setText("Black");
    break;
    case 2: colorStatusBar.setText("Blue");
    break;
    case 3: colorStatusBar.setText("Green");
    break;
    case 4: colorStatusBar.setText("Red");
    break;
    case 5: colorStatusBar.setText("Purple");
    break;
    case 6: colorStatusBar.setText("Orange");
    break;
    case 7: colorStatusBar.setText("Pink");
    break;
    case 8: colorStatusBar.setText("Gray");
    break;
    case 9: colorStatusBar.setText("Yellow");
    break;
    case 10: colorStatusBar.setText("User Defined Color");
    break;
    setMainColor();
    updateRGBValues();
    public void adjustmentValueChanged(AdjustmentEvent e)
    updateRGBValues();
    public void clearPanel(JPanel drawPanel2)
    opStatusBar.setText("Clear");
    Graphics g = drawPanel2.getGraphics();
    g.setColor(drawPanel2.getBackground());
    g.fillRect(0,0,drawPanel2.getBounds().width,drawPanel2.getBounds().height);
    public void penOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    if (initialPen)
    setGraphicalDefaults(e);
    initialPen = false;
    g.drawLine(prevx,prevy,mousex,mousey);
    if (mouseHasMoved(e))
    mousex = e.getX();
    mousey = e.getY();
    g.drawLine(prevx,prevy,mousex,mousey);
    prevx = mousex;
    prevy = mousey;
    public void lineOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    if (initialLine)
    setGraphicalDefaults(e);
    g.setXORMode(xorColor);
    g.drawLine(Orx,Ory,mousex,mousey);
    initialLine=false;
    if (mouseHasMoved(e))
    g.setXORMode(xorColor);
    g.drawLine(Orx,Ory,mousex,mousey);
    mousex = e.getX();
    mousey = e.getY();
    g.drawLine(Orx,Ory,mousex,mousey);
    public void rectOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    if (initialRect)
    setGraphicalDefaults(e);
    initialRect = false;
    if (mouseHasMoved(e))
    g.setXORMode(drawPanel.getBackground());
    g.drawRect(drawX,drawY,OrWidth,OrHeight);
    mousex = e.getX();
    mousey = e.getY();
    setActualBoundry();
    g.drawRect(drawX,drawY,OrWidth,OrHeight);
    public void ovalOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    if (initialOval)
    setGraphicalDefaults(e);
    initialOval=false;
    if (mouseHasMoved(e))
    g.setXORMode(xorColor);
    g.drawOval(drawX,drawY,OrWidth,OrHeight);
    mousex = e.getX();
    mousey = e.getY();
    setActualBoundry();
    g.drawOval(drawX,drawY,OrWidth,OrHeight);
    public void frectOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    if (initialFRect)
    setGraphicalDefaults(e);
    initialFRect=false;
    if (mouseHasMoved(e))
    g.setXORMode(xorColor);
    g.drawRect(drawX,drawY,OrWidth-1,OrHeight-1);
    mousex = e.getX();
    mousey = e.getY();
    setActualBoundry();
    g.drawRect(drawX,drawY,OrWidth-1,OrHeight-1);
    public void fovalOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    if (initialFOval)
    setGraphicalDefaults(e);
    initialFOval = false;
    if (mouseHasMoved(e))
    g.setXORMode(xorColor);
    g.drawOval(drawX,drawY,OrWidth,OrHeight);
    mousex = e.getX();
    mousey = e.getY();
    setActualBoundry();
    g.drawOval(drawX,drawY,OrWidth,OrHeight);
    public void eraserOperation(MouseEvent e)
    Graphics g = drawPanel.getGraphics();
    if (initialEraser)
    setGraphicalDefaults(e);
    initialEraser = false;
    g.setColor(mainColor.white);
    g.fillRect(mousex-eraserLength, mousey-eraserLength,eraserLength*2,eraserLength*2);
    g.setColor(Color.black);
    g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
    prevx = mousex;
    prevy = mousey;
    if (mouseHasMoved(e))
    g.setColor(mainColor.white);
    g.drawRect(prevx-eraserLength, prevy-eraserLength,eraserLength*2,eraserLength*2);
    mousex = e.getX();
    mousey = e.getY();
    g.setColor(mainColor.white);
    g.fillRect(mousex-eraserLength, mousey-eraserLength,eraserLength*2,eraserLength*2);
    g.setColor(Color.black);
    g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
    prevx = mousex;
    prevy = mousey;
    public void polygonOperation(MouseEvent e)
    if (initialPolygon)
    prevx = e.getX();
    prevy = e.getY();
    initialPolygon = false;
    else
    mousex = e.getX();
    mousey = e.getY();
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    g.drawLine(prevx,prevy,mousex,mousey);
    prevx = mousex;
    prevy = mousey;
    public void splineOperation(MouseEvent e)
    if(initialSpline)
    initialSpline = false;
    public boolean mouseHasMoved(MouseEvent e)
    return (mousex != e.getX() || mousey != e.getY());
    public void setActualBoundry()
    if (mousex < Orx || mousey < Ory)
    if (mousex < Orx)
    OrWidth = Orx - mousex;
    drawX = Orx - OrWidth;
    else
    drawX = Orx;
    OrWidth = mousex - Orx;
    if (mousey < Ory)
    OrHeight = Ory - mousey;
    drawY = Ory - OrHeight;
    else
    drawY = Ory;
    OrHeight = mousey - Ory;
    else
    drawX = Orx;
    drawY = Ory;
    OrWidth = mousex - Orx;
    OrHeight = mousey - Ory;
    public void setGraphicalDefaults(MouseEvent e)
    mousex = e.getX();
    mousey = e.getY();
    prevx = e.getX();
    prevy = e.getY();
    Orx = e.getX();
    Ory = e.getY();
    drawX = e.getX();
    drawY = e.getY();
    OrWidth = 0;
    OrHeight = 0;
    public void mouseDragged(MouseEvent e)
    updateMouseCoordinates(e);
    switch (opStatus)
    case PEN_OP : penOperation(e);
    break;
    case LINE_OP : lineOperation(e);
    break;
    case RECT_OP : rectOperation(e);
    break;
    case OVAL_OP : ovalOperation(e);
    break;
    case FRECT_OP : frectOperation(e);
    break;
    case FOVAL_OP : fovalOperation(e);
    break;
    case ERASER_OP: eraserOperation(e);
    break;
    public void mouseReleased(MouseEvent e)
    updateMouseCoordinates(e);
    switch (opStatus)
    case PEN_OP : releasedPen();
    break;
    case LINE_OP : releasedLine();
    break;
    case RECT_OP : releasedRect();
    break;
    case OVAL_OP : releasedOval();
    break;
    case FRECT_OP : releasedFRect();
    break;
    case FOVAL_OP : releasedFOval();
    break;
    case ERASER_OP : releasedEraser();
    break;
    public void mouseEntered(MouseEvent e)
    updateMouseCoordinates(e);
    public void setMainColor()
    switch (colorStatus)
    case 1 : mainColor = Color.black;
    break;
    case 2: mainColor = Color.blue;
    break;
    case 3: mainColor = Color.green;
    break;
    case 4: mainColor = Color.red;
    break;
    case 5: mainColor = Color.magenta;
    break;
    case 6: mainColor = Color.orange;
    break;
    case 7: mainColor = Color.pink;
    break;
    case 8: mainColor = Color.gray;
    break;
    case 9: mainColor = Color.yellow;
    break;
    case 10: mainColor = userDefinedColor;
    break;
    public void releasedPen()
    initialPen = true;
    public void releasedLine()
    if ((Math.abs(Orx-mousex)+Math.abs(Ory-mousey)) != 0)
    // System.out.println("Line has been released....");
    initialLine = true;
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    g.drawLine(Orx,Ory,mousex,mousey);
    public void releasedEraser()
    initialEraser = true;
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor.white);
    g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
    public void releasedRect()
    initialRect = true;
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    g.drawRect(drawX,drawY,OrWidth,OrHeight);
    public void releasedOval()
    initialOval = true;
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    g.drawOval(drawX,drawY,OrWidth,OrHeight);
    public void releasedFRect()
    initialFRect = true;
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    g.fillRect(drawX,drawY,OrWidth,OrHeight);
    public void releasedFOval()
    initialFOval = true;
    Graphics g = drawPanel.getGraphics();
    g.setColor(mainColor);
    g.fillOval(drawX,drawY,OrWidth,OrHeight);
    public void updateMouseCoordinates(MouseEvent e)
    String xCoor ="";
    String yCoor ="";
    if (e.getX() < 0) xCoor = "0";
    else
    xCoor = String.valueOf(e.getX());
    if (e.getY() < 0) xCoor = "0";
    else
    yCoor = String.valueOf(e.getY());
    mouseStatusBar.setText("x:"+xCoor+" y:"+yCoor);
    public void updateRGBValues()
    udefRedValue = redSlider.getValue();
    udefGreenValue = greenSlider.getValue();
    udefBlueValue = blueSlider.getValue();
    if (udefRedValue > 255)
    udefRedValue = 255;
    if (udefRedValue < 0 )
    udefRedValue =0;
    if (udefGreenValue > 255)
    udefGreenValue = 255;
    if (udefGreenValue < 0 )
    udefGreenValue =0;
    if (udefBlueValue > 255)
    udefBlueValue = 255;
    if (udefBlueValue < 0 )
    udefBlueValue =0;
    redValue.setText(String.valueOf(udefRedValue));
    greenValue.setText(String.valueOf(udefGreenValue));
    blueValue.setText(String.valueOf(udefBlueValue));
    userDefinedColor = new Color(udefRedValue,udefGreenValue,udefBlueValue);
    userDefButton.setBackground(userDefinedColor);
    Graphics g = udefdemcolPanel.getGraphics();
    g.setColor(userDefinedColor);
    g.fillRect(0,0,800,800);
    public void mouseClicked(MouseEvent e)
    updateMouseCoordinates(e);
    switch (opStatus)
    case 9 : splineOperation(e);
    break;
    case 10 : polygonOperation(e);
    break;
    public void mouseExited(MouseEvent e)
    updateMouseCoordinates(e);
    public void mouseMoved(MouseEvent e)
    updateMouseCoordinates(e);
    public void mousePressed(MouseEvent e)
    updateMouseCoordinates(e);
    Edited by: eclipse on Feb 19, 2008 6:29 AM

    If you can't divide the class then you can't implement an MVC design methodology.
    This class is a giant mess and can be EASILY broken down into smaller classes. Seperate the visual components into their own classes. Create Model objects that contain the data behind your visual components.
    Split up your giant ActionListener into several smaller more specialized actionlisteners and create a Controller object that you can assign these listeners and models to. Allow the event handling to be done by the controller so it can propogate necessary data changes to the models, thus altering the Views.
    Thats it in a nutshell. It is not an easy answer.

Maybe you are looking for