Trying to create Netbeans Swing/GUI component

Hello,
I'm trying to create a GUI component from the following code. The main idea is to create a component consisting of a checkbox and a panel. The panel can contain several other swing components. By checking or unchecking the checkbox I want all by components in the panel to be enabled or disabled.
The important thing is that this component should work in the Netbeans GUI designer. I'm using Netbeans 5.5.
My problem is the following:
When adding my swing component to the Netbeans swing component palette and dragging onto a new form, I cannot assign other components to the main panel of my component. Even if I use the Inspector tree to drag components to be children of my component, the mouse icon shows a denying icon.
If I add swing components programmatically, it works.
Can somebody give me an advice what I should change in my code to make it work with the Netbeans GUI designer?
Below you can find the current code of my standalone component. It includes a main() method so one can give it a try.
Many thanks in advance!
package test.swing;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JEnabler extends JPanel {
    private JCheckBox checkEnabler = new JCheckBox();
    private JPanel contentPane = new JPanel();
    public JEnabler() {
        super.setLayout(new BorderLayout());
        checkEnabler.setSelected(true);
        checkEnabler.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        checkEnabler.setMargin(new Insets(0, 0, 0, 0));
        checkEnabler.setVerticalAlignment(SwingConstants.TOP);
        checkEnabler.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                checkEnablerActionPerformed(evt);
        super.addImpl(checkEnabler, BorderLayout.WEST, -1);
        super.addImpl(contentPane, BorderLayout.CENTER, -1);
    private void checkEnablerActionPerformed(ActionEvent evt) {
        Component[] list = contentPane.getComponents();
        for (int i=0; i<list.length; i++)
            list.setEnabled(checkEnabler.isSelected());
protected void addImpl(Component comp, Object constraints, int index) {
contentPane.add(comp, constraints, index);
public LayoutManager getLayout() {
return contentPane.getLayout();
public void setLayout(LayoutManager mgr) {
if (contentPane!=null)
contentPane.setLayout(mgr);
public void remove(Component comp) {
contentPane.remove(comp);
public void remove(int index) {
contentPane.remove(index);
public void removeAll() {
contentPane.removeAll();
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JEnabler enabler = new JEnabler();
JTextField tf = new JTextField("Test");
enabler.add(tf);
JButton test = new JButton("Click");
enabler.add(test);
frame.getContentPane().add(enabler);
frame.pack();
frame.setVisible(true);

Can anyone tell me what I am missing?
public void paintComponents(Graphics g)you're not 'missing' anything, in fact you've gained an 's'

Similar Messages

  • How to display multiple tables from database using netbeans swing gui

    plz reply asap on how to display multiple tables from database using netbeans swing gui into the same project

    Layered Pane with JTables or you can easily to it with a little scripting and HTML.
    plzzzzzzzzzzzzzzzzz, do not use SMS speak when posting.

  • Creating Undo Menu on Swing GUI

    Undo Menu is to be Created on Swing GUI on the Graphics. In the Tutorial, Undo with Text is given. But on implementing the logic of Undo with Text , some Errors come.

    You can use javax.swing.undo.* stuff only with classes implementing
    javax.swing.text.Document interface.
    To add undo/redo functionality for some Graphic components you should program this mechanism by yourself.
    So create your own object model, track all changes and implement/add appropriate listeners.

  • Can not change vendor when creating a new Development Component in NWDS

    Dear friends,
    Im trying to create a new Development Component in NWDS. Our NWDS is connected to NWDI and we are using CM Services option of NWDI.
    Before I could create a DC and change the vendor but now I cant change it anymore. Now, the vendor is by default sap.com and we cant change it and it seems that we also have to put our project in a separate directory. home/ directory or other directories in the list.
    See below screen shots...
    If I make a new DC than we see it like this: home/bpm_test [sap.com].
    If I make a new DC in my LocalDevelopment I can change the vendor and I dont have to choose a home directory.
    Do you have any idea how to change that?
    Any help would be greatly appreciated.
    Thank you in advance,

    HI,
    it seems that the vendor is defined in the NWDI track. That's why you can't change it.
    regards,
    Vasils

  • Creating a custom JSF Component

    Hi,
    I am trying to create a custom JSF Component. My ultimate goal is to pass a bean to my custom component and have the component render some HTML output based on the info contained in the bean. Before I attempt that I am trying to get a simple custom component to just work. This component is based on the tutorial found here: http://www.jsftutorials.net/components/index.html
    This tutorial just creates a component that outputs a <div> tag around the body contents of the custom component.
    To keep this short I have done the following items from the tutorial link above:
    1) I have created the tld file defining the tag class, name, uri and shortname
    2) I have also created the tag class called TickerTag.java along with the component class UITicker.java. These classes are straight copy-and-paste jobs from the tutorial link and compile fine.
    3)My faces-config.xml file has the proper component definition of
    <component>
    <component-type>ticker</component-type>
    <component-class>ticker.UITicker</component-class>
    </component>
    This was the easy part. The example then goes on to use the custom component in a JSP page. I managed to get the custom component to work in a JSP page BUT my problem is getting the custom component to work in an XHTML file.
    I thought all I had to do was define an xml namespace using the uri from my tld file like so:
    Note: My uri is www.fubar.com/tags and is defined in the tld file.
    <html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:t="http://myfaces.apache.org/tomahawk"
    xmlns:u="http://www.fubar.com/tags">
    I then try to use the tag like so <u:ticker> <f:verbatim>Hello JSF Component</f:verbatim></u:ticker>
    I am expecting the following output: <div>Hello JSF Component
    </div>
    but instead I get
    <u:ticker>Hello JSF Component</u:ticker>
    It seems the tag is not even processed. This is my first jump into custom components. I have done custom JSP tags in the past but I never tried to display them on an XHTML page.
    If you are wondering why I am using XHTML pages, this was setup a while back by a previous developer. Changing everything to a JSP would take a long time and probably break some stuff I am not aware of yet. As such the web.xml file of this JSF web app has the following:
    <context-param>
    <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
    <param-value>.xhtml</param-value>
    </context-param>
    So all *.jsf files are processed and sent to the corresponding .xhtml file.
    I have looked up creating custom components on google and every last example uses their newly created components in a jsp file. No XHTML uses so far.
    Below are my tld files and xhtml file if that helps:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
    <taglib>
    <tlib-version>1.0</tlib-version>
    <jsp-version>1.2</jsp-version>
    <short-name>u</short-name>
    <uri>http://www.fubar.com/tags</uri>
    <tag>
    <name>ticker</name>
    <tag-class>ticker.TickerTag</tag-class>
    <body-content>JSP</body-content>
    </tag>
    </taglib>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:t="http://myfaces.apache.org/tomahawk"
    xmlns:u="http://www.fubar.com/tags">
    <html>
    <head>
    <title>Show Custom Component</title>
    </head>
    <body>
    <f:view>
    <u:ticker> <f:verbatim>Hello JSF Component</f:verbatim></u:ticker>
    </f:view>
    </body>
    </html>
    Any suggestions/help are much appreciated,
    Nick
    </div>

    Thanks Ray. I'll take a look at that site.
    I managed to figure out my problem. I never created a .taglib.xml file that reference the component I defined in the faces-config.xml file. Once I did that everything work perfectly.
    I managed to use this forum post as a guide.
    http://osdir.com/ml/java.facelets.user/2006-12/msg00042.html
    I hope this helps anyone else.
    Nick

  • Getting error while creating Service controller from component controller

    Hi,
    I have added CAF model in used model for DC project.But when i m trying to create service controller from component controller by selecting used model it is giving error like "Context element cannot be bound to model layer".
    Can anybody help me out on this issue.
    Thanks in advance.

    Hello,
    try to check the check box in MS Word - File - Options - General - "Open e-mail attachements and other uneditable files in reading view"
    I am not sure how this option really works, but I think you will find it checked. So try to uncheck it.
    Or wise versa :c)
    Kind regards

  • Help - Bean Binding an SQL join to a gui component(jtable) in Netbeans?

    Good afternoon. I'd like to ask if there is a way to data bind an SQL Join from 2 or more tables to a
    GUI component(Jtable) in Netbeans. All the tutorials show is how to bind all the fields of 1 database table
    to the component. Under the BIND/ELements option the IMPORT DATA TO FORM menu only allows
    you to choose 1 among the database tables from a selected database.
    Is there a way to configure an SQL query and attach it to the component?
    Thanks.

    This is not a Swing problem. Try a NetBeans forum.

  • Component integration: Control framework / create your own gui controls

    Hi,
    Does anyone know where to find documentation about creating your own gui controls, like cl_gui_picture.
    For example we would like to make a zcl_gui_movie !!!
    Kind regards
    Keld Gregersen

    Hi Keld,
    Check out /people/thomas.jung3/blog/2004/09/01/using-net-windows-controls-in-the-abap-control-framework
    And
    /people/thomas.jung3/blog/2005/05/11/using-classic-activex-controls-in-the-abap-control-framework
    I have been able to create and use my own control in the SAP GUI - but I'm still trying to figure out how to handle any events raised by that control.
    If all you need to do is use the control to display something (like a movie!) it should work...
    If you can get some form of event processing working PLEASE let me know!!!
    Cheers,
    N

  • (Youtube-) Video in a Swing GUI

    Hey everyone,
    I'm currently trying to play a video in my Swing GUI with JMF but I really can't get it to work.
    With the help of google I got this far:
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.media.CannotRealizeException;
    import javax.media.Manager;
    import javax.media.NoPlayerException;
    import javax.media.Player;
    import javax.swing.JFrame;
    public class MediaPanel extends JFrame {
        public MediaPanel() {
            setLayout(new BorderLayout()); // use a BorderLayout
            // Use lightweight components for Swing compatibility
            Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, true);
            URL mediaURL = null;
            try {
                mediaURL = new URL("http://www.youtube.com/watch?v=Q7_Z_mQUBa8");
            } catch (MalformedURLException ex) {
                System.err.println(ex);
            try {
                // create a player to play the media specified in the URL
                Player mediaPlayer = Manager.createRealizedPlayer(mediaURL);
                // get the components for the video and the playback controls
                Component video = mediaPlayer.getVisualComponent();
                Component controls = mediaPlayer.getControlPanelComponent();
                if (video != null) {
                    add(video, BorderLayout.CENTER); // add video component
                if (controls != null) {
                    add(controls, BorderLayout.SOUTH); // add controls
                mediaPlayer.start(); // start playing the media clip
            } // end try
            catch (NoPlayerException noPlayerException) {
                System.err.println("No media player found");
            } // end catch
            catch (CannotRealizeException cannotRealizeException) {
                System.err.println("Could not realize media player");
            } // end catch
            catch (IOException iOException) {
                System.err.println("Error reading from the source");
            } // end catch
        } // end MediaPanel constructor
    }But all I get is errors:
    Warning: The URL may not exist. Please check URL
    No media player found
    Can you please please help me get this working? I would really appreciate a little walkthrough
    Best regards,
    Patrick
    Edited by: 954807 on Aug 24, 2012 6:52 AM

    Just use \ tags. People don't like to go to external sites.
    I really advise you to consider using JavaFX 2 here. Swing is old and not really supported anymore, JMF is also old and absolutely not supported anymore.                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • NetBean Swing or Swing without NetBean

    In previous posts I have mentioned about me using BlueJ. Ive tried NetBeans IDE and find it better than BlueJ so I am using NetBeans now. One area of NetBeans uses Swing GUI components which allows you to build GUIs and creates the source code for you. There seems to be alot of information in the Oracle tutorials on Swing outside Netbeans. and at the moment I am still learning the Java programming language and do not know how important learning Swing is. This leads me to the question: Is using Swing in NetBeans enough to get by in creating GUIs or what aspects in Swing are the most important to use in conjunction with Swing in NetBeans?

    You can do desktop or web application development (there are others). I suggest you do web application development instead of desktop since I believe there are more employment opportunites there. If you decide to go that route, I suggest you dump Swing and go with JSF. Its part of the recommended JEE technology stack (http://www.oracle.com//technetwork/java/javaee/tech/index.html). I also suggest you use either Netbeans IDE or Eclipse IDE since they are the most popular with experienced developers. You'll also need a (free) database. I suggest Oracle Express. For a server: Tomcat or Glassfish.
    I suggest the first book you read is on Java, then on Servlets, then on  JSF. I suggest you keep away from JSP, its older technology. However, you will eventually need to read up on it since so many web applications are written with it. You will probably need to maintain those types of web applications when employed. Which other technologies to study and in which order in the above mentioned link is a subject for another day.

  • Creating word processor gui question

    Hi
    I'm trying to create a word processor gui and I'm new to Java so I'm very new to working with guis. I'm trying to create a menu bar and use Jtextarea so that the user would be able to type in multiple lines of text. I'm completely confused with how to do bc I've been trying and trying but seem to have a problem with my main class and my default constructor. any tips on how to get started?
    my main class looks like this {
    WordProcessorDemo f = new WordProcessorDemo();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();
    f.setVisible(true);
    f.setSize(800, 600);
    f.setTitle("Word Processor");}
    and it gives me this error msg :
    java.lang.IllegalArgumentException: illegal component position
         at java.awt.Container.addImpl(Container.java:325)
         at java.awt.Container.add(Container.java:252)
         at javax.swing.JMenu.add(JMenu.java:511)
         at wordprocessor.WordProcessorDemo.<init>(WordProcessorDemo.java:62)
         at wordprocessor.WordProcessorDemo.main(WordProcessorDemo.java:18)

    That code is not causing the problem. Look at line 62 in your constructor
    at wordprocessor.WordProcessorDemo.<init>(WordProcessorDemo.java:62)
    You are adding something to a JMenu
    at javax.swing.JMenu.add(JMenu.java:511)
    and it's not liking your parameters or something

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

  • Loading large files in Java Swing GUI

    Hello Everyone!
    I am trying to load large files(more then 70 MB of xml text) in a Java Swing GUI. I tried several approaches,
    1)Byte based loading whith a loop similar to
    pane.setText("");
                 InputStream file_reader = new BufferedInputStream(new FileInputStream
                           (file));
                 int BUFFER_SIZE = 4096;
                 byte[] buffer = new byte[BUFFER_SIZE];
                 int bytesRead;
                 String line;
                 while ((bytesRead = file_reader.read(buffer, 0, BUFFER_SIZE)) != -1)
                      line = new String(buffer, 0, bytesRead);
                      pane.append(line);
                 }But this is gives me unacceptable response times for large files and runs out of Java Heap memory.
    2) I read in several places that I could load only small chunks of the file at a time and when the user scrolls upwards or downwards the next/previous chunk is loaded , to achieve this I am guessing extensive manipulation for the ScrollBar in the JScrollPane will be needed or adding an external JScrollBar perhaps? Can anyone provide sample code for that approach? (Putting in mind that I am writting code for an editor so I will be needing to interact via clicks and mouse wheel roatation and keyboard buttons and so on...)
    If anyone can help me, post sample code or point me to useful links that deal with this issue or with writting code for editors in general I would be very grateful.
    Thank you in advance.

    Hi,
    I'm replying to your question from another thread.
    To handle large files I used the new IO libary. I'm trying to remember off the top of my head but the classes involved were the RandomAccessFile, FileChannel and MappedByteBuffer. The MappedByteBuffer was the best way for me to read and write to the file.
    When opening the file I had to scan through the contents of the file using a swing worker thread and progress monitor. Whilst doing this I indexed the file into managable chunks. I also created a cache to further optimise file access.
    In all it worked really well and I was suprised by the performance of the new IO libraries. I remember loading 1GB files and whilst having to wait a few seconds to perform the indexing you wouldn't know that the data for the JList was being retrieved from a file whilst the application was running.
    Good Luck,
    Martin.

  • 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

  • Problem in Opening of Calendar in portal 3.0.9.8.4 ? -URGENT

    Dear All, I have recently applied the above patch(3.0.9.8.4). I have my Calendar and its Parameter Page(page based on Procedure) in two Tabs of a page. After selecting the Parameters when I press the button to submit to the Calendar Tab IT DOES NOT G

  • How to Design Attractive Logo In Adobe Photoshop?

    Hi          I am working on adobe Photoshop to design a Logo for a Recruitment Job Portal E-Recruitment Hub - Govt Jobs Notification 2014 Online Application Form and  i am trying to making an attractive logo for this jobs site. Dear all please sugges

  • Where do i add a new email alias?

    I can no longer find where i set up a new alias email address for my iCloud account. I have found "alternate" email addresses but this doesn't accept anything i try to add as an alias so I'm guessing its not that.. This USED to be easy.. Any ideas? T

  • XML Data Conversion Problem

    Hi, Am facing problem in flex that using web services am getting the data in xml format (below provided) am not able to provide the data from xml to datagrid. Am getting the data in datagridcolumn with the tag also. I need only data to be displayed w

  • Implementing an ESR Enterprise Service in Ecc 6.0

    Hi experts, I've finish to model my Enterprise Service in the ES Builder. So, now i want to implement that service in the ECC 6.0. How can i do that o what do i need ? I think that i have to configure an Abap proxy is that ok? I need information plea