JPanel as a PropertyChangeListener

Is it acceptable design to have a JPanel implement PropertyChangeListener? The reason I ask is that I want this JPanel to be able to be notifed from many sources if a specific property changes. More details follow:
- user clicks button
- AbstractAction is called
- sets property on a MasterPanel via setter
- change event gets fired sending a JPanelListener.CONTSTANT_VALUE.
- JPanelListeners are registered with teh MasterPanel PropertyChangeSupport
- the JPanelListeners recieve the JPanelListener.CONTSTANT_VALUE and act accordingly
Is this design acceptable?
Thanks
NG

I like this design. I have used it successfully on several occasions.
DB

Similar Messages

  • Trouble when embedding a Bean in an Office Document

    Hello all,
    I have to embed a Java Bean into an ActiveX Container like a MS Office document via the axbridge.
    Let me mention, what I have (successfully) done so far:
    - Create a Java Bean
    - Create a Jar file (incl. the manifest file)
    - Run the packager and register the Object
    - Test the control in the MS ActiveX Control Test Container
    System: Win2k, JSDK 1.4.2, JRE 1.4.2_03, Office 2000, Visual C++ 6.0 SP 3
    The ActiveX control works fine in the MS test container. When I try to embed it in another Container like a MS Office document or Macromedia Authoware, the Container Program hangs up without an error message. Also the Java Console contains no message.
    On the other side, the Control can successfully be created and used within VBA:
    Sub myTestApplet()
        Set myTest = CreateObject("TestApplet.Bean.1")
        �
        Set myTest = Nothing
    End Sub Doing so, the control works correctly, but isn�t displayed in the document.
    I tried to use different Superclasses for the Bean like Component, JComponent, Panel etc. and at last I used an empty Bean inherited from JComponent. Every try works well in the MS test container, but as soon as I try to embed it into an Office-Document the Application hangs up.
    The ActiveX Bridge from the 1.4.2 SDK/JRE Bundle doesn�t work at all, even not in the MS test container. Thus I installed the 1.4.2_03 JRE, which makes the controls work in the MS test container (but still not in other Containers).
    Can somebody help me? I have no idea for a workaround and I�m blocked now. Any advice is very welcome!
    Regards,
    Oliver

    Thank you very much for your interest at my problem.
    I try to describe exactly, what I do: I want to integrate a Java3D program into a Macromedia Authorware application. Therefore I want to convert the Java3D program into an ActiveX control (and use the ActiveX Bridge). Authorware must be able to access methods of the J3D program and the J3D program must be able to throw events to Authorware. I think this is nothing special for an ActiveX control.
    In order to avoid additional problems, I use a simple test application without Java3D (source code enclosed).
    I work on:
    WindowsXP,
    JSDK 1.4.2, JRE 1.4.2_3,
    Visual C++ 6.0 SP3 and I also tried Visual Studio .NET.
    Authorware 7
    MS Office 2000
    What have I done so far?
    - compiled the code and created a jar archive (manifest file enclosed)
    - packaged and registered the Bean as described in http://java.sun.com/j2se/1.4.2/docs/guide/beans/axbridge/developerguide/index.html
    - successfully tested the ActiveX control in the ActiveX Control Test Container. The exported methods appear (and work) correctly when I choose "invoke methods".
    Now to the problem(s): If I try to embed the control in Authorware or an office document via the ToolBox, the container program hangs up. But as already mentioned above, Visual Basic .NET embeds the control successfully. Therefore I try to create an ActiveX control in VB .NET, which integrates my Java Bean. Let's say a wrapper control. Here are the steps:
    - I opened Visual Studio .NET and created a new VB project based on template "Windows Application".
    - added the Bean to the ToolBox
    - added the Bean into the VB Form.
    - added a button into the form. The form designer created the Bean and button as:Friend WithEvents AxActiveXTest1 As AxActiveXTest.AxActiveXTest
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Me.AxActiveXTest1 = New AxActiveXTest.AxActiveXTest()
    Me.Button1 = New System.Windows.Forms.Button() - in the form designer double clicked the button and entered the following code: Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Me.AxActiveXTest1.appendText("Hello World")
    End Sub- test the form and click on the VB button.
    Now the error message listed above appears ("cannot invoke method 'appendText' at this time"). I have no idea, why VB crashes when I try to access a method of the Bean. Somewhere I must have made an error. Each assistance is very welcome.
    Thank you in advance and please excuse my less good English.
    Oliver
    Source code:
    1. Class ActiveXTest package de.acns.test;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.beans.*;
    import java.io.*;
    * class ActiveXTest
    public class ActiveXTest extends JPanel implements Serializable,
                                                       PropertyChangeListener
        // member variables
        private PropertyChangeSupport propertySupport;
        /** Creates new form ActiveXTest */
        public ActiveXTest() {
            propertySupport = new PropertyChangeSupport( this );
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            java.awt.GridBagConstraints gridBagConstraints;
            jButton1 = new javax.swing.JButton();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
            setLayout(new java.awt.GridBagLayout());
            jButton1.setText("Click Here!");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 0;
            gridBagConstraints.gridy = 0;
            gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
            add(jButton1, gridBagConstraints);
            jScrollPane1.setMinimumSize(new java.awt.Dimension(160, 100));
            jScrollPane1.setPreferredSize(new java.awt.Dimension(160, 100));
            jTextArea1.setPreferredSize(new java.awt.Dimension(50, 50));
            jScrollPane1.setViewportView(jTextArea1);
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 0;
            gridBagConstraints.gridy = 1;
            gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
            add(jScrollPane1, gridBagConstraints);
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            // Add your handling code here:
            appendText("You clicked the java button.\n");
         * Public methods to export
        public void appendText( String text)
            jTextArea1.append(text);
        public void setText( String text )
            String oldValue = jTextArea1.getText();
            jTextArea1.setText( text );
            propertySupport.firePropertyChange("TEXT", oldValue,
                                               jTextArea1.getText());
        public String getText()
            return jTextArea1.getText();
         * PropertyChangeListener Support
        public void addPropertyChangeListener(PropertyChangeListener listener) {
            propertySupport.addPropertyChangeListener(listener);
        public void removePropertyChangeListener(PropertyChangeListener listener) {
            propertySupport.removePropertyChangeListener(listener);
         * static main method, enables the bean to be testet "standalone"
        public static void main( String[] args)
            // Create a new instance and add it to a JFrame
            ActiveXTest activeXTest = new ActiveXTest();
            JFrame      frame       = new JFrame("Testapplication");
            activeXTest.addPropertyChangeListener(activeXTest);
            frame.setDefaultCloseOperation(frame.HIDE_ON_CLOSE);
            frame.addWindowListener(new WindowAdapter()
                public void windowClosing( WindowEvent e )
                    System.exit(0);
            frame.getContentPane().setLayout( new GridLayout ());
            frame.getContentPane().add( activeXTest );
            frame.validate();
            frame.pack();
            frame.setLocation( (Toolkit.getDefaultToolkit().getScreenSize().width 
                                 - frame.getWidth())  >> 1,
                               (Toolkit.getDefaultToolkit().getScreenSize().height
                                 - frame.getHeight()) >> 1 );
            frame.show();
         * For testing purposes only, when the bean is
         * created by the static main method
        public void propertyChange(PropertyChangeEvent evt)
            System.out.println("Property \"" + evt.getPropertyName()
                                + "\" wurde von \"" + evt.getOldValue()
                                + "\" in \"" + evt.getNewValue()
                                + "\" ge?ndert");
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextArea jTextArea1;
        // End of variables declaration
    } 2. ActiveXTestBeanInfopackage de.acns.test;
    import java.beans.*;
    * class ActiveXTestBeanInfo
    public class ActiveXTestBeanInfo extends SimpleBeanInfo {
        // Bean descriptor information will be obtained from introspection.
        private static BeanDescriptor beanDescriptor = null;
        private static BeanDescriptor getBdescriptor(){
            // Here you can add code for customizing the BeanDescriptor.
            return beanDescriptor;     }
        // Properties information will be obtained from introspection.
        private static PropertyDescriptor[] properties = null;
        private static PropertyDescriptor[] getPdescriptor(){
            // Here you can add code for customizing the properties array.
            System.out.println("ActiveXTestBeanInfo: Properties werden exportiert:");
            try
                // create the property descritpors
                properties = new PropertyDescriptor[]
                    new PropertyDescriptor( "text", de.acns.test.ActiveXTest.class )
                // For debugging purposes only
                for( int i=0; i<properties.length; i++)
                    System.out.println(properties.getShortDescription() );
    System.out.println(" ");
    catch( Exception e )
    e.printStackTrace();
    return properties; }
    // Event set information will be obtained from introspection.
    private static EventSetDescriptor[] eventSets = null;
    private static EventSetDescriptor[] getEdescriptor(){
    // Here you can add code for customizing the event sets array.
    return eventSets; }
    // Method information will be obtained from introspection.
    private static MethodDescriptor[] methods = null;
    private static MethodDescriptor[] getMdescriptor(){
    // Here you can add code for customizing the methods array.
    System.out.println("ActiveXTestBeanInfo: exportiere Methoden:");
    try
    // create the method descriptors
    methods = new MethodDescriptor[]
    new MethodDescriptor( ActiveXTest.class.getMethod("appendText", new Class[]{String.class}))
    // For debugging purposes only
    for( int i=0; i<methods.length; i++)
    System.out.println(methods[i].getName());
    System.out.println(" ");
    catch( Exception e)
    e.printStackTrace();
    return methods; }
    private static int defaultPropertyIndex = -1;
    private static int defaultEventIndex = -1;
    // Here you can add code for customizing the Superclass BeanInfo.
    * Gets the bean's <code>BeanDescriptor</code>s.
    * @return BeanDescriptor describing the editable
    * properties of this bean. May return null if the
    * information should be obtained by automatic analysis.
    public BeanDescriptor getBeanDescriptor() {
    return getBdescriptor();
    * Gets the bean's <code>PropertyDescriptor</code>s.
    * @return An array of PropertyDescriptors describing the editable
    * properties supported by this bean. May return null if the
    * information should be obtained by automatic analysis.
    * <p>
    * If a property is indexed, then its entry in the result array will
    * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor.
    * A client of getPropertyDescriptors can use "instanceof" to check
    * if a given PropertyDescriptor is an IndexedPropertyDescriptor.
    public PropertyDescriptor[] getPropertyDescriptors() {
    return getPdescriptor();
    * Gets the bean's <code>EventSetDescriptor</code>s.
    * @return An array of EventSetDescriptors describing the kinds of
    * events fired by this bean. May return null if the information
    * should be obtained by automatic analysis.
    public EventSetDescriptor[] getEventSetDescriptors() {
    return getEdescriptor();
    * Gets the bean's <code>MethodDescriptor</code>s.
    * @return An array of MethodDescriptors describing the methods
    * implemented by this bean. May return null if the information
    * should be obtained by automatic analysis.
    public MethodDescriptor[] getMethodDescriptors() {
    return getMdescriptor();
    * A bean may have a "default" property that is the property that will
    * mostly commonly be initially chosen for update by human's who are
    * customizing the bean.
    * @return Index of default property in the PropertyDescriptor array
    *           returned by getPropertyDescriptors.
    * <P>     Returns -1 if there is no default property.
    public int getDefaultPropertyIndex() {
    return defaultPropertyIndex;
    * A bean may have a "default" event that is the event that will
    * mostly commonly be used by human's when using the bean.
    * @return Index of default event in the EventSetDescriptor array
    *          returned by getEventSetDescriptors.
    * <P>     Returns -1 if there is no default event.
    public int getDefaultEventIndex() {
    return defaultEventIndex;
    3. manifest file manifest.mf
    Manifest-Version: 1.0
    Name: de/acns/test/ActiveXTest.class
    Java-Bean: True

  • How to prevent JFileChooser automatically changing to parent directory?

    When you show only directories, and click on the dir icons to navigate, and then dont select anything and click OK, it automatically 'cd's to the parent folder.
    My application is using the JFileChooser to let the user navigate through folders and certain details of 'foo' files in that folder are displayed in another panel.
    So we dont want the chooser automatically changing dir to parent when OK is clicked. How to prevent this behavior?
    I considered extending the chooser and looked at the Swing source code but it is hard to tell where the change dir is happening.
    thanks,
    Anil
    To demonstrate this, I took the standard JFileChooserDemo from the Sun tutorial and modified it adding these lines
              // NEW line 45 in constructor
              fc.addPropertyChangeListener((PropertyChangeListener) this);
              fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
          * NEW -
          * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
         public void propertyChange(PropertyChangeEvent e) {
              String prop = e.getPropertyName();
              if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) {
                   System.out.println("DIRECTORY_CHANGED_PROPERTY");
                   File file = (File) e.getNewValue();
                   System.out.println("DIRECTORY:" + file.getPath());
         }

    Here is the demo:
    package filechooser;
    import java.awt.BorderLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.io.File;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    * FileChooserDemo.java uses these files:
    *   images/Open16.gif
    *   images/Save16.gif
    public class FileChooserDemo extends JPanel implements ActionListener,
              PropertyChangeListener {
         static private final String newline = "\n";
         JButton openButton, saveButton;
         JTextArea log;
         JFileChooser fc;
         public FileChooserDemo() {
              super(new BorderLayout());
              // Create the log first, because the action listeners
              // need to refer to it.
              log = new JTextArea(5, 20);
              log.setMargin(new Insets(5, 5, 5, 5));
              log.setEditable(false);
              JScrollPane logScrollPane = new JScrollPane(log);
              // Create a file chooser
              fc = new JFileChooser();
              // NEW
              fc.addPropertyChangeListener((PropertyChangeListener) this);
              fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
              // Create the open button. We use the image from the JLF
              // Graphics Repository (but we extracted it from the jar).
              openButton = new JButton("Open a File...",
                        createImageIcon("images/Open16.gif"));
              openButton.addActionListener(this);
              // Create the save button. We use the image from the JLF
              // Graphics Repository (but we extracted it from the jar).
              saveButton = new JButton("Save a File...",
                        createImageIcon("images/Save16.gif"));
              saveButton.addActionListener(this);
              // For layout purposes, put the buttons in a separate panel
              JPanel buttonPanel = new JPanel(); // use FlowLayout
              buttonPanel.add(openButton);
              buttonPanel.add(saveButton);
              // Add the buttons and the log to this panel.
              add(buttonPanel, BorderLayout.PAGE_START);
              add(logScrollPane, BorderLayout.CENTER);
          * NEW -
          * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
         public void propertyChange(PropertyChangeEvent e) {
              String prop = e.getPropertyName();
              // If the directory changed, don't show an image.
              if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) {
                   System.out.println("DIRECTORY_CHANGED_PROPERTY");
                   File file = (File) e.getNewValue();
                   System.out.println("DIRECTORY:" + file.getPath());
         public void actionPerformed(ActionEvent e) {
              // Handle open button action.
              if (e.getSource() == openButton) {
                   int returnVal = fc.showOpenDialog(FileChooserDemo.this);
                   if (returnVal == JFileChooser.APPROVE_OPTION) {
                        File file = fc.getSelectedFile();
                        // This is where a real application would open the file.
                        log.append("Opening: " + file.getName() + "." + newline);
                   } else {
                        log.append("Open command cancelled by user." + newline);
                   log.setCaretPosition(log.getDocument().getLength());
                   // Handle save button action.
              } else if (e.getSource() == saveButton) {
                   int returnVal = fc.showSaveDialog(FileChooserDemo.this);
                   if (returnVal == JFileChooser.APPROVE_OPTION) {
                        File file = fc.getSelectedFile();
                        // This is where a real application would save the file.
                        log.append("Saving: " + file.getName() + "." + newline);
                   } else {
                        log.append("Save command cancelled by user." + newline);
                   log.setCaretPosition(log.getDocument().getLength());
         /** Returns an ImageIcon, or null if the path was invalid. */
         protected static ImageIcon createImageIcon(String path) {
              java.net.URL imgURL = FileChooserDemo.class.getResource(path);
              if (imgURL != null) {
                   return new ImageIcon(imgURL);
              } else {
                   System.err.println("Couldn't find file: " + path);
                   return null;
          * Create the GUI and show it. For thread safety, this method should be
          * invoked from the event dispatch thread.
         private static void createAndShowGUI() {
              // Create and set up the window.
              JFrame frame = new JFrame("FileChooserDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Add content to the window.
              frame.add(new FileChooserDemo());
              // Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args) {
              // Schedule a job for the event dispatch thread:
              // creating and showing this application's GUI.
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        // Turn off metal's use of bold fonts
                        UIManager.put("swing.boldMetal", Boolean.FALSE);
                        createAndShowGUI();
    }

  • How to get multiline text on progress bar

    Hi there,
    I have to use Progress Bar and need to show text in multiline.
    can anyone please suggest me how to achieve that.
    Thanks,
    Prashant

    can u guys figure out what really i am missing here?A spoon-fed solution, I suppose. So enjoy:
    // A JProgressBar with two lines of text.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.beans.*;
    public class PB2Lines extends JPanel implements
                             ActionListener, PropertyChangeListener {
        private TwoLinesProgressBar progressBar;
        private JButton startButton;
        private Task task;
        class Task extends SwingWorker<Void, Void> {
            public Void doInBackground() {
                int progress = 0;
                //Initialize progress property.
                setProgress(0);
                while (progress < 100) {
                    progress += 25;
                    setProgress(progress);
              if (progress==25)
                progressBar.setString("Eggs|added");
              else if (progress==50)
                progressBar.setString("Sugar|added");
              else if (progress==75)
                progressBar.setString("Milk|added");
              else
                progressBar.setString("Everything|done");
                    try {
                      Thread.sleep(500);
                    } catch (InterruptedException ignore) {}
                return null;
            public void done() {
                Toolkit.getDefaultToolkit().beep();
                startButton.setEnabled(true);
                setCursor(null); //turn off the wait cursor
        public PB2Lines() {
            super(new BorderLayout());
            //Create the demo's UI.
            startButton = new JButton("Start");
    //        startButton.setActionCommand("start");
            startButton.addActionListener(this);
            progressBar = new TwoLinesProgressBar(0, 100);
            progressBar.setPreferredSize(new Dimension(200,40));
            progressBar.setValue(0);
    //        progressBar.setStringPainted(true);
            progressBar.setString("Progress|Bar");
            JPanel panel = new JPanel();
            panel.add(startButton);
            panel.add(progressBar);
            add(panel, BorderLayout.PAGE_START);
            setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
         * Invoked when the user presses the start button.
        public void actionPerformed(ActionEvent evt) {
            startButton.setEnabled(false);
            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            task = new Task();
            task.addPropertyChangeListener(this);
            task.execute();
         * Invoked when task's progress property changes.
        public void propertyChange(PropertyChangeEvent evt) {
            if ("progress" == evt.getPropertyName()) {
                int progress = (Integer) evt.getNewValue();
                progressBar.setValue(progress);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                   JFrame frame = new JFrame("ProgressBar with 2 lines");
                   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   JComponent newContentPane = new PB2Lines();
                   newContentPane.setOpaque(true); //content panes must be opaque
                   frame.setContentPane(newContentPane);
                   frame.pack();
                   frame.setVisible(true);
      class TwoLinesProgressBar extends JProgressBar {
        public TwoLinesProgressBar(int min, int max) {
          super(min, max);
        private int getXofCenteredString(String s) {
          int ix= getFontMetrics(getFont()).stringWidth(s);
          return (getWidth()-ix)/2;
        protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          int i= getString().indexOf('|');
          String s= getString().substring(0,i);
          int ix= getXofCenteredString(s);
          g.setColor(Color.BLACK);
          g.drawString(s, ix,15);
          s= getString().substring(i+1);
          ix= getXofCenteredString(s);
          g.drawString(s, ix,35);
    }

  • Set TimeOut for SwingWorker

    nice day,
    1/ how can I get real Html size in kB with intention to set as maxValue to ProgressMonitor
    2/ how can I set/synchronize current valueOfDownLoadedHtml in kB to ProgressMonitor throught downloading Html content
    3/ how can I set TimeOut for this Tast, (maybe ... could I use Timer)
    import java.awt.BorderLayout;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import java.net.URLConnection;
    import java.nio.charset.Charset;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.ProgressMonitor;
    import javax.swing.SwingWorker;
    public class ProgressMonitorDemo extends JPanel implements ActionListener, PropertyChangeListener {
        private static final long serialVersionUID = 1L;
        private ProgressMonitor progressMonitor;
        private JButton startButton;
        private JTextArea taskOutput;
        private Task task;
        private int sizeIn_kB = 0;
        class Task extends SwingWorker<Void, Void> {
            private String str;
            int progress = 0;
            public Task(String str) {
                this.str = str;
            @Override
            public Void doInBackground() {
                if (str.equals("Loads")) {
                    addBackgroundLoadsData();
                    setProgress(0);
                    while (progress < sizeIn_kB && !isCancelled()) {
                        progress += sizeIn_kB;
                        setProgress(Math.min(progress, sizeIn_kB));
                return null;
            @Override
            public void done() {
                if (str.equals("Loads")) {
                    Toolkit.getDefaultToolkit().beep();
                    startButton.setEnabled(true);
                    progressMonitor.setProgress(0);
        public void addBackgroundLoadsData() {
            InputStream in = null;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            String charset ="";
            try {
                String UrlString = "http://java.sun.com/";
                URL url = new URL(UrlString);
                URLConnection conn = url.openConnection();
                sizeIn_kB = conn.getContentLength();
                charset = conn.getContentEncoding();
                conn.setRequestProperty("Accept-Charset", charset);
                in = conn.getInputStream();
                int len;
                byte[] buf = new byte[1024];
                while ((len = in.read(buf)) > 0) {
                    bos.write(buf, 0, len);
                in.close();
                String charEncoding = Charset.defaultCharset().name();
                //String fileEncoding = System.getProperty("file.encoding");
                //System.out.println("File Encoding: " + fileEncoding);
                //System.out.println("Char Encoding: " + charEncoding);
                //System.out.println("Char Encoding: " + Charset.availableCharsets());
                charEncoding = "cp1250";
                String groupImport = new String(bos.toByteArray(), charEncoding);
                conn = null;
            } catch (IOException ioException) {
                ioException.printStackTrace();
                JOptionPane.showMessageDialog(null, ioException.getMessage(), "Htlm error", JOptionPane.ERROR_MESSAGE);
            } catch (StringIndexOutOfBoundsException ioException) {
                ioException.printStackTrace();
                JOptionPane.showMessageDialog(null, ioException.getMessage(), "InputStream error", JOptionPane.ERROR_MESSAGE);
        public ProgressMonitorDemo() {
            super(new BorderLayout());
            startButton = new JButton("Start");
            startButton.setActionCommand("start");
            startButton.addActionListener(this);
            taskOutput = new JTextArea(5, 20);
            taskOutput.setMargin(new Insets(5, 5, 5, 5));
            taskOutput.setEditable(false);
            add(startButton, BorderLayout.PAGE_START);
            add(new JScrollPane(taskOutput), BorderLayout.CENTER);
            setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        @Override
        public void actionPerformed(ActionEvent evt) {
            progressMonitor = new ProgressMonitor(ProgressMonitorDemo.this, "Running a Long Task", "", 0, 100);
            progressMonitor.setProgress(0);
            task = new Task("Loads");
            task.addPropertyChangeListener(this);
            task.execute();
            startButton.setEnabled(false);
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if ("progress" == null ? evt.getPropertyName() == null : "progress".equals(evt.getPropertyName())) {
                int progress = (Integer) evt.getNewValue();
                progressMonitor.setProgress(progress);
                String message = String.format("Completed %d%%.\n", progress);
                progressMonitor.setNote(message);
                taskOutput.append(message);
                if (progressMonitor.isCanceled() || task.isDone()) {
                    Toolkit.getDefaultToolkit().beep();
                    if (progressMonitor.isCanceled()) {
                        task.cancel(true);
                        taskOutput.append("Task canceled.\n");
                    } else {
                        taskOutput.append("Task completed.\n");
                    startButton.setEnabled(true);
        private static void createAndShowGUI() {
            JFrame frame = new JFrame("ProgressMonitorDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JComponent newContentPane = new ProgressMonitorDemo();
            newContentPane.setOpaque(true);
            frame.setContentPane(newContentPane);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    See the session-descriptor element of weblogic.xml deployment descriptor:
    http://download.oracle.com/docs/cd/E21764_01/web.1111/e13712/weblogic_xml.htm#i1071981

  • Cannot find symbol error when compiling from cmd

    When compile and running program from Eclipse 3.3 everything works fine, but when trying to compile from cmd I get this error:
    C:\TEMP\1>javac A.java
    A.java:38: cannot find symbol
    symbol : class SwingWorker
    location: package javax.swing
    import javax.swing.SwingWorker;
    ^
    A.java:48: cannot find symbol
    symbol : class SwingWorker
    location: class A
    class Task extends SwingWorker {
    ^
    A.java:109: cannot find symbol
    symbol : method addPropertyChangeListener(A)
    location: class A.Task
    task.addPropertyChangeListener(this);
    ^
    A.java:110: cannot find symbol
    symbol : method execute()
    location: class A.Task
    task.execute();
    ^
    java -version get back: java version "1.6.0_14"....
    now, if i copy .class file that Eclipse made and just execute thet .class file from cmd everything works fine.
    here is the code, but i think that problems is somwhere else. i tried to serach on google, but... :(
    import java.awt.BorderLayout;
    import java.awt.Cursor;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.SwingWorker;
    public class A extends JPanel implements ActionListener, PropertyChangeListener {
        private JProgressBar progressBar;
        private JButton startButton;
        private JTextArea taskOutput;
        private Task task;
        class Task extends SwingWorker {
             * Main task. Executed in background thread.
    //        @Override
            public Void doInBackground() {
                 System.out.println("test");
                return null;
             * Executed in event dispatching thread
    //        @Override
            public void done() {
                Toolkit.getDefaultToolkit().beep();
                startButton.setEnabled(true);
                setCursor(null); //turn off the wait cursor
                taskOutput.append("Done!\n");
        public A() {
            super(new BorderLayout());
            //Create the demo's UI.
            startButton = new JButton("Start");
            startButton.setActionCommand("start");
            startButton.addActionListener(this);
            progressBar = new JProgressBar(0, 100);
            progressBar.setValue(0);
            progressBar.setStringPainted(true);
            taskOutput = new JTextArea(25, 50);
            taskOutput.setMargin(new Insets(5,5,5,5));
            taskOutput.setEditable(false);
            JPanel panel = new JPanel();
            panel.add(startButton);
            panel.add(progressBar);
            add(panel, BorderLayout.PAGE_START);
            add(new JScrollPane(taskOutput), BorderLayout.CENTER);
            setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
         * Invoked when the user presses the start button.
        public void actionPerformed(ActionEvent evt) {
            startButton.setEnabled(false);
            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            //Instances of javax.swing.SwingWorker are not reusuable, so
            //we create new instances as needed.
            task = new Task();
            task.addPropertyChangeListener(this);
            task.execute();
         * Invoked when task's progress property changes.
        public void propertyChange(PropertyChangeEvent evt) {
            if ("progress" == evt.getPropertyName()) {
                int progress = (Integer) evt.getNewValue();
                progressBar.setValue(progress);
    //            taskOutput.append(String.format("Completed %d%% of task.\n", task.getProgress()));
         * Create the GUI and show it. As with all GUI code, this must run
         * on the event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("Veritas Backup");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new A();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
             javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }thank you very much!!!!

    Perhaps you are running an older version of javac. What do you get with "javac -version" or try compiling with the full path to jdk 1.6.0_14/bin/javac.

  • ProgressMonitor dialog doesn't go away

    When I run the ProgressMonitor demo found in the tutorial (on [http://java.sun.com/docs/books/tutorial/uiswing/components/progress.html#monitors|http://java.sun.com/docs/books/tutorial/uiswing/components/progress.html#monitors] ), the ProgressMonitor doesn't go away when the task is complete.
    If I press the "Start" button again, I get two ProgressMonitors, one showing the old status of 100%, and another one showing the current progress. (You have to move the dialog windows around to see both of them.)
    How do I make the ProgressMonitor dialog disappear? Calling the close() method doesn't do it.
    Claus

    I don't understand this. I have a problem with a demonstration program that is available on Sun's own web site. The program is already extremely short and concise. Do you want me to download it and upload it again?
    Anyway, here it is:
    * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
    * [rest of copyright comment removed. Please forgive me, Sun.]
    package components;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.beans.*;
    import java.util.Random;
    public class ProgressMonitorDemo extends JPanel
                                     implements ActionListener,
                                                PropertyChangeListener {
        private ProgressMonitor progressMonitor;
        private JButton startButton;
        private JTextArea taskOutput;
        private Task task;
        class Task extends SwingWorker<Void, Void> {
            @Override
            public Void doInBackground() {
                Random random = new Random();
                int progress = 0;
                setProgress(0);
                try {
                    Thread.sleep(1000);
                    while (progress < 100 && !isCancelled()) {
                        //Sleep for up to one second.
                        Thread.sleep(random.nextInt(1000));
                        //Make random progress.
                        progress += random.nextInt(10);
                        setProgress(Math.min(progress, 100));
                } catch (InterruptedException ignore) {}
                return null;
            @Override
            public void done() {
                Toolkit.getDefaultToolkit().beep();
                startButton.setEnabled(true);
                progressMonitor.setProgress(0);
        public ProgressMonitorDemo() {
            super(new BorderLayout());
            //Create the demo's UI.
            startButton = new JButton("Start");
            startButton.setActionCommand("start");
            startButton.addActionListener(this);
            taskOutput = new JTextArea(5, 20);
            taskOutput.setMargin(new Insets(5,5,5,5));
            taskOutput.setEditable(false);
            add(startButton, BorderLayout.PAGE_START);
            add(new JScrollPane(taskOutput), BorderLayout.CENTER);
            setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
         * Invoked when the user presses the start button.
        public void actionPerformed(ActionEvent evt) {
            progressMonitor = new ProgressMonitor(ProgressMonitorDemo.this,
                                      "Running a Long Task",
                                      "", 0, 100);
            progressMonitor.setProgress(0);
            task = new Task();
            task.addPropertyChangeListener(this);
            task.execute();
            startButton.setEnabled(false);
         * Invoked when task's progress property changes.
        public void propertyChange(PropertyChangeEvent evt) {
            if ("progress" == evt.getPropertyName() ) {
                int progress = (Integer) evt.getNewValue();
                progressMonitor.setProgress(progress);
                String message =
                    String.format("Completed %d%%.\n", progress);
                progressMonitor.setNote(message);
                taskOutput.append(message);
                if (progressMonitor.isCanceled() || task.isDone()) {
                    Toolkit.getDefaultToolkit().beep();
                    if (progressMonitor.isCanceled()) {
                        task.cancel(true);
                        taskOutput.append("Task canceled.\n");
                    } else {
                        taskOutput.append("Task completed.\n");
                    startButton.setEnabled(true);
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("ProgressMonitorDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new ProgressMonitorDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    Claus

  • PropertyChangeListener for a JButton that contains a JPanel?

    I created a class that extends from the JButton class. The class contains a JPanel that adds two components to the panel, A JLabel that contains text and a JLabel that contains an icon. Therefore this class is really just a button that contains a JPanel with 2 JLabels added to the panel. (Reason for doing this is it adds layout control to add the 2 components to a panel instead of directly to the JButton) Normally you would do a changepropertylistener to the JButton but because I added the 2 components (JLabel) to a panel and then added the JPanel to the button, the button doesn't notice any change events. How would I detect the PropertyChangeEvent for this cenario?
    thanks,
    Peter Landis

    The solution to the problem is when the instance of the class is created, do a getComponent(0) to get the JPanel component and the do a getComponent(0) to get the JLabel component. Now from here you can add a PropertyChangeListener to the JLabel that you just obtained. The PropertyChangeListener class will look like:
    class RotorItemListener implements PropertyChangeListener
         public void propertyChange(PropertyChangeEvent e)
    System.out.println("CHANGE");
    String name = e.getPropertyName();
    if(name == "text")
    System.out.println("Label changed");
    This will only trap a change that occurs when the label has changed. If you omit the if(name == "text") then when the component is created, a property change event will be triggered which is not what you want. This only traps event that occur only when a change has occurred on the JLabel. Notice that during the instantiation of the component you'll see the text displayed "CHANGE" and not the "Label changed" until the label text has changed.
    Pretty cool huh!

  • Resizing a JPanel

    Heres the problem i'm having:
    I'm trying to implement my own tooltips for a bar graph class that i have created. I need tooltips to appear when i move the mouse over the top of each of the bars.
    The graph is built from an array of data which is an instance variable of the class. The data in this array is updated periodically (say every 10 secs). The heights of the bars in the graph depend on the height of the panel so are set in the paintComponent method.
    Currently in the paintComponent method i also update the instance variable array with the rectangle created for each bar in the graph so that the mouseMotionListener (a subclass of this class) can check if the mouse is within the rectangle.
    This works fine until the data in the instance varible array is updated. Here null pointers are set for each of the rectangles until a repaint is called and the rectangles are updated. This means that before a repaint takes place, the mouseListener can try and access the rectangles in the array and get a nullPointerException
    Is there a better way of doing this? I dont think that i should be updating the data array from the paintComponent method but cant think of another way to do it as the bars depend on the height...
    Any help is greatly appreciated.

    Why not make the bars jcomponents and use the native tool tip?
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.util.*;
    import java.beans.PropertyChangeListener;
    import java.beans.PropertyChangeEvent;
    import java.awt.*;
    import java.awt.event.*;
    public class Demo extends JFrame
        public Demo()
            super( "Demo");
            setDefaultCloseOperation( EXIT_ON_CLOSE );
            setContentPane( new GraphPanel() );
            setSize( 500 , 500 );
            show();
        public static void main(String[] args)
            try
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch( Exception e )
            new Demo();
        public class GraphPanel extends JPanel implements ComponentListener
            ArrayList bars = new ArrayList();
            Random rand = new Random();
            public GraphPanel()
                setLayout( null );
                addBar( Color.blue, 50 );
                addBar( Color.red,  50 );
                addBar( Color.yellow, 50 );
                addBar( Color.green,  50 );
                addComponentListener( this );
                javax.swing.Timer timer = new javax.swing.Timer( 2000, new ActionListener(){
                         * Invoked when an action occurs.
                        public void actionPerformed(ActionEvent e)
                            randomAdjust();
                timer.start();
            private void addBar( Color color, int value )
                bars.add( new BarPanel( color, value ) );
                layoutBars();
            private void layoutBars()
                removeAll();
                int max = 0;
                for( int i = 0; i < bars.size(); i ++ )
                    int value = ((BarPanel) bars.get( i )).getValue();
                    max = value > max?value:max;
                Dimension d = getSize();
                int spacer = d.width/100 +1;
                int width = (d.width-spacer)/bars.size();
                for( int i = 0; i < bars.size(); i ++ )
                    BarPanel bp =(BarPanel) bars.get( i );
                    double bpWeight =  1 - (max-bp.getValue())/(double)max;
                    int bpHeight =  (int)(bpWeight * d.height);
                    bp.setBounds((i+1)*spacer + i*width,
                                 d.height-bpHeight,
                                 width,
                                 bpHeight);
                    add( bp );
                revalidate();
                repaint();
            private void randomAdjust()
                for( int i = 0; i < bars.size(); i ++ )
                    int adjust = rand.nextInt( 100 )-50;
                    BarPanel bp = (BarPanel) bars.get( i );
                    bp.setValue( bp.getValue()+adjust );
                    if( bp.getValue() < 0 )
                             bp.setValue( 0 );
                layoutBars();
             * Invoked when the component's size changes.
            public void componentResized(ComponentEvent e)
                layoutBars();
             * Invoked when the component's position changes.
            public void componentMoved(ComponentEvent e)
             * Invoked when the component has been made visible.
            public void componentShown(ComponentEvent e)
                layoutBars();
             * Invoked when the component has been made invisible.
            public void componentHidden(ComponentEvent e)
        public class BarPanel extends JPanel
            private Color color;
            private int value;
            public BarPanel( Color color, int value )
                this.color = color;
                setValue( value );
                setBackground( color );
            public int getValue()
                return( value );
            public void setValue( int value )
                 setToolTipText( "Value = "+value );
                 this.value = value;
    }By the way... That was fun to write and is the fist time I have ever found a use for a null layout.
    Hope this helps,
    Todd

  • How do I detect when a JPanel's children have focus?

    I need to paint a "focus border" around a JPanel when one of it's child JComponents gets focus. The border is now problem; it's the getting notified when a child receives focus part. There are several components and I'd prefer not to add code to each of them, I was hoping for a central piece of code to handle all cases.
    I'm sure this is very simple, but my brain doesn't seem to be working well today.
    Thanks,
    Jamie

    since 1.4 you can add a PropertyChangeListener with the keyboardFocusManager, listening for a "focusOwner" or "permanentFocusOwner" and check it the new one is a child of the panel or not. In earlier versions you have to add a focusListener to any of the panel's children - as was already mentioned in this thread.
    Greetings
    Jeanette

  • A list of property names for PropertyChangeListener

    Hello all,
    Can anyone post a link to a list of property names? I want to use the addPropertyChangeListener(String, PropertyChangeListener) method, but I can't until I find the name for the property I desire! (The one I'm after is the background colour for a JPanel, on the offchance someone knows it.)
    Thanks,
    Muel.

    I don't know what you're after, maybe if this helps you.
    NOTE: This is not my source! Somebody posted it a while ago.import javax.swing.*;
    import java.util.*;
    public class ShowUIDefaults {
         public static void main(String[] args) {
              javax.swing.UIDefaults defaults = UIManager.getDefaults();
              String[] colName = { "Key", "Value" };
              String[][] rowData = new String[defaults.size()][2];
              int i = 0;
              System.out.println("Count Item = " + defaults.size());
              // Constructing a TreeMap directly from defaults (which
              // does supposedly implement Map) was resulting in an empty map.
              java.util.TreeMap map = new TreeMap(defaults);
              for (Enumeration enum = defaults.keys(); enum.hasMoreElements();) {
                   String key = (String) enum.nextElement();
                   map.put(key, defaults.get(key));
              // I use a TreeMap so the keys in the table will be alphabetically sorted.
              for (java.util.Iterator iter = map.keySet().iterator(); iter.hasNext(); i++) {
                   String keyStr = (String) iter.next();
                   rowData[0] = keyStr;
                   rowData[i][1] = "" + map.get(keyStr);
              JFrame f = new JFrame("UIDefaults Key-Value sheet");
              JTable t = new JTable(rowData, colName);
              f.setContentPane(new JScrollPane(t));
              f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              f.pack();
              f.setVisible(true);

  • Jpanel child action events

    I have a JPanel that i created which has an interface for choosing a date. I dropped the jpanel into an appointment book program im creating. It resides in the main frame of the appointment book program. The datechooser panel implements actionlistener, and changes the date member data field every time the user clicks on a different date, changes the month, etc...
    What i can't figure out, is how to tell when an event has taken place inside the datechooser panel from the appointment book frame. I need to update the appointment table in the appointment book frame every time the user changes the date by clicking on a new date insdide of the datechooser panel.

    Look at PropertyChangeListener in java.beans package. All swing components have the ability to fire property change ecents. Have your date chooser fire a property change event with the new date. Your frame can register as a PCL with the panel.
    There is also a java.swing.event.SwingPropertyChangeSupport class you might want to look at.
    Cheers
    DB

  • Detect Focus transfer between JPanels

    I have an app that has a scrollpane containing a JPanel (A), that contains a bunch of JPanels (B) - each of which contains multiple controls, panels, etc....
    I want to make sure that whichever JPanel (B) has the focus in it, and use the viewPort.scrollToVisible() to make sure that panel is fully displayed.
    So far, the only way I've seen to do that is to add a FocusListener to each and every control and check to see which panel it's in.
    BLECH!
    Is there an easier way?
    I'd really like some kind of listener that is just notified whenever focus transfers between the upper level Panels.

    Thanks to all. Re-read those sections, and came up with this little utility class to do what I needed.
    It listens for focus changes between panels, and notifies a listener of these changes.
    import java.awt.Component;
    import java.awt.KeyboardFocusManager;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.util.ArrayList;
    import javax.swing.JPanel;
    * Tracks the focus for Panels.  If the focus enters or leaves the panel (i.e. focus goes
    * to/from any component in the panel, and from/to anything outside the panel)
    * It notifies any listeners of the event.
    * @author jlussmyer
    public class PanelFocusTracker {
        /** Array of panels we are tracking focus changes for. */
        private JPanel[] panels = new JPanel[0];
        /** Which of our tracked panels currently has the focus */
        private JPanel curFocus = null;
         * Constructor.  Ties into focus handling system.
        public PanelFocusTracker() {
            KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
            focusManager.addPropertyChangeListener(
                    new PropertyChangeListener() {
                        @Override
                        public void propertyChange(PropertyChangeEvent e) {
                            String prop = e.getPropertyName();
                            if (("focusOwner".equals(prop)) && ((e.getNewValue()) instanceof Component)) {
                                Component comp = (Component) e.getNewValue();
                                checkForPanelChange(comp);
            return;
         * Check to see if focus going to his component changes which containing
         * panel has the focus.
         * @param comp Component that is gaining focus.
        private void checkForPanelChange(Component comp) {
            JPanel gainPanel = getPanelForComponent(comp);
            if (gainPanel == curFocus) {
                return; // no change, nothing to do.
            if (curFocus != null) {
                notifyListeners(curFocus, false); // This panel lost focus
            if (gainPanel != null) {
                notifyListeners(gainPanel, true); // This panel gained focus
            curFocus = gainPanel;
            return;
         * Finds which of the panels we are tracking contains the given component.
         * @param comp Component to find containing panel for
         * @return Containing Panel, null if it isn't in one of the panels being tracked.
        private JPanel getPanelForComponent(Component comp) {
            JPanel result = null;
            while ((comp != null) && (result == null)) {
                if (isBeingTracked(comp)) {
                    result = (JPanel) comp;
                } else {
                    comp = comp.getParent();
            return result;
         * Checks to see if this is one of the JPanels we are tracking.
         * @param comp Component to check
         * @return true if it's a JPanel that we are tracking.
        private boolean isBeingTracked(Component comp) {
            boolean result = false;
            for (int idx = 0; (idx < panels.length); idx++) {
                if (comp == panels[idx]) {
                    result = true;
                    break;
            return result;
         * Add a panel to the list of panels being tracked for Panel Focus
         * changes.
         * @param panel Panel to track focus for.
        public void addPanel(JPanel panel) {
            // Don't allow the same panel to be added multiple times.
            for (int idx = 0; (idx < panels.length); idx++) {
                if (panel == panels[idx]) {
                    panel = null;
                    break;
            if (panel != null) {
                JPanel[] temp = new JPanel[panels.length + 1];
                System.arraycopy(panels, 0, temp, 0, panels.length);
                temp[panels.length] = panel;
                panels = temp;
            return;
         * Remove a panel from the list of panels being tracked for Panel Focus
         * changes.
         * @param panel Panel to stop tracking focus for.
         * @return true if panel was being tracked, false otherwise.
        public boolean removePanel(JPanel panel) {
            boolean found = false;
            for (int idx = 0; (idx < panels.length); idx++) {
                if (panel == panels[idx]) {
                    found = true;
                    JPanel[] temp = new JPanel[panels.length - 1];
                    if (idx == 0) { // removing first entry
                        if (temp.length > 0) {
                            System.arraycopy(panels, 1, temp, 0, temp.length);
                    } else if (idx == (panels.length - 1)) { // remove last entry
                        System.arraycopy(panels, 0, temp, 0, temp.length);
                    } else { // Remove something in the middle
                        System.arraycopy(panels, 0, temp, 0, idx);
                        System.arraycopy(panels, idx + 1, temp, idx + 1, temp.length - idx);
                    break;
            return found;
         * Remove all JPanels from focus tracking.
        public void removeAllPanels() {
            panels = new JPanel[0];
            curFocus = null;
            return;
         * Interface for listeners to be notified of focus being gained/lost by
         * any of the panels being tracked.
        public interface Listener {
            /** Focus Lost by given panel */
            void panelFocusLost(JPanel panel);
            /** Focus gained by given panel */
            void panelFocusGained(JPanel panel);
        /** Listeners to be notified of Panel Focus changes */
        private ArrayList<Listener> focusListeners = new ArrayList<Listener>();
         * Add a listener to be notified of changes to the Focus for any Panel
         * being tracked.
         * @param listener Listener to be notified for Panel Focus changes.
        public void addListener(Listener listener) {
            focusListeners.add(listener);
            return;
         * Remove a Panel Focus listener.
         * @param listener listener to no longer be notified of Focus changes.
         * @return true if listener found, false otherwise.
        public boolean removeListener(Listener listener) {
            return focusListeners.remove(listener);
         * Notify all registered listeners of a Panel Focus change.
         * @param panel panel that gained/lost focus.
         * @param gained true if focus gained, false if focus lost.
        private void notifyListeners(JPanel panel, boolean gained) {
            Listener[] list = focusListeners.toArray(new Listener[focusListeners.size()]);
            for (int idx = 0; (idx < list.length); idx++) {
                if (gained) {
                    list[idx].panelFocusGained(panel);
                } else {
                    list[idx].panelFocusLost(panel);
            return;
    }

  • JPanels and JButtons

    My main file is ExpenseTracker.java. When u
    compile the ExpenseTracker.java , there is a column of buttons on the left
    and a right box. I would like to make the output of the RecordMenu.java
    appear(not pop out) in the right box of my ExoenseTracker when i click one
    of the button 'Record Expenses'. I wonder you can help me in this? I am
    facing that problem right now.=======================================================================
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    public class ExpenseTracker extends JFrame {
    public ExpenseTracker() {
    super("Expense Tracker");
    // FirstPanel
    JPanel FirstPanel = new JPanel();
    FirstPanel.setLayout(null);
    JLabel labeltracker = new JLabel("Expense Tracker");
    JButton recordExpenses = new JButton("Record Expenses");
    JButton viewExpenses = new JButton("View Expenses");
    JButton calendar = new JButton("Calendar" );
    JButton exit = new JButton("Exit");
    labeltracker.setBounds(40,120,135,30);
    recordExpenses.setBounds(25,160,135,30);
    viewExpenses.setBounds(25,210,135,30);
    calendar.setBounds(25,260,135,30);
    exit.setBounds(25,310,135,30);
    FirstPanel.setBounds(5,5,200,500);
    FirstPanel.add(labeltracker);
    FirstPanel.add(recordExpenses);
    FirstPanel.add(viewExpenses);
    FirstPanel.add(calendar);
    FirstPanel.add(exit);
    //SecondPanel
    JPanel SecondPanel = new JPanel();
    SecondPanel.setLayout(new BorderLayout(1,2));
    // SecondPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
    SecondPanel.setBorder(new LineBorder(Color.black));
    SecondPanel.setBounds(210,120,530,270);
    getContentPane().setLayout(null);
    getContentPane().add(FirstPanel);
    getContentPane().add(SecondPanel);
    setSize(800,500);
    setVisible(true);
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    public static void main(String [] args) {
    new ExpenseTracker();
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    public class RecordMenu extends JFrame implements ItemListener,ActionListener {
    >>
    JCheckBox weekly;
    JCheckBox monthly;
    public RecordMenu() {
    super("Choose");
    Container c = getContentPane();
    JPanel checkPanel = new JPanel();
    checkPanel.setLayout(new GridLayout(4,2));
    checkPanel.setBorder(new TitledBorder("Record Expenses"));
    JLabel label2 = new JLabel("Amount to track:");
    JTextField amtField = new JTextField(5);
    //Create the check boxes.
    weekly = new JCheckBox("Weekly");
    weekly.setSelected(false);
    monthly = new JCheckBox("Monthly");
    monthly.setSelected(false);
    //Register a listener for the check boxes.
    weekly.addItemListener(this);
    monthly.addItemListener(this);
    amtField.addActionListener(this);
    //Put the check boxes in a column in a panel
    checkPanel.add(weekly,BorderLayout.NORTH);
    checkPanel.add(monthly,BorderLayout.SOUTH);
    checkPanel.add(label2);
    checkPanel.add(amtField);
    JPanel buttonPanel = new JPanel();
    JButton buttonOk = new JButton("OK");
    JButton buttonCancel = new JButton("Cancel");
    buttonPanel.add(buttonOk);
    buttonPanel.add(buttonCancel);
    c.add(checkPanel,BorderLayout.NORTH);
    c.add(buttonPanel);
    setSize(370,200);
    setVisible(true);
    /** Listens to the check boxes. */
    public void itemStateChanged(ItemEvent event) {
    public static void main(String[] args) {
    new RecordMenu();

    Hi,
    1. When i clicked e 'record expenses' and click 'ok' after that, there will b a JOptionPane that will pop out, i wonder how to make CheckBox.java appear right after the 'ok' button was clicked?
    2. I had also 3 files about creating a calendar.. can you show me how can i make e calendar appear in the right panel when i clicked the 'calendar' in the ExpenseTracker.java?
    As there are many java files, is it possible to make the program work by not putting all codes in a file but calling e codes from another file?
    ================================================================================
    1.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    public class PuttingItTogether {    
    public static void main(String[] args) {   
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(new ExpenseTracker());
    f.setSize(800,500);
    f.setVisible(true);
    class ExpenseTracker extends JPanel implements ActionListener, ItemListener {
         JCheckBox weekly;
         JCheckBox monthly;
         JTextField amtField;
         JButton buttonOk, buttonCancel;
         public ExpenseTracker() {       
         // FirstPanel
         JPanel FirstPanel = new JPanel();
         FirstPanel.setLayout(null);
         JLabel labeltracker = new JLabel("Expense Tracker");
         JButton recordExpenses = new JButton("Record Expenses");
         JButton viewExpenses = new JButton("View Expenses");
         JButton calendar = new JButton("Calendar" );
         JButton exit = new JButton("Exit");
         labeltracker.setBounds(40,120,135,30);
         recordExpenses.setBounds(25,160,135,30);
         viewExpenses.setBounds(25,210,135,30);
         calendar.setBounds(25,260,135,30);
         exit.setBounds(25,310,135,30);
         recordExpenses.setActionCommand("records");
         viewExpenses.setActionCommand("view");
         calendar.setActionCommand("calendar");
         exit.setActionCommand("exit");
         FirstPanel.setBounds(5,5,200,500);
         FirstPanel.add(labeltracker);
         FirstPanel.add(recordExpenses);
         FirstPanel.add(viewExpenses);
         FirstPanel.add(calendar);
         FirstPanel.add(exit);
         // record panel
         JPanel checkPanel = new JPanel();
         checkPanel.setLayout(new GridLayout(4,2));
         checkPanel.setBorder(new TitledBorder("Record Expenses"));
         JLabel label2 = new JLabel("Amount to track:");
         amtField = new JTextField(5);
         //Create the check boxes.
         weekly = new JCheckBox("Weekly");
         weekly.setSelected(false);
         monthly = new JCheckBox("Monthly");
         monthly.setSelected(false);
         //Register a listener for the check boxes.
         weekly.addItemListener(this);
         monthly.addItemListener(this);
         //Put the check boxes in a column in a panel
         checkPanel.add(weekly,BorderLayout.NORTH);
         checkPanel.add(monthly,BorderLayout.SOUTH);
         checkPanel.add(label2);
         checkPanel.add(amtField);
         JPanel buttonPanel = new JPanel();
         buttonOk = new JButton("OK");
         buttonOk.addActionListener(this);
         buttonCancel = new JButton("Cancel");
         buttonCancel.addActionListener(this);
         buttonPanel.add(buttonOk);
         buttonPanel.add(buttonCancel);
         JPanel recordPanel = new JPanel(new BorderLayout());
         recordPanel.add(checkPanel);
         recordPanel.add(buttonPanel, "South");
         //View Expenses panel
         //SecondPanel
         CardLayout cards = new CardLayout();
         JPanel SecondPanel = new JPanel();
         SecondPanel.setLayout(cards);
         SecondPanel.setBorder(new LineBorder(Color.black));
         SecondPanel.setBounds(210,120,530,270);
         JPanel coverPanel = new JPanel();
         SecondPanel.add(coverPanel, "cover");
         SecondPanel.add(recordPanel, "record");
         ButtonListener buttonListener = new ButtonListener(SecondPanel, cards);
         recordExpenses.addActionListener(buttonListener);
         viewExpenses.addActionListener(buttonListener);
         calendar.addActionListener(buttonListener);
         exit.addActionListener(buttonListener);
         setLayout(null);
         add(FirstPanel);
         add(SecondPanel);
         /** * Registered on JButtons buttonOk and buttonCancel */
         public void actionPerformed(ActionEvent e) { 
         String entry = amtField.getText();
    String term = weekly.isSelected() ? "weekly" : "monthly";      
         JButton button = (JButton)e.getSource();
         if(button == buttonOk)
         JOptionPane.showMessageDialog(null, "Total amount to be tracked on a " + term + " basis is $" + entry);
         /** * Listener for JCheckBoxes weekly and monthly. */
         public void itemStateChanged(ItemEvent e) {       
         JCheckBox checkBox = (JCheckBox)e.getSource();
         String stateChange, caller = "";
         if(e.getStateChange() == ItemEvent.SELECTED)
         stateChange = "SELECTED";
         else
         stateChange = "DESELECTED";
         if(checkBox == weekly)
         caller = "weekly";
         if(checkBox == monthly)
         caller = "monthly";
         System.out.println(caller + " " + stateChange);
         /** * Listener for JButtons in ExpenseTracker. */
         class ButtonListener implements ActionListener {    
         JPanel panel;
         CardLayout cards;
         public ButtonListener(JPanel p, CardLayout cl) {       
         panel = p;
         cards = cl;
         public void actionPerformed(ActionEvent e) {       
         JButton button = (JButton)e.getSource();
         String ac = button.getActionCommand();
         if(ac.equals("records"))
         cards.show(panel, "record");
         System.out.println("ac = " + ac);
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.text.DecimalFormat;
    public class CheckBox extends JFrame implements ItemListener, ActionListener {
         private JPanel checkPanel, buttonPanel;
         private     JCheckBox transport, bills, food, gifts, leisure, others;
    private JTextField transportField, billsField, foodField, giftsField,
    leisureField, othersField, totalField;
    double transportAmt, billsAmt, foodAmt, giftsAmt, leisureAmt, othersAmt, totalAmt;
    private JButton buttonTotal, saveButton, dontSaveButton;
    private JLabel showTotal;
    public CheckBox() {
    Container c = getContentPane();
    //create a panel for diaplaying the checkboxs and buttons
    checkPanel = new JPanel();
    checkPanel.setLayout(null);
    //Create the check boxes.
    transport = new JCheckBox("Transport");
    transport.setSelected(false);
    transport.setBounds(10,30,80,30);
    transportField = new JTextField();
    transportField.setEditable(false);
    transportField.setBounds(100,35,45,20);
    bills = new JCheckBox("Bills");
    bills.setSelected(false);
    bills.setBounds(10,60,80,30);
    billsField = new JTextField(5);
    billsField.setEditable(false);
    billsField.setBounds(100,65,45,20);
    food = new JCheckBox("Food");
    food.setSelected(false);
    food.setBounds(10,90,80,30);
    foodField = new JTextField(5);
    foodField.setEditable(false);
    foodField.setBounds(100,95,45,20);
    gifts = new JCheckBox("Gifts");
    gifts.setSelected(false);
    gifts.setBounds(200,30,80,30);
    giftsField = new JTextField(5);
    giftsField.setEditable(false);
    giftsField.setBounds(300,35,45,20);
    leisure = new JCheckBox("Leisure");
    leisure.setSelected(false);
    leisure.setBounds(200,60,80,30);
    leisureField = new JTextField(5);
    leisureField.setEditable(false);
    leisureField.setBounds(300,65,45,20);
    others = new JCheckBox("Others");
    others.setSelected(false);
    others.setBounds(200,90,80,30);
    othersField = new JTextField(5);
    othersField.setEditable(false);
    othersField.setBounds(300,95,45,20);
    //Register a listener for the check boxes.
    transport.addItemListener(this);
    bills.addItemListener(this);
    food.addItemListener(this);
    gifts.addItemListener(this);
    leisure.addItemListener(this);
    others.addItemListener(this);
    transportField.addActionListener(this);
    billsField.addActionListener(this);
    foodField.addActionListener(this);
    giftsField.addActionListener(this);
    leisureField.addActionListener(this);
    othersField.addActionListener(this);
    checkPanel.add(transport);
    checkPanel.add(transportField);
    checkPanel.add(bills);
    checkPanel.add(billsField);
    checkPanel.add(food);
    checkPanel.add(foodField);
    checkPanel.add(gifts);
    checkPanel.add(giftsField);
    checkPanel.add(leisure);
    checkPanel.add(leisureField);
    checkPanel.add(others);
    checkPanel.add(othersField);
    checkPanel.setBounds(1,1,390,180);
    checkPanel.setBorder(new TitledBorder("Check the amount you want to track"));
    buttonTotal = new JButton("Calculate Total");
    buttonTotal.setBounds(150,140,130,30);
    buttonTotal.addActionListener(this);
    showTotal = new JLabel(" = __");
    showTotal.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    showTotal.setBounds(290,140,100,30);
    checkPanel.add(buttonTotal);
    checkPanel.add(showTotal);
    buttonPanel = new JPanel();
    buttonPanel.setLayout(null);
    buttonPanel.setBounds(5,180,200,40);
    saveButton = new JButton("Save");
    saveButton.setBounds(90,190,100,30);
    saveButton.addActionListener(this);
    dontSaveButton = new JButton("Don't Save");
    dontSaveButton.setBounds(200,190,100,30);
    dontSaveButton.addActionListener(this);
    buttonPanel.add(saveButton);
    buttonPanel.add(dontSaveButton);
    c.add(checkPanel);
    c.add(buttonPanel);
    setSize(400,260);
    setVisible(true);
    /** Listens to the check boxes. */
    public void itemStateChanged(ItemEvent e) {          
    if (e.getSource() == transport)
    if (e.getStateChange() == ItemEvent.SELECTED)
    transportField.setEditable(true);
    else
         transportField.setEditable(false);      
    if (e.getSource() == bills)
    if (e.getStateChange() == ItemEvent.SELECTED)
    billsField.setEditable(true);
    else
    billsField.setEditable(false);
    if (e.getSource() == food)
    if (e.getStateChange() == ItemEvent.SELECTED)
    foodField.setEditable(true);
    else
    foodField.setEditable(false);
    if (e.getSource() == gifts)
    if (e.getStateChange() == ItemEvent.SELECTED)
    giftsField.setEditable(true);
    else
    giftsField.setEditable(false);
    if (e.getSource() == leisure)
    if (e.getStateChange() == ItemEvent.SELECTED)
    leisureField.setEditable(true);
    else
    leisureField.setEditable(false);
    if (e.getSource() == others)
    if (e.getStateChange() == ItemEvent.SELECTED)
    othersField.setEditable(true);
    else
    othersField.setEditable(false);
    public void actionPerformed(ActionEvent event) {
         if (event.getSource() == buttonTotal) {
              double transportAmt=0.0, billsAmt=0.0, foodAmt=0.0, giftsAmt=0.0,
              leisureAmt=0.0, othersAmt=0.0, totalAmt=0.0;
    if (!transportField.getText().equals(""))
    transportAmt = Double.parseDouble(transportField.getText());
    if(!billsField.getText().equals(""))
    billsAmt = Double.parseDouble(billsField.getText());
    if(!foodField.getText().equals(""))
    foodAmt = Double.parseDouble(foodField.getText());
    if(!giftsField.getText().equals(""))
    giftsAmt = Double.parseDouble(giftsField.getText());
    if(!leisureField.getText().equals(""))
    leisureAmt = Double.parseDouble(leisureField.getText());
    if(!othersField.getText().equals(""))
    othersAmt = Double.parseDouble(othersField.getText());
    totalAmt = transportAmt + billsAmt + foodAmt + giftsAmt + leisureAmt + othersAmt;
    showTotal.setText("= $" + totalAmt);
    if (event.getSource() == dontSaveButton) {
         System.exit(0);
    public static void main(String[] args) {
    new CheckBox();
    =========================================================================
    2.
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.*;
    import java.util.*;
    import javax.swing.*;
    public class Demo extends JFrame implements PropertyChangeListener
    private DateButton startDateButton;
    private DateButton endDateButton;
    private Date startDate;
    private Date endDate;
    private Demo() {
         super( "DateChooser demo" );
         addWindowListener
         new WindowAdapter() {
              public void windowClosing( WindowEvent e ) {
                   System.exit( 0 );
         startDate = new Date();
         endDate = new Date();
         startDateButton = new DateButton();
         startDateButton.addPropertyChangeListener( "date", this );
         endDateButton = new DateButton();
         endDateButton.addPropertyChangeListener( "date", this );
         getContentPane().setLayout( new GridLayout(2,2) );
         getContentPane().add( new JLabel("Start date") );
         getContentPane().add( startDateButton );
         getContentPane().add( new JLabel("End date") );
         getContentPane().add( endDateButton );
         pack();
         setResizable( false );
    public void propertyChange( PropertyChangeEvent e ) {
         DateButton db = (DateButton)e.getSource();
         if ( db == startDateButton )
         System.out.print( "Start date changed: " );
         else
         System.out.print( "End date changed: " );
         System.out.println( db.getDate() );
    public static void main( String[] args ) {
         (new Demo()).show();
    import java.awt.event.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    * Custom button for entering dates. The <code>DateButton</code> class
    * is just a standard button that defines an additional bound
    * property: "date". The button displays the date property as its
    * label. When clicked, it does not generate an
    * <code>ActionEvent</code>, but displays a {@link DateChooser} dialog
    * instead, that allows you to change the date. When the date is
    * changed, a <code>PropertyChangeEvent</code> is generated, according
    * the contract for bound properties.
    public class DateButton extends JButton
    /** Format to use to display the date property. */
    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd-yyyy");
    /** DateChooser instance to use to change the date. */
    private static final DateChooser DATE_CHOOSER = new DateChooser((JFrame)null,"Select Date");
    /** Date property. */
    private Date date;
    * Called when the button is clicked, in order to fire an
    * <code>ActionEvent</code>. Displays the dialog to change the
    * date instead of generating the event and updates the date
    * property.
    * @param e <code>ActionEvent</code> to fire
    protected void fireActionPerformed( ActionEvent e ) {
         Date newDate = DATE_CHOOSER.select(date);
         if ( newDate == null )
         return;
         setDate( newDate );
    * Constructs a new <code>DateButton</code> object with a given
    * date.
    * @param date initial date
    public DateButton( Date date ) {
         super( DATE_FORMAT.format(date) );
         this.date = date;
    * Constructs a new <code>DateButton</code> object with the system
    * date as the initial date.
    public DateButton() {
         this( new Date() );
    * Gets the value of the date property.
    * @return the current value of the date property
    public Date getDate() {
         return date;
    * Sets the valus of the date property.
    * @param date new value of the date property
    * @return the old value of the date property
    public void setDate( Date date ) {
         Date old = this.date;
         this.date = date;
         setText( DATE_FORMAT.format(date) );
         firePropertyChange( "date", old, date );
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    * Custom dialog box to enter dates. The <code>DateChooser</code>
    * class presents a calendar and allows the user to visually select a
    * day, month and year so that it is impossible to enter an invalid
    * date.
    public class DateChooser extends JDialog
    implements ItemListener, MouseListener, FocusListener, KeyListener, ActionListener
    /** Names of the months. */
    private static final String[] MONTHS =
         new String[] {
         "January",
         "February",
         "March",
         "April",
         "May",
         "June",
         "July",
         "August",
         "September",
         "October",
         "November",
         "December"
    /** Names of the days of the week. */
    private static final String[] DAYS =
         new String[] {
         "Sun",
         "Mon",
         "Tue",
         "Wed",
         "Thu",
         "Fri",
         "Sat"
    /** Text color of the days of the weeks, used as column headers in
    the calendar. */
    private static final Color WEEK_DAYS_FOREGROUND = Color.black;
    /** Text color of the days' numbers in the calendar. */
    private static final Color DAYS_FOREGROUND = Color.blue;
    /** Background color of the selected day in the calendar. */
    private static final Color SELECTED_DAY_FOREGROUND = Color.white;
    /** Text color of the selected day in the calendar. */
    private static final Color SELECTED_DAY_BACKGROUND = Color.blue;
    /** Empty border, used when the calendar does not have the focus. */
    private static final Border EMPTY_BORDER = BorderFactory.createEmptyBorder(1,1,1,1);
    /** Border used to highlight the selected day when the calendar
    has the focus. */
    private static final Border FOCUSED_BORDER = BorderFactory.createLineBorder(Color.yellow,1);
    /** First year that can be selected. */
    private static final int FIRST_YEAR = 1900;
    /** Last year that can be selected. */
    private static final int LAST_YEAR = 2100;
    /** Auxiliary variable to compute dates. */
    private GregorianCalendar calendar;
    /** Calendar, as a matrix of labels. The first row represents the
    first week of the month, the second row, the second week, and
    so on. Each column represents a day of the week, the first is
    Sunday, and the last is Saturday. The label's text is the
    number of the corresponding day. */
    private JLabel[][] days;
    /** Day selection control. It is just a panel that can receive the
    focus. The actual user interaction is driven by the
    <code>DateChooser</code> class. */
    private FocusablePanel daysGrid;
    /** Month selection control. */
    private JComboBox month;
    /** Year selection control. */
    private JComboBox year;
    /** "Ok" button. */
    private JButton ok;
    /** "Cancel" button. */
    private JButton cancel;
    /** Day of the week (0=Sunday) corresponding to the first day of
    the selected month. Used to calculate the position, in the
    calendar ({@link #days}), corresponding to a given day. */
    private int offset;
    /** Last day of the selected month. */
    private int lastDay;
    /** Selected day. */
    private JLabel day;
    /** <code>true</code> if the "Ok" button was clicked to close the
    dialog box, <code>false</code> otherwise. */
    private boolean okClicked;
    * Custom panel that can receive the focus. Used to implement the
    * calendar control.
    private static class FocusablePanel extends JPanel
         * Constructs a new <code>FocusablePanel</code> with the given
         * layout manager.
         * @param layout layout manager
         public FocusablePanel( LayoutManager layout ) {
         super( layout );
         * Always returns <code>true</code>, since
         * <code>FocusablePanel</code> can receive the focus.
         * @return <code>true</code>
         public boolean isFocusTraversable() {
         return true;
    * Initializes this <code>DateChooser</code> object. Creates the
    * controls, registers listeners and initializes the dialog box.
    private void construct()
         calendar = new GregorianCalendar();
         month = new JComboBox(MONTHS);
         month.addItemListener( this );
         year = new JComboBox();
         for ( int i=FIRST_YEAR; i<=LAST_YEAR; i++ )
         year.addItem( Integer.toString(i) );
         year.addItemListener( this );
         days = new JLabel[7][7];
         for ( int i=0; i<7; i++ ) {
         days[0] = new JLabel(DAYS[i],JLabel.RIGHT);
         days[0][i].setForeground( WEEK_DAYS_FOREGROUND );
         for ( int i=1; i<7; i++ )
         for ( int j=0; j<7; j++ )
              days[i][j] = new JLabel(" ",JLabel.RIGHT);
              days[i][j].setForeground( DAYS_FOREGROUND );
              days[i][j].setBackground( SELECTED_DAY_BACKGROUND );
              days[i][j].setBorder( EMPTY_BORDER );
              days[i][j].addMouseListener( this );
         ok = new JButton("Ok");
         ok.addActionListener( this );
         cancel = new JButton("Cancel");
         cancel.addActionListener( this );
         JPanel monthYear = new JPanel();
         monthYear.add( month );
         monthYear.add( year );
         daysGrid = new FocusablePanel(new GridLayout(7,7,5,0));
         daysGrid.addFocusListener( this );
         daysGrid.addKeyListener( this );
         for ( int i=0; i<7; i++ )
         for ( int j=0; j<7; j++ )
              daysGrid.add( days[i][j] );
         daysGrid.setBackground( Color.white );
         daysGrid.setBorder( BorderFactory.createLoweredBevelBorder() );
         JPanel daysPanel = new JPanel();
         daysPanel.add( daysGrid );
         JPanel buttons = new JPanel();
         buttons.add( ok );
         buttons.add( cancel );
         Container dialog = getContentPane();
         dialog.add( "North", monthYear );
         dialog.add( "Center", daysPanel );
         dialog.add( "South", buttons );
         pack();
         setResizable( false );
    * Gets the selected day, as an <code>int</code>. Parses the text
    * of the selected label in the calendar to get the day.
    * @return the selected day or -1 if there is no day selected
    private int getSelectedDay()
         if ( day == null )
         return -1 ;
         try {
         return Integer.parseInt(day.getText());
         } catch ( NumberFormatException e ) {
         return -1;
    * Sets the selected day. The day is specified as the label
    * control, in the calendar, corresponding to the day to select.
    * @param newDay day to select
    private void setSelected( JLabel newDay )
         if ( day != null ) {
         day.setForeground( DAYS_FOREGROUND );
         day.setOpaque( false );
         day.setBorder( EMPTY_BORDER );
         day = newDay;
         day.setForeground( SELECTED_DAY_FOREGROUND );
         day.setOpaque( true );
         if ( daysGrid.hasFocus() )
         day.setBorder( FOCUSED_BORDER );
    * Sets the selected day. The day is specified as the number of
    * the day, in the month, to selected. The function compute the
    * corresponding control to select.
    * @param newDay day to select
    private void setSelected( int newDay )
         setSelected( days[(newDay+offset-1)/7+1][(newDay+offset-1)%7] );
    * Updates the calendar. This function updates the calendar panel
    * to reflect the month and year selected. It keeps the same day
    * of the month that was selected, except if it is beyond the last
    * day of the month. In this case, the last day of the month is
    * selected.
    private void update()
         int iday = getSelectedDay();
         for ( int i=0; i<7; i++ ) {
         days[1][i].setText( " " );
         days[5][i].setText( " " );
         days[6][i].setText( " " );
         calendar.set( Calendar.DATE, 1 );
         calendar.set( Calendar.MONTH, month.getSelectedIndex()+Calendar.JANUARY );
         calendar.set( Calendar.YEAR, year.getSelectedIndex()+FIRST_YEAR );
         offset = calendar.get(Calendar.DAY_OF_WEEK)-Calendar.SUNDAY;
         lastDay = calendar.getActualMaximum(Calendar.DATE);
         for ( int i=0; i<lastDay; i++ )
         days[(i+offset)/7+1][(i+offset)%7].setText( String.valueOf(i+1) );
         if ( iday != -1 ) {
         if ( iday > lastDay )
              iday = lastDay;
         setSelected( iday );
    * Called when the "Ok" button is pressed. Just sets a flag and
    * hides the dialog box.
    public void actionPerformed( ActionEvent e ) {
         if ( e.getSource() == ok )
         okClicked = true;
         hide();
    * Called when the calendar gains the focus. Just re-sets the
    * selected day so that it is redrawn with the border that
    * indicate focus.
    public void focusGained( FocusEvent e ) {
         setSelected( day );
    * Called when the calendar loses the focus. Just re-sets the
    * selected day so that it is redrawn without the border that
    * indicate focus.
    public void focusLost( FocusEvent e ) {
         setSelected( day );
    * Called when a new month or year is selected. Updates the calendar
    * to reflect the selection.
    public void itemStateChanged( ItemEvent e ) {
         update();
    * Called when a key is pressed and the calendar has the
    * focus. Handles the arrow keys so that the user can select a day
    * using the keyboard.
    public void keyPressed( KeyEvent e ) {
         int iday = getSelectedDay();
         switch ( e.getKeyCode() ) {
         case KeyEvent.VK_LEFT:
         if ( iday > 1 )
              setSelected( iday-1 );
         break;
         case KeyEvent.VK_RIGHT:
         if ( iday < lastDay )
              setSelected( iday+1 );
         break;
         case KeyEvent.VK_UP:
         if ( iday > 7 )
              setSelected( iday-7 );
         break;
         case KeyEvent.VK_DOWN:
         if ( iday <= lastDay-7 )
              setSelected( iday+7 );
         break;
    * Called when the mouse is clicked on a day in the
    * calendar. Selects the clicked day.
    public void mouseClicked( MouseEvent e ) {
         JLabel day = (JLabel)e.getSource();
         if ( !day.getText().equals(" ") )
         setSelected( day );
         daysGrid.requestFocus();
    public void keyReleased( KeyEvent e ) {}
    public void keyTyped( KeyEvent e ) {}
    public void mouseEntered( MouseEvent e ) {}
    public void mouseExited( MouseEvent e) {}
    public void mousePressed( MouseEvent e ) {}
    public void mouseReleased( MouseEvent e) {}
    * Constructs a new <code>DateChooser</code> with the given title.
    * @param owner owner dialog
    * @param title dialog title
    public DateChooser( Dialog owner, String title )
         super( owner, title, true );
         construct();
    * Constructs a new <code>DateChooser</code>.
    * @param owner owner dialog
    public DateChooser( Dialog owner )
         super( owner, true );
         construct();
    * Constructs a new <code>DateChooser</code> with the given title.
    * @param owner owner frame
    * @param title

  • How to repaint a JPanel in bouncing balls game?

    I want to repaint the canvas panel in this bouncing balls game, but i do something wrong i don't know what, and the JPanel doesn't repaint?
    The first class defines a BALL as a THREAD
    If anyone knows how to correct the code please to write....
    package fuck;
    //THE FIRST CLASS
    class CollideBall extends Thread{
        int width, height;
        public static final int diameter=15;
        //coordinates and value of increment
        double x, y, xinc, yinc, coll_x, coll_y;
        boolean collide;
        Color color;
        Rectangle r;
        bold BouncingBalls balls; //A REFERENCE TO SECOND CLASS
        //the constructor
        public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c, BouncingBalls balls) {
            width=w;
            height=h;
            this.x=x;
            this.y=y;
            this.xinc=xinc;
            this.yinc=yinc;
            this.balls=balls;
            color=c;
            r=new Rectangle(150,80,130,90);
        public double getCenterX() {return x+diameter/2;}
        public double getCenterY() {return y+diameter/2;}
        public void move() {
            if (collide) {
            x+=xinc;
            y+=yinc;
            //when the ball bumps against a boundary, it bounces off
            //bounce off the obstacle
        public void hit(CollideBall b) {
            if(!collide) {
                coll_x=b.getCenterX();
                coll_y=b.getCenterY();
                collide=true;
        public void paint(Graphics gr) {
            Graphics g = gr;
            g.setColor(color);
            //the coordinates in fillOval have to be int, so we cast
            //explicitly from double to int
            g.fillOval((int)x,(int)y,diameter,diameter);
            g.setColor(Color.white);
            g.drawArc((int)x,(int)y,diameter,diameter,45,180);
            g.setColor(Color.darkGray);
            g.drawArc((int)x,(int)y,diameter,diameter,225,180);
            g.dispose(); ////////
        ///// Here is the buggy code/////
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.canvas.repaint();
    //THE SECOND CLASS
    public class BouncingBalls extends JFrame{
        public Graphics gBuffer;
        public BufferedImage buffer;
        private Obstacle o;
        private List<CollideBall> balls=new ArrayList();
        private static final int SPEED_MIN = 0;
        private static final int SPEED_MAX = 15;
        private static final int SPEED_INIT = 3;
        private static final int INIT_X = 30;
        private static final int INIT_Y = 30;
        private JSlider slider;
        private ChangeListener listener;
        private MouseListener mlistener;
        private int speedToSet = SPEED_INIT;
        public JPanel canvas;
        private JPanel p;
        public BouncingBalls() {
            super("fuck");
            setSize(800, 600);
            p = new JPanel();
            Container contentPane = getContentPane();
            final BouncingBalls xxxx=this;
            o=new Obstacle(150,80,130,90);
            buffer=new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
            gBuffer=buffer.getGraphics();
            //JPanel canvas start
            final JPanel canvas = new JPanel() {
                final int w=getSize().width-5;
                final int h=getSize().height-5;
                @Override
                public void update(Graphics g)
                   paintComponent(g);
                @Override
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    gBuffer.setColor(Color.ORANGE);
                    gBuffer.fillRect(0,0,getSize().width,getSize().height);
                    gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
                    //paint the obstacle rectangle
                    o.paint(gBuffer);
                    g.drawImage(buffer,0,0, null);
                    //gBuffer.dispose();
            };//JPanel canvas end
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            addButton(p, "Start", new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    CollideBall b = new CollideBall(canvas.getSize().width,canvas.getSize().height
                            ,INIT_X,INIT_Y,speedToSet,speedToSet,Color.BLUE,xxxx);
                    balls.add(b);
                    b.start();
            contentPane.add(canvas, "Center");
            contentPane.add(p, "South");
        public void addButton(Container c, String title, ActionListener a) {
            JButton b = new JButton(title);
            c.add(b);
            b.addActionListener(a);
        public boolean collide(CollideBall b1, CollideBall b2) {
            double wx=b1.getCenterX()-b2.getCenterX();
            double wy=b1.getCenterY()-b2.getCenterY();
            //we calculate the distance between the centers two
            //colliding balls (theorem of Pythagoras)
            double distance=Math.sqrt(wx*wx+wy*wy);
            if(distance<b1.diameter)
                return true;
            return false;
        synchronized void repairCollisions(CollideBall a) {
            for (CollideBall x:balls) if (x!=a && collide(x,a)) {
                x.hit(a);
                a.hit(x);
        public static void main(String[] args) {
            JFrame frame = new BouncingBalls();
            frame.setVisible(true);
    }  And when i press start button:
    Exception in thread "Thread-2" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-4" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    and line 153 is: balls.canvas.repaint(); in Method run() in First class.
    Please help.

    public RepaintManager manager;
    public BouncingBalls() {
            manager = new RepaintManager();
            manager.addDirtyRegion(canvas, 0, 0,canvas.getSize().width, canvas.getSize().height);
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.manager.paintDirtyRegions(); //////// line 153
       but when push start:
    Exception in thread "Thread-2" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    i'm newbie with Concurrency and i cant handle this exceptons.
    Is this the right way to do repaint?

Maybe you are looking for

  • ABAP, SD Error

    Hi Experts, I am facing the following error after doing VA01 i.e creation of sales order and while selecting the order from the list it is showing me the run time error. Runtime Errors         CALL_FUNCTION_CONFLICT_LENG Except.                CX_SY_

  • Percentage calculation from a certain point in time

    I am trying to calculate the pass rate from after the ID studied a particular UNIT. So I want to get the rate AFTER they studied their PREP01 unit So right now  the code below works fine but it considers all units. ID 1 studied one UNIT in 2010 which

  • Process flow- Assigning Versoins and Scenarios

    Hi John, I tried the new version Process flow in 11.1.2 and created a Planning hierarchy. Assigned an Owner and reviewer to it. When trying to assign scenarios and versions, I was able to select the Scenario but the Version drop down is showing the V

  • Error configuring the repository using Repository Assistant.

    Hi, I have a SYSDBA access to a oracle 9i instance and i tried to configure the OWB Repository through Repository Assistant. I am getting the following error. How can i rectify this error. INS0037 - The initialization parameter job_queue_processes of

  • Ios software problems

    why does it make me backup my stuff when i want to update new software, but it takes atleast an hour for it to do the tiniest bit, please help?