Accessing a gui component directly via getSource()

Hi,
to access a gui component I can access it by getting its object variable and casting it to its class type, e.g.:
public class Tab02 extends JFrame {
     JTable tab = new JTable (rows, head);
     JTextField txt = new JTextField ("dimensions");
     JTree tree = new JTree(node.getRoot());
class DragDropNode implements TreeSelectionListener, MouseMotionListener, MouseListener {
public void mouseDragged (MouseEvent me ) {
     Cursor dragcurs = new Cursor(13);
// me.getSource().setCursor (mdragcurs) does not work as getSource delivers an object type
     JTree tmp = (JTree)me.getSource();
// me.getSource().setCursor (mdragcurs)
     tmp.setCursor (mdragcurs);     // as me.getSource().setCursor (mdragcurs)
     JTable tmp = (JTable )me.getSource();
     tmp.setCursor (mdragcurs);
How can I cast the object automatically to the genuine type?
Is there a method that returns the type and I can use this method to cast me.getSource()?
Thanks

Navigate to the folder enclosing it and enter Library in the Go to Folder command.
(70632)

Similar Messages

  • How do I access a gui component in a different class?

    I have a jpanel (mainwindow) in a japplet. mainwindow loads and displays a jpanel form (content1). How do I code a button on conent1 so that mainwindow loads and displays a different jpanel form(content2)? mainwindow, content1, and content2 are all in different classes/packages. Thanks in advance!

    Let your JPanel content1 forward its ActionEvents to its parent. For instance, you could define your content1 as follows:
    public class Content1 extends JPanel
        private ArrayList<ActionListener> actionListeners;
        private JButton myButton;
              public Content1()
             actionListeners = new ArrayList<ActionListener>();
             myButton = new JButton("Test");
             myButton.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             forwardAction(e);
              public void addActionListener(ActionListener listener) {
             actionListeners.add(listener);
        protected void forwardAction(ActionEvent e) {
          for (ActionListener l: actionListeners) {
               l.actionPerformed(e);
    }Then you could let your mainWindow listen to content1:
    // in your main windows' code:
    Content1 content1 = new Content1();
    content1.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
              swapPane(e);    // create a method swapPane in your mainwindow that handles the switch to content2.
    });

  • Can you access i store directly via app TV

    can you access i store directly via app TV

    Welcome to the Apple Community.
    Yes, you can rent and purchase content directly from the Apple TV.

  • How to get change a GUI component from another class?

    Hi there,
    I'm currently trying to change a GUI component in my 'Application' class from my 'Dice' class.
    So the Application class sets up some GUI including a JLabel that initially displays "Change".
    The 'Dice' class contains the ActionPerformed() method for when the 'Change' button (made from Application class) is clicked.
    And it returns an 'int' between 1 and 6.
    Now I want to set this number back int he JLabel from the Application class.
    APPLICATION CLASS
    import javax.swing.*;
    import java.awt.*;
    import java.util.Random;
    import java.awt.event.*;
    public class Application extends JFrame implements ActionListener{
         public JPanel rollDicePanel = new JPanel();
         public JLabel dice = new JLabel("Loser");
         public Container contentPane = getContentPane();
         public JButton button = new JButton("Change");
         public Dice diceClass = new Dice();
         public Application() {}
         public static void main(String[] args)
              Application application = new Application();
              application.addGUIComponents();
         public void addGUIComponents()
              contentPane.setLayout(new BorderLayout());
              rollDicePanel.add(dice);
            button.addActionListener(diceClass);
            contentPane.add(rollDicePanel, BorderLayout.SOUTH);
            contentPane.add(button,BorderLayout.NORTH);
              this.setSize(460, 655);
              this.setVisible(true);
              this.setResizable(false);
         public void changeDice()
              dice.setText("Hello");
         public void actionPerformed(ActionEvent e) {}
    }DICE
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class Dice implements ActionListener
         public Dice() {}
         public void actionPerformed(ActionEvent e)
              //super.actionPerformed(e);
              String event = e.getActionCommand();
              if(event.equals("Change"))
                   System.out.println("Will be about to change the 'dice' label");
                   Application application = new Application();
                   application.dice.setText("Hello");
    }

    It's all about references, baby. The Dice object needs a way to communicate with the Application object, and so Dice needs a reference to Application. There are many ways to pass this. In my example I pass the application object directly to Dice, but a better way would use interfaces and some indirection. Look up the Observer pattern for a better way to do this that scales much better than my brute-force approach.
    import javax.swing.*;
    import java.awt.*;
    public class Application extends JFrame // *** implements ActionListener
        // *** make all of these fields private ***
        private JPanel rollDicePanel = new JPanel();
        private JLabel dice = new JLabel("Loser");
        private Container contentPane = getContentPane();
        private JButton button = new JButton("Change");
        // *** pass a reference to your application ("this")
        // *** to your Dice object:
        private Dice diceClass = new Dice(this);
        public Application()
        public static void main(String[] args)
            Application application = new Application();
            application.addGUIComponents();
        public void addGUIComponents()
            contentPane.setLayout(new BorderLayout());
            rollDicePanel.add(dice);
            button.addActionListener(diceClass);
            contentPane.add(rollDicePanel, BorderLayout.SOUTH);
            contentPane.add(button, BorderLayout.NORTH);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setPreferredSize(new Dimension(460, 655));
            pack();
            setLocationRelativeTo(null);
            setVisible(true);
            setResizable(false);
        // *** I'm not sure what this is supposed to be doing, so I commented it out.
        //public void changeDice()
            //dice.setText("Hello");
        // *** ditto.  I strongly dislike making a GUI class implement ActionListeenr
        //public void actionPerformed(ActionEvent e)
        // *** here's the public method that the Dice object calls
        public void setTextDiceLabel(String text)
            dice.setText(text);
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class Dice implements ActionListener
        // *** have a variable that holds a reference to your application object
        private Application application;
        private boolean hello = true;
        public Dice(Application application)
            // *** get that reference via a constructor parameter (one way to do this)
            this.application = application;
        public void actionPerformed(ActionEvent e)
            String event = e.getActionCommand();
            if (event.equals("Change"))
                System.out.println("Will be about to change the 'dice' label");
                if (hello)
                    // *** call the application's public method
                    application.setTextDiceLabel("Hello");
                else
                    application.setTextDiceLabel("Goodbye");
                hello = !hello;
                //Application application = new Application();
                //application.dice.setText("Hello");
    }

  • Trying to access the java script files via jar file in WEB SERVER

    hi all,
    I am trying to access the java script files via jar file ,which is present in Apache webserver in order to minimise the number of hits to app server.some thing like cache ...
    in jsp the code goes like this...
         <script type="text/javascript"  archive="http://localhost:14000/dojo.jar!" src="dojo.jar/parser.js" " ></script>{code}
    But i am not able to access the js file which is put in jar file present in the  webserver.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Hi,
    You can use DWR (Direct Web remoting) for that. It is easy AJAX for java. ou can directly call the java script function from java class and also java class from javaScripts..
    Regards,
    Hardik

  • Cannot access the content producer portal via reverse proxy

    Hi all,
    I hope my post is in the right forum
    We have an FPN environment using RRA with our EP (NW 7.0 SPS18) as the consumer and our BI portal (NW 7.0 SPS18) as the content producer.  The consumer is registered with the producer using HTTP protocol.  Everything works as expected.
    We're trying to implement an Apache reverse proxy for our FPN with SSL termination so that we can access the portals from the Internet with HTTPS protocol while keeping HTTP protocol for the internal users.
    Through the reverse proxy, we can access the consumer portal and we can access the producer portal directly without any problem.  The only problem is that, if we logged onto the consumer via the reverse proxy, we cannot access the content from the producer.  We'd get the browser security warning message
    "Although this page is encrypted.  The information you have entered will be sent over an unencrypted connection. ..."
    When we hit the Continue button, we'd get the eror 404 Not Found - The request resource does not exist.
    Our Unix admin tried both Apache and SAP Web Dispatcher but we couldn't get it to work properly.  We went through a lot of blogs and documents and we are at our wits end.  We would greatly appreciate if someone can point out where we should look at.
    Thank you very much in advance.
    Dao

    Hi Kevin,
    Unfortunately, our Unix admin thinks you missed the point because my question was not clear enough
    We do not have problems with the "correct name" in the reverse proxy and our main SSL termination works fine. 
    It's just that the consumer is registered with the producer using HTTP protocol; as a result, the producer's URL link is 'hard-coded' to use HTTP protocol in the consumer portal since we are not using SSL in the internal network.  Hence, we'd like to know if there's any way to change them to HTTPS for the Internet clients while keeping the HTTP protocol for the internal users.
    I hope I made it clearer this time
    Regards,
    Dao

  • Cisco 4400 WLC - Accessing web gui remotely

    I know how to access the GUI from the service port. However, I am not able to access from Port 0. IPs have all been properly set. We have a management VLAN in our enterprise. I have configured the WLC management interface for an ip on that subnet. Port 0 is connected to a 3560G switch. I have set the switch port to be an access port to the management vlan and I have tried to set the switch port as a trunk, with the native vlan set to the management vlan. I am not able to ping nor access the web GUI remotely via the management vlan. Is this by design?
    Jeff

    Hi Jeff,
    plz try to configure 0 as vlan on managment interface on WLC after configuring native vlan on the switch. if you havent tried it yet.
    command - config interface vlan management 0
    NOTe - you need to disabl all wlan that r mapped with management interface before doing any changes from CLI.
    hope it will solve your prob.
    Thanks

  • Unauthorised users accessing iviews through a direct URL

    Hi,
    How do you prevent unauthorised users from accessing iviews through a direct URL? e.g. From the BeX Web Template on testing a query a URL is known, this URL can then be used by user who have no rights to view/ execute this report (after portal logon).
    Can security zones be defined for the BeX iviews? If yes, how? Does setting the parameter Dcom.sap.nw.sz=true solve the problem? 
    Appreciate your input.
    Many thanks,
    Dharmi

    Hi Bharath,
    Thank you for the input.
    Can you please be more specific as to which BW component ?
    I navigated to
    Go to permission editor: 'System Administration' -> 'Permissions' -> 'Portal Permissions'.
    folder: 'Security Zones' -> 'sap.com' -> 'NetWeaver.Portal' -> 'high_safety'
    There the rights are ok.
    Best regards,
    Dharmi

  • Thread wont update GUI component

    I'm developing an RMI application. I can't seem to get the gui components to show their value once their value has been set. I know the value has been set because i can retrieve it and print it out using System.out.println("Client status : " + lblYourStatus.getText());
    My thread gets called when there's a Property ChangeEvent, the code executes correctly but the gui component still doesn't show the correct value.
    Am i implementing the code for the thread incorrectly? or am i missing something else?
    Any help would be appreciated, this has been wrecking my head for a while now.
    private void jPanel1PropertyChange(java.beans.PropertyChangeEvent evt) {
    System.out.println("in propertyChange()");
    // lblYourStatus.setText(clientStatus);
    Thread t = new Thread(this);
    t.setDaemon(true);
    t.start();
    public void run()
    // while (true)
    try
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    lblYourStatus.setText(clientStatus);
    System.out.println("Client status : " + lblYourStatus.getText());
    catch (Exception e)
    try
    Thread.sleep(1000);
    catch(Exception e) {}
    // } //end while
    }

    I don't think the RMI can affect it. It's the same for one client as it is for multiple clients. All the clients receive the correct values. I have been using System.out.println() statements to follow the program as it's been executing and everything seems to work as it should. I changed the code using the example you directed me to.
    It still receives all the correct values but when i set the label text the gui still doesn't show the text if i pass it in as a variable eg lblPlayer1Name.setText(m_player1Name), it still shows literal values eg lblPlayer1Name.setText( "test")
    I know the variable names contain valid values as i use System.out.println() statements to view them.
    any more ideas? thanks for your help so far.
        private void jPanel1PropertyChange(java.beans.PropertyChangeEvent evt) {
            Thread t = new Thread(this);
           // t.setDaemon(true);
            t.start();
        public void updateDetails(boolean gameInProgress, String status, String player1Name, String player2Name, int numSpectators)
            m_clientStatus = m_clientStatus + status;
            m_player1Name = player1Name;
            m_player2Name = player2Name;
            lblYourStatus.setText(m_clientStatus);       
            lblPlayer1Name.setText(m_player1Name);
            lblPlayer2Name.setText(m_player2Name);
        public void run()          
            //  SwingUtilities makes sure code is executed in the event thread.                                        
            SwingUtilities.invokeLater(new Runnable()                              
                public void run()                              
                    //this line wont print the value to the screen eventhough the next System.out.println() statement shows that the variable contains a valid string                              
                    lblPlayer1Name.setText(m_player1Name);     
                    System.out.println("Player 1 variable value: " + m_player1Name);
                    System.out.println("Player 1 label value: " + lblPlayer1Name.getText());
                    lblPlayer1Name.setText(lblPlayer1Name.getText());
                    //this line will print the literal string "Tom" to the label
                    lblPlayer1Name.setText("Tom");     
            // simulate log running task                              
          //  try { Thread.sleep(1000); }                         
          //  catch (Exception e) {}                    
            SwingUtilities.invokeLater(new Runnable()               
                public void run()                              
                    lblPlayer2Name.setText(m_player2Name);
                    System.out.println("Player 2 variable value: " + m_player2Name);
                    System.out.println("Player 2 label value: " + lblPlayer2Name.getText());
        }

  • Is there a voice recording app for ipad that shares directly via iMessage (not just email) - like voice memos does on iphone?

    Does any-one perhaps know whether there's a voice recording app for ipad that shares directly via iMessage (not just email) - like voice memo does on iphone?

    You can't do anything in the background of iOS. Apps are still one at a time (with a few exceptions like Music), and suspend when the app is closed. It's also against the App Store guidelines to sell apps that would allow such actions.
    Though, maybe you could get your Voice Memos saved to MP3's, which can play in the background of other apps.

  • Is it possible to virtually bypass the battery on a macbook pro (retina 2014) and power the mac directly via AC power?

    Is it possible to virtually bypass the battery on a macbook pro (retina 2014) and power the mac directly via AC power?
    E.g. Dell allows you to plug the laptop into AC power but prevent battery charging.
    Note: I do not want to physically remove the battery.
    If there isn't an option on Mac OS, is there anything I can download to bypass the battery when I want?

    Thanks for linking me! Wow I had no idea the clock speed would be cut so severely! What a bunch of rubbish, as if the AC won't provide enough power!
    I guess the only solution to my question would be an app which virtually disconnects the battery but tricks the mac into thinking the battery is still connected. I'm just surprised Apple haven't yet started to build prisons for the government - considering how well they lock up their software and hardware!

  • A sort of KeyListener without a GUI Component?

    a sort of KeyListener without a GUI Component? ( or any trick that will do)?
    please be patient with my question
    I can't express myself very well but it's very important.
    Please help me I need an example how to implement
    a way to detect some combination of keystrokes in java without
    any GUI ( without AWT or Swing frames ...)
    just the console (DOS or Linux shell window) or with a minimzed
    java frame (awt or swing...) you know, MINIMIZED= not in focus.
    in other words if the user press ctrl + alt +shift ...or some
    other combination... ANYTIME ,and the java program is running in the
    background, is there a way to detect that,
    ... my problem if I use a frame (AWT or SWING) the windows must
    be in focus and NOT MINIMIZED..
    if I use
    someObject.addKeylistener(someComponent);
    then the "someComponent" must be in focus, am I right?
    What I'm coding is a program that if you highlight ANY text in
    ANY OS window, a java window (frame) should pop up and match the
    selected text in a dictionary file and brings me the meaning
    ( or a person's phone number , or
    a book author ...etc.)
    MY CHALLENGE IS WITHOUT PRESSING (Ctrl+C) to copy and paste
    ...etc. and WITHOUT MONITORING THE OS's CLIPBOARD ...I just want to
    have the feature that the user simply highlight a text in ANY
    window anywhere then press Ctrl+shift or some other combination,
    then MY JAVA PROGRAM IS TRIGGERED and it should EMULATE SOME
    KEYSTROKES OF Ctrl+C and then paste the clipboard
    somewhere in my program...with all that AUTOMATION BEING in the background.
    remember that my whole program ALL THE TIME MUST BE MINIMIZED AND
    NOT IN FOCUS
    or just running in the background (using javaw)..
    is there any trick ? pleeeeeeze!!!
    i'm not trying to write a sort of the spying so-called "key-logger"
    purely in java but it's a very similar challenge.
    please reply if you have questions
    I you could please answer me , then guys this would be very
    valuable technique that I need urgently. Thanks!

    DO NOT CROSS POST especially since this has nothing to do with game development at all. I can understand if it was in Java programming and New to Java but even then pick a forum and post it to that one and that one only.

  • Unable to access a windows 7 Workstation via RDP

    Hi,
    I have a windows 7 Pro SP1 workstation that I’m unable to access from any other machine via RDP...
    This is a domain environment.
    The machine in question is 100% up to date. (WSUS)
    It's running an up-to-date anti-virus solution and has been scanned. (Panda cloud) (No firewall)
    This is on a local network, no router involved.
    Can ping the machine, can see network shares.
    Checked that it's listening on the correct port.
    Necessary services are running and are starting correctly.
    Configured RDP correctly and tried different configurations (with and without NLA and adding/removing users)
    This machine seems to be able to RDP into other machines, it just wont accept any sessions.
    Assigning the necessary exclusions in firewall - no effect
    Firewall is disabled by GPO and I have stopped the service - no effect.
    Deleted the computer certificate - no effect.
    uninstalled the RDP 8 update - no effect
    Tried using both the IP and hostname - no difference
    I'm completely out of ideas, no other machine I tested with is having this issue and all the domain machines are running same AV and same GPO's are applied.
    Re-installation is not an option.
    Below is the error - very unhelpful.
    Kind Regards,
    Stephen

    Hi Hinte,
    Here are the results:
    Here is the netstat result - can't see 3389 anywhere:
    Active Connections
      Proto  Local Address          Foreign Address        State           PID
      TCP    0.0.0.0:135            0.0.0.0:0              LISTENING       1060
      RpcSs
     [svchost.exe]
      TCP    0.0.0.0:445            0.0.0.0:0              LISTENING       4
     Can not obtain ownership information
      TCP    0.0.0.0:623            0.0.0.0:0              LISTENING       4124
     [LMS.exe]
      TCP    0.0.0.0:16992          0.0.0.0:0              LISTENING       4124
     [LMS.exe]
      TCP    0.0.0.0:18226          0.0.0.0:0              LISTENING       2476
     [WAHost.exe]
      TCP    0.0.0.0:49152          0.0.0.0:0              LISTENING       532
     [wininit.exe]
      TCP    0.0.0.0:49153          0.0.0.0:0              LISTENING       1140
      eventlog
     [svchost.exe]
      TCP    0.0.0.0:49154          0.0.0.0:0              LISTENING       1292
      Schedule
     [svchost.exe]
      TCP    0.0.0.0:49185          0.0.0.0:0              LISTENING       624
     [lsass.exe]
      TCP    0.0.0.0:49187          0.0.0.0:0              LISTENING       600
     [services.exe]
      TCP    0.0.0.0:49192          0.0.0.0:0              LISTENING       3268
      PolicyAgent
     [svchost.exe]
      TCP    127.0.0.1:5939         0.0.0.0:0              LISTENING       2360
     [TeamViewer_Service.exe]
      TCP    127.0.0.1:5939         127.0.0.1:49206        ESTABLISHED     2360
     [TeamViewer_Service.exe]
      TCP    127.0.0.1:5939         127.0.0.1:49234        ESTABLISHED     2360
     [TeamViewer_Service.exe]
      TCP    127.0.0.1:49204        127.0.0.1:49205        ESTABLISHED     3856
     [TeamViewer_Desktop.exe]
      TCP    127.0.0.1:49205        127.0.0.1:49204        ESTABLISHED     3856
     [TeamViewer_Desktop.exe]
      TCP    127.0.0.1:49206        127.0.0.1:5939         ESTABLISHED     3856
     [TeamViewer_Desktop.exe]
      TCP    127.0.0.1:49232        127.0.0.1:49233        ESTABLISHED     2660
     [TeamViewer.exe]
      TCP    127.0.0.1:49233        127.0.0.1:49232        ESTABLISHED     2660
     [TeamViewer.exe]
      TCP    127.0.0.1:49234        127.0.0.1:5939         ESTABLISHED     2660
     [TeamViewer.exe]
      TCP    127.0.0.1:49241        0.0.0.0:0              LISTENING       4552
     [UNS.exe]
      TCP    192.168.100.22:139     0.0.0.0:0              LISTENING       4
     Can not obtain ownership information
      TCP    192.168.100.22:49201   92.51.156.72:443       ESTABLISHED     2360
     [TeamViewer_Service.exe]
      TCP    192.168.100.22:49203   197.85.190.46:443      ESTABLISHED     2360
     [TeamViewer_Service.exe]
      TCP    192.168.100.22:49211   192.168.100.5:445      ESTABLISHED     4
     Can not obtain ownership information
      TCP    192.168.100.22:49231   192.168.100.5:49159    ESTABLISHED     1732
     [spoolsv.exe]
      TCP    [::]:135               [::]:0                 LISTENING      
    1060
      RpcSs
     [svchost.exe]
      TCP    [::]:445               [::]:0                 LISTENING      
    4
     Can not obtain ownership information
      TCP    [::]:623               [::]:0                 LISTENING      
    4124
     [LMS.exe]
      TCP    [::]:16992             [::]:0                 LISTENING      
    4124
     [LMS.exe]
      TCP    [::]:49152             [::]:0                 LISTENING      
    532
     [wininit.exe]
      TCP    [::]:49153             [::]:0                 LISTENING      
    1140
      eventlog
     [svchost.exe]
      TCP    [::]:49154             [::]:0                 LISTENING      
    1292
      Schedule
     [svchost.exe]
      TCP    [::]:49185             [::]:0                 LISTENING      
    624
     [lsass.exe]
      TCP    [::]:49187             [::]:0                 LISTENING      
    600
     [services.exe]
      TCP    [::]:49192             [::]:0                 LISTENING      
    3268
      PolicyAgent
     [svchost.exe]
      TCP    [::1]:49179            [::]:0                 LISTENING       2008
     [jhi_service.exe]
      TCP    [::1]:49237            [::1]:49239            ESTABLISHED     4124
     [LMS.exe]
      TCP    [::1]:49239            [::1]:49237            ESTABLISHED     4124
     [LMS.exe]
      UDP    0.0.0.0:123            *:*                                   
    1256
      W32Time
     [svchost.exe]
      UDP    0.0.0.0:500            *:*                                   
    1292
      IKEEXT
     [svchost.exe]
      UDP    0.0.0.0:4500           *:*                                   
    1292
      IKEEXT
     [svchost.exe]
      UDP    0.0.0.0:5355           *:*                                   
    1540
      Dnscache
     [svchost.exe]
      UDP    0.0.0.0:21226          *:*                                   
    2476
     [WAHost.exe]
      UDP    127.0.0.1:50083        *:*                                   
    1400
      gpsvc
     [svchost.exe]
      UDP    127.0.0.1:55096        *:*                                   
    624
     [lsass.exe]
      UDP    127.0.0.1:60632        *:*                                   
    1540
      NlaSvc
     [svchost.exe]
      UDP    127.0.0.1:64416        *:*                                   
    4416
     [IntelSmallBusinessAdvantage.exe]
      UDP    192.168.100.22:137     *:*                                   
    4
     Can not obtain ownership information
      UDP    192.168.100.22:138     *:*                                   
    4
     Can not obtain ownership information
      UDP    [::]:123               *:*                                   
    1256
      W32Time
     [svchost.exe]
      UDP    [::]:500               *:*                                   
    1292
      IKEEXT
     [svchost.exe]
      UDP    [::]:4500              *:*                                   
    1292
      IKEEXT
     [svchost.exe]
      UDP    [::]:5355              *:*                                   
    1540
      Dnscache
     [svchost.exe]
      UDP    [fe80::3447:c85a:1d2d:4ff9%11]:546  *:*                                   
    1140
      Dhcp
     [svchost.exe]

  • Using my new GUI component in an applet :Help!!!

    I am seeking help for the following
    Define class MyColorChooser as a new component so it can be reused in other applications or applets. We want to use the new GUI component as part of an applet that displays the current Color value.
    The following is the code of MyColorChooser class
    * a) We define a class called MyColorChooser that provides three JSlider
    * objects and three JTextField objects. Each JSlider represents the values
    * from 0 to 255 for the red, green and blue parts of a color.
    * We use wred, green and blue values as the arguments to the Color contructeur
    * to create a new Color object.
    * We display the current value of each JSlider in the corresponding JTextField.
    * When the user changes the value of the JSlider, the JTextField(s) should be changed
    * accordingly as weel as the current color.
    * b)Define class MyColorChooser so it can be reused in other applications or applets.
    * Use your new GUI component as part of an applet that displays the current
    * Color value.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    public class MyChooserColor extends JFrame{
         private int red, green, blue;  // color shade for red, green and blue
         private static Color myColor;  // color resultant from red, green and blue shades
         private JSlider mySlider [];      
         private JTextField textField [];
    // Panels for sliders, textfields and button components
         private JPanel mySliderPanel, textFieldPanel, buttonPanel;
    // sublcass objet of JPanel for drawing purposes
         private CustomPanel myPanel;
         private JButton okButton, exitButton;
         public MyChooserColor ()     
              super( "HOME MADE COLOR COMPONENT; composition of RGB values " );
    //       setting properties of the mySlider array and registering the events
              mySlider = new JSlider [3];
              ChangeHandler handler = new ChangeHandler();
              for (int i = 0; i < mySlider.length; i++)
              {     mySlider[i] = new JSlider( SwingConstants.HORIZONTAL,
                               0, 255, 255 );
                   mySlider.setMajorTickSpacing( 10 );
                   mySlider[i].setPaintTicks( true );
    //      register events for mySlider[i]
                   mySlider[i].addChangeListener( handler);                     
    //      setting properties of the textField array           
              textField = new JTextField [3];          
              for (int i = 0; i < textField.length; i++)
              {     textField[i] = new JTextField("100.00%", 5 );
                   textField[i].setEditable(false);
                   textField[i].setBackground(Color.white);
    // initial Background color of each slider and foreground for each textfield
    // accordingly to its current color shade
              mySlider[0].setBackground(
                        new Color ( mySlider[0].getValue(), 0, 0 ) );
              textField[0].setForeground(
                        new Color ( mySlider[0].getValue(), 0, 0 ) );           
              mySlider[1].setBackground(
                        new Color ( 0, mySlider[1].getValue(), 0 ) );
              textField[1].setForeground(
                        new Color ( 0, mySlider[1].getValue(), 0 ) );
              mySlider[2].setBackground(
                        new Color ( 0, 0, mySlider[2].getValue() ) );
              textField[2].setForeground(
                        new Color ( 0, 0, mySlider[2].getValue() ) );
    // initialize myColor to white
              myColor = Color.WHITE;
    // instanciate myPanel for drawing purposes          
              myPanel = new CustomPanel();
              myPanel.setBackground(myColor);
    // instanciate okButton with its inanymous class
    // to handle its related events
              okButton = new JButton ("OK");
              okButton.setToolTipText("To confirm the current color");
              okButton.setMnemonic('o');
              okButton.addActionListener(
                   new ActionListener(){
                        public void actionPerformed (ActionEvent e)
                        {     // code permetting to transfer
                             // the current color to the parent
                             // component backgroung color
                             //System.exit( 0 );     
    //      instanciate exitButton with its inanymous class
    //      to handle its related events           
              exitButton = new JButton("Exit");
              exitButton.setToolTipText("Exit the application");
              exitButton.setMnemonic('x');
              exitButton.addActionListener(
                        new ActionListener(){
                             public void actionPerformed (ActionEvent e)
                             {     System.exit( 0 );     
    // define the contentPane
              Container c = getContentPane();
              c.setLayout( new BorderLayout() );
    //     panel as container for sliders
              mySliderPanel = new JPanel(new BorderLayout());
    //      panel as container for textFields           
              textFieldPanel = new JPanel(new FlowLayout());
    //      panel as container for Jbuttons components           
              buttonPanel = new JPanel ();
              buttonPanel.setLayout( new BoxLayout( buttonPanel, BoxLayout.Y_AXIS ) );
    //add the Jbutton components to buttonPanel           
              buttonPanel.add(okButton);
              buttonPanel.add(exitButton);
    //     add the mySlider components to mySliderPanel
              mySliderPanel.add(mySlider[0], BorderLayout.NORTH);
              mySliderPanel.add(mySlider[1], BorderLayout.CENTER);
              mySliderPanel.add(mySlider[2], BorderLayout.SOUTH);
    //add the textField components to textFieldPanel     
              for (int i = 0; i < textField.length; i++){
                   textFieldPanel.add(textField[i]);
    // add the panels to the container c          
              c.add( mySliderPanel, BorderLayout.NORTH );
              c.add( buttonPanel, BorderLayout.WEST);
              c.add( textFieldPanel, BorderLayout.SOUTH);
              c.add( myPanel, BorderLayout.CENTER );
              setSize(500, 300);          
              show();               
    //     inner class for mySlider events handling
         private class ChangeHandler implements ChangeListener {          
              public void stateChanged( ChangeEvent e )
    // start by collecting the current color shade
    // for red , forgreen and for blue               
                   setRedColor(mySlider[0].getValue());
                   setGreenColor(mySlider[1].getValue());
                   setBlueColor(mySlider[2].getValue());
    //The textcolor in myPanel (subclass of JPanel for drawing purposes)
                   myPanel.setMyTextColor( ( 255 - getRedColor() ),
                             ( 255 - getGreenColor() ), ( 255 - getBlueColor() ) );
    //call to repaint() occurs here
                   myPanel.setThumbSlider1( getRedColor() );
                   myPanel.setThumbSlider2( getGreenColor() );
                   myPanel.setThumbSlider3( getBlueColor() );
    // display color value in the textFields (%)
                   DecimalFormat twoDigits = new DecimalFormat ("0.00");
                   for (int i = 0; i < textField.length; i++){
                        textField[i].setText("" + twoDigits.format(
                                  100.0* mySlider[i].getValue()/255) + " %") ;
    // seting the textcolor for each textField
    // and the background color for each slider               
                   textField[0].setForeground(
                             new Color ( getRedColor(), 0, 0 ) );
                   mySlider[0].setBackground(
                             new Color ( getRedColor(), 0, 0) );
                   textField[1].setForeground(
                             new Color ( 0, getGreenColor() , 0 ) );
                   mySlider[1].setBackground(
                             new Color ( 0, getGreenColor(), 0) );
                   textField[2].setForeground(
                             new Color ( 0, 0, getBlueColor() ) );
                   mySlider[2].setBackground(
                             new Color ( 0, 0, getBlueColor() ) );
    // color of myPanel background
                   myColor = new Color (getRedColor(),
                             getGreenColor(), getBlueColor());
                   myPanel.setBackground(myColor);               
    // set methods to set the basic color shade
         private void setRedColor (int r){
              red = ( (r >= 0 && r <= 255) ? r : 255 );
         private void setGreenColor (int g){
              green = ( (g >= 0 && g <= 255) ? g : 255 );
         private void setBlueColor (int b){
              blue = ( (b >= 0 && b <= 255) ? b : 255 );
    // get methods (return the basic color shade)
         private int getRedColor (){
              return red ;
         private int getGreenColor (){
              return green;
         private int getBlueColor (){
              return blue;
         public static Color getMyColor (){
              return myColor;
    // main method                
         public static void main (String args []){
              MyChooserColor app = new MyChooserColor();
              app.addWindowListener(
                        new WindowAdapter() {
                             public void windowClosing( WindowEvent e )
                             {     System.exit( 0 );
    // inner class CustomPanel for drawing purposes
         private class CustomPanel extends JPanel {
              private int thumbSlider1 = 255;
              private int thumbSlider2 = 255;
              private int thumbSlider3 = 255;
              private Color myTextColor;
              public void paintComponent( Graphics g )
                   super.paintComponent( g );
                   g.setColor(myTextColor);
                   g.setFont( new Font( "Serif", Font.TRUETYPE_FONT, 12 ) );
                   DecimalFormat twoDigits = new DecimalFormat ("0.00");
                   g.drawString( "The RGB values of the current color are : "
                             + "( "     + thumbSlider1 + " , " + thumbSlider2 + " , "
                             + thumbSlider3 + " )", 10, 40);
                   g.drawString( "The current background color is composed by " +
                             "the folllowing RGB colors " , 10, 60);
                   g.drawString( "Percentage of RED from slider1 : "
                        + twoDigits.format(thumbSlider1*100.0/255), 10, 80 );
                   g.drawString( "Percentage of GREEN from slider2 : "
                        + twoDigits.format(thumbSlider2*100.0/255), 10, 100 );
                   g.drawString( "Percentage of BLUE from slider3 : "
                        + twoDigits.format(thumbSlider3*100.0/255), 10, 120 );
    // call to repaint occurs here     
              public void setThumbSlider1(int th){
                   thumbSlider1 = (th >= 0 ? th: 255 );
                   repaint();
              public void setThumbSlider2(int th){
                   thumbSlider2 = (th >= 0 ? th: 255 );
                   repaint();
              public void setThumbSlider3(int th){
                   thumbSlider3 = (th >= 0 ? th: 255 );
                   repaint();
              public void setMyTextColor(int r, int g, int b){
                   myTextColor = new Color(r, g, b);
                   repaint();
    //The following method is used by layout managers
              public Dimension getPreferredSize()
              {     return new Dimension( 150, 100 );
    The following is the code of application that tests the component
    //Application used to demonstrating
    // the homemade GUI MyChooserColor component
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ShowMyColor extends JFrame {
         private JButton changeColor;
         private Color color = Color.lightGray;
         private Container c;
         MyChooserColor colorComponent;
         public ShowMyColor()
         {     super( "Using MyChooserColor" );
              c = getContentPane();
              c.setLayout( new FlowLayout() );
              changeColor = new JButton( "Change Color" );
              changeColor.addActionListener(
                        new ActionListener() {
                             public void actionPerformed( ActionEvent e )
                             {     colorComponent = new MyChooserColor ();
                                  colorComponent.show();
                                  color = MyChooserColor.getMyColor();
                                  if ( color == null )
                                       color = Color.lightGray;
                                  c.setBackground( color );
                                  c.repaint();
              c.add( changeColor );
              setSize( 400, 130 );
              show();
         public static void main( String args[] )
         {     ShowMyColor app = new ShowMyColor();
              app.addWindowListener(
                        new WindowAdapter() {
                             public void windowClosing( WindowEvent e )
                             {  System.exit( 0 );

    Yes, I want help for the missing code to add in actionPerformed method below. As a result, when you confirm the selected color (clicking the OK button), it will be transferred to a variable color of class ShowMyColor.
    // instanciate okButton with its inanymous class
    // to handle its related events
              okButton = new JButton ("OK");
              okButton.setToolTipText("To confirm the current color");
              okButton.setMnemonic('o');
              okButton.addActionListener(
                   new ActionListener(){
                        public void actionPerformed (ActionEvent e)
                        {     // code permetting to transfer
                             // the current color to the parent
                             // component backgroung color
                             //System.exit( 0 );     
              );

  • Updating a GUI component from a runnable class that doesn't know that GUI

    Hi. I have a problem that I think isn't solvable in an elegant way, but I'd like to get confirmation before I do it the dirty way.
    My application allows the user to save (and load) his work in sessions files. I implemented this by a serializable class "Session" that basically stores all the information that the user created or the settings he made in its member variables.
    Now, I obviously want the session files created by this to be as small as possible and therefore I made sure that no GUI components are stored in this class.
    When the user has made all his settings, he can basically "run" his project, which may last for a long time (minutes, hours or days, depending on what the user wants to do....). Therefore I need to update the GUI with information on the progress/outcome of the running project. This is not just a matter of updating one single GUI component, but of a dynamic number of different internal frames and panels. So I'd need a reference to a GUI component that knows all these subcomponents to run a method that does the update work.
    How do I do that? I cannot pass the reference to that component through the method's argument that "runs" the project, because that needs to be a seperate thread, meaning that the method is just the run() method of that thread which has no arguments (which I cannot modify if I'm not mistaken).
    So the only thing I can think of is passing the reference through the constructor of the runnable class (which in turn must be stored in the session because it contains critical information on the user's work). As a result, all components that need to be incorporated in that updating process would be part of the session and go into the exported file, which is exactly what I wanted to avoid.
    I hope this description makes sense...
    Thanks in advance!

    Thanks for the quick answer! Though to be honest I am not sure how it relates to my question. Which is probably my fault rather than yours :-)
    But sometimes all it takes me to solve my problem is posting it to a forum and reading it through again :)
    Now I wrote a seperate class "Runner" that extends thread and has the gui components as members (passed through its constructor). I create and start() that object in the run method of the original runnable class (which isn't runnable anymore) so I can pass the gui component reference through that run method's argument.
    Not sure if this is elegant, but at least it allows me to avoid saving gui components to the session file :-)
    I am realizing that probably this post shouldn't have gone into the swing forum...

Maybe you are looking for

  • It is no longer possible to use ALT + N and ALT + P from the "get info" window.

    On a PC, previously, when in the "get info" windows, it was possible to use ALT + N and ALT + P to switch to the song information for the next and previous song.  Since the update to the newest iTunes, it's no longer possible.  Has anybody found a ke

  • 1.4.2_01 and 1.4.2_02 difference

    Is there any documentation on the difference between JRE 1.4.2_01 and 1.4.2_02. I can find the docs for enhancements and changes for 1.4.2 but not for this. Cheers

  • Download Mainstage 2?

    I have a computer that runs 10.7.4 and can't upgrade to Mavericks because it is pre 2007. Is there anywhere I can download Mainstage 2 safely?

  • Custom item does not appear on Hotsync Menu

    I have a Sprint Treo 700p.  My work email was converted to Outlook from GroupWise.  I am able to sync successfully, but received a message about changing profiles and conduits.  I tried to do this by clicking the Hotsync icon in system tray.  The men

  • Adobe Capture 3.0 install media and license

    Hi, Seriously need some help here. We have a custoemr that used Adobe Captire 3.0 as part of a scanning solution that worked with Kofax, an old version. We are currently redeploying this oriignal solution but the client has misplaced the media and we