JPanel not repainting if embedded in another panel

I have a reusable class called as DuplicatorPanel. This class has two add/ remove buttons like in Mac if you are familiar.
The problem is that the screen gets updated with an extra row in case i have a main method in Duplicator itself. However if i have that in another panel as in HyperlinkBuilder then it does not repaint itself.
Please can someone help ?
package sam.dnd;
import java.awt.event.ActionEvent;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
public abstract class DuplicatorPanel extends Box {
    private static final long serialVersionUID = 1L;
    private static int oneup = 0;
    private Map<String, JComponent> panelMap = new LinkedHashMap<String, JComponent>();
    private Action addAction;
    private Action removeAction;
    public DuplicatorPanel() {
        super(BoxLayout.Y_AXIS);
        this.initComponents();
        this.placeComponents();
    private void initComponents() {
        addAction = new AddAction();
        removeAction = new RemoveAction();
        addDuplicatorPanel();
    private void placeComponents() {
        Iterator<JComponent> itr = this.panelMap.values().iterator();
        while(itr.hasNext()) {
            JComponent comp = (JComponent) itr.next();
            this.add(comp);
        this.add(Box.createVerticalGlue());
    private void addDuplicatorPanel() {
        int index = oneup++;
        JComponent component = this.createDuplicate();
        JButton btnAdd = new JButton("Add");
        btnAdd.setActionCommand("" + index);
        btnAdd.addActionListener(this.addAction);
        JButton btnRemove = new JButton("Remove");
        btnRemove.setActionCommand("" + index);
        btnRemove.addActionListener(this.removeAction);
        Box box = Box.createHorizontalBox();
        box.add(component);
        box.add(Box.createHorizontalGlue());
        box.add(btnAdd);
        box.add(btnRemove);
        this.panelMap.put("" + index, box);
        fireValueChanged();
    private void fireValueChanged() {
        this.removeAll();
        this.placeComponents();
        this.repaint();
    protected void doAdd() {
        addDuplicatorPanel();
        fireValueChanged();
    protected void doRemove(String key) {
        if(this.panelMap.size() == 1) {
            return;
        JComponent comp = this.panelMap.remove(key);
        if(comp != null) {
            this.fireValueChanged();
    protected abstract JComponent createDuplicate();
    class AddAction extends AbstractAction {
        private static final long serialVersionUID = 1L;
        public void actionPerformed(ActionEvent evt) {
            doAdd();
    class RemoveAction extends AbstractAction {
        private static final long serialVersionUID = 1L;
        public void actionPerformed(ActionEvent evt) {
            JButton source = (JButton) evt.getSource();
            doRemove(source.getActionCommand());
     * @param args
    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.add(new MyDuplicatorPanel());
        f.setSize(200, 200);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    static class MyDuplicatorPanel extends DuplicatorPanel {
        private static final long serialVersionUID = 1L;
        public JComponent createDuplicate() {
            return new JLabel("Test");
}This is another class that calls the above
package sam.dnd;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.HashMap;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class HyperLinkBuilder extends JPanel {
    private static final long serialVersionUID = 1L;
     * @param args
    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.add(new HyperLinkBuilder());
        f.setSize(200, 200);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    private static HashMap<String, String> linkNameValueMap = new HashMap<String, String>();
    private static HashMap<String, String> paramNameValueMap = new HashMap<String, String>();
    private static HashMap<String, String> valueNameValueMap = new HashMap<String, String>();
    static {
        linkNameValueMap.put("Name1", "Value1");
        linkNameValueMap.put("Name2", "Value2");
        linkNameValueMap.put("Name3", "Value3");
        paramNameValueMap.put("Name1", "Value1");
        paramNameValueMap.put("Name2", "Value2");
        paramNameValueMap.put("Name3", "Value3");
        valueNameValueMap.put("Name1", "Value1");
        valueNameValueMap.put("Name2", "Value2");
        valueNameValueMap.put("Name3", "Value3");
    private String link;
    private JComboBox linkCombo;
    private DuplicatorPanel panel;
    public HyperLinkBuilder() {
        this.initComponents();
        this.placeComponents();
        this.addListeners();
    private void initComponents() {
        linkCombo = new JComboBox(linkNameValueMap.keySet().toArray());
        panel = new MyDuplicatorPanel();
    private void placeComponents() {
        this.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        this.add(linkCombo, gbc);
        gbc.gridy++;
        gbc.fill = GridBagConstraints.BOTH;
        this.add(panel, gbc);
    private void addListeners() {
        this.linkCombo.addItemListener(new LinkSelector());
    private JPanel createNameValuePanel() {
        JComboBox nameCombo = new JComboBox(paramNameValueMap.keySet().toArray());
        JComboBox valueCombo = new JComboBox(valueNameValueMap.keySet().toArray());
        JPanel panel = new JPanel();
        panel.add(nameCombo);
        panel.add(valueCombo);
        return panel;
    private void doLinkSelected() {
        String name = (String) linkCombo.getSelectedItem();
        link = linkNameValueMap.get(name);
    public String build() {
        //TODO:
        return this.link;
    class LinkSelector implements ItemListener {
        public void itemStateChanged(ItemEvent e) {
            doLinkSelected();
    class MyDuplicatorPanel extends DuplicatorPanel {
        private static final long serialVersionUID = 1L;
        @Override
        protected JComponent createDuplicate() {
            return HyperLinkBuilder.this.createNameValuePanel();
}

Hey Xeon,
Replace that repaint() with revalidate. That is the trick in there.
-Sam

Similar Messages

  • After GLcanvas setVisible(false), normal JPanels sometimes not repainted.

    We are running an application which uses some jogl for animaties.
    Sometimes when the animation is finished and we set the GLCanvas to invisible, the normal
    java JPanels are not repainted.
    Also alt-tab to another windows application and back will not force a redraw.
    The application itself is still working, clicking on a (now) not visible button will trigger
    the jogl animations, and these are show correctly.
    Also from logging it appear that the AWT-thread is not blocking.
    We are looking for tips that can help find us the problem from logging
    as it only appears a few times a week and it is not reproducable.

    The problem is that most of the time it works, but after some hours/days, the java panels are not repainted.
    There is no memory leak.
    Pseudo code:
    public class AnimateTilePopup extends JPanel {
    GLCanvas glCanvas;
    public AnimateTilePopup() {
    super(null);
    setOpaque(true);
    glCanvas = new GLCanvas();
    glCanvas.setLocation(0,0);
    glCanvas.setSize(width, height);
    glCanvas.setVisible(false);
    glCanvas.setFocusable(false);
    add(glCanvas);
    flipRendererZoom = new AnimateRendererZoom();
    glCanvas.addGLEventListener(flipRendererZoom);
    public startAnimation() {
    glCanvas.setVisible(true);
    this.setVisible(true);
    public stopAnimation() {
    glCanvas.setVisible(false);
    this.setVisible(false);
    So sometimes when we call stopAnimation(), the animation is stoppped, but the underlying java JPanels are not repainted.
    When we now call startAnimation, the animation is shown and when stopped, no repaint for the normal JPanels.
    Most times it is working perfectly, only sometimes it failes.
    What can be the cause or what logging can be gather that might gives us a clue how to fix this problem.

  • Add a panel on another panel

    I am working on a program and need to put one panel into another panel . I have been successful at adding the panel
    however when i do this i cannot set the size of the 2nd panel. The first panel on the frame is just fine
    i have tried adding the panel to the first panels constructor this works the panel shows up but i am unable
    to set the size of the panel which is the problem.
    I tried calling this.setSize in the second panels constructor to solve this problem no luck there
    i have also tried adding the 2nd panel to the frame but this produces the same problem as stated above
    im really stumped any help woul be appreciated
    here is some code i have
    This is the frames class with the first panel added
    public ICUFrame () {
            super("ICU");
            canvas= new ICUPanel();
            add(canvas, BorderLayout.CENTER);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(1000,1000);
            setVisible(true);
        } this is the panel on the frame
    only the constructor is required here as the rest is just code for drawing etc...
    public class ICUPanel extends JPanel {
        DiaDisplay d ;
        SysDisplay s;
        public ICUPanel(){
            super();
            setBackground(Color.BLACK);
            ICUMonitoring monitor = new ICUMonitoring();
            Thread rep = new Thread(new Repainter());
            d = new DiaDisplay(220,20,40,200);
            s = new SysDisplay(420,220,40,200);
            rep.start();
        }// end of constructor
    }this is the 2nd panel i am trying to add to the 1st panel
    public class ECGPanel extends JPanel {
        ecgDisplay e;
         public ECGPanel(){
         super();
         setBackground(Color.white);
         e = new ecgDisplay();
        }// end of constructor
    }

    xiaolixx wrote:
    I am working on a program and need to put one panel into another panel . I have been successful at adding the panel
    however when i do this i cannot set the size of the 2nd panel. The first panel on the frame is just fine
    i have tried.. What happened to your shift key? Please apply it once at the start of every sentence, rather than those rare occasions you 'feel like it'. Adding an upper case letter to each sentence makes it easier for people to quickly scan the text, looking for ways to help. You would not want to make it harder for someone to help, would you?
    ..adding the panel to the first panels constructor this works the panel shows up but i am unable
    to set the size of the panel which is the problem.
    I tried calling this.setSize in the second panels constructor to solve this problem no luck there
    i have also tried adding the 2nd panel to the frame but this produces the same problem as stated above
    im really stumped any help woul be appreciated
    here is some code i haveAlso known as 'uncompilable code snippets'. For better help sooner, post an SSCCE . But first, go through the tutorial to which Darryl linked.

  • Adding and displaying a new JPanel -- not working as expected

    I'm starting my own new thread that is based on a problem discussed in another person's thread that can be found here in the New to Java forum titled "ActionListener:
    http://forum.java.sun.com/thread.jspa?threadID=5207301
    What I want to do: press a button which adds a new panel into another panel (the parentPane), and display the changes. The Actionlistener-derived class (AddPaneAction) for the button is in it's own file (it's not an internal class), and I pass a reference to the parentPane in the AddPaneAction's constructor as a parameter argument.
    What works: After the button is clicked the AddPaneAction's actionPerformed method is called without problem.
    What doesn't work: The new JPanel (called bluePanel) is not displayed as I thought it would be after I call
            parentPane.revalidate();  // this doesn't work
            parentPane.repaint(); 
    What also doesn't work: So I obtained a reference to the main app's JFrame (I called it myFrame) by recursively calling component.getParent( ), no problem there, and then tried (and failed to show the bluePanel with) this:
            myFrame.invalidate();  // I tried this with and without calling this method here
            myFrame.validate();  // I tried this with and without calling this method here
            myFrame.repaint();
    What finally works but confuses me: I got it to work but only after calling this:
            myFrame.pack(); 
            myFrame.repaint();But I didn't think that I needed to call pack to display the panel. So, what am I doing wrong? Why are my expectations not correct? Here's my complete code/SSCCE below. Many thanks in advance.
    Pete
    The ParentPane class:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class ParentPane extends JPanel
        private JButton addPaneBtn = new JButton("Add new Pane");
        public ParentPane()
            super();
            setLayout(new BorderLayout());
            setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
            setBackground(Color.yellow);
            JPanel northPane = new JPanel();
            northPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
            northPane.setBackground(Color.yellow);
            northPane.add(addPaneBtn);
            add(northPane, BorderLayout.NORTH);
            // add our actionlistener object and pass it a reference
            // to the main class which happens to be a JPanel (this)
            addPaneBtn.addActionListener(new AddPaneAction(this));
        public static void main(String[] args)
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
        private static void createAndShowGUI()
            JFrame frame = new JFrame("test add panel");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new ParentPane());
            frame.pack();
            frame.setVisible(true);
    } the AddPaneAction class:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingConstants;
    public class AddPaneAction implements ActionListener
        private JPanel parentPane;
        private JFrame myFrame;
        public AddPaneAction(JPanel parentPane)
            this.parentPane = parentPane;
         * recursively get the JFrame that holds the parentPane panel.
        private JFrame getJFrame(Component comp)
            Component parentComponent = comp.getParent();
            if (parentComponent instanceof JFrame)
                return (JFrame)parentComponent;
            else
                return getJFrame(parentComponent);
        public void actionPerformed(ActionEvent arg0)
            JPanel bluePanel = new JPanel(new BorderLayout());
            bluePanel.setBackground(Color.blue);
            bluePanel.setPreferredSize(new Dimension(400, 300));
            JLabel myLabel = new JLabel("blue panel label");
            myLabel.setForeground(Color.LIGHT_GRAY);
            myLabel.setVerticalAlignment(SwingConstants.CENTER);
            myLabel.setHorizontalAlignment(SwingConstants.CENTER);
            bluePanel.add(myLabel, BorderLayout.CENTER);
            parentPane.add(bluePanel);
            myFrame = getJFrame(parentPane);
            //parentPane.revalidate();  // this doesn't work
            //parentPane.repaint(); 
            //myFrame.invalidate(); // and also this doesn't work
            //myFrame.validate();
            //myFrame.repaint();
            myFrame.pack();  // but this does!?
            myFrame.repaint();
    }

    For me (as it happens I'm using JDK 1.5.0_04) your code appears to work fine.
    It may be that we're seeing the same thing but interpreting it differently.
    1. When I run your application with your "working" code, and press the button then the JFrame resizes and the blue area appears.
    2. When I run your application with your "not working" code and press the button then the JFrame does not resize. If I manually resize it then the blue area is there.
    3. When I run your application with your "not working" code, resize it first and then press the button then the JFrame then the blue area is there.
    I interpret all of this as correct behaviour.
    Is this what you are seeing too?
    Are you expecting revalidate, repaint, invalidate or validate to resize your JFrame? I do not.
    As an aside, I do remember having problems with this kind of thing in earlier JVMs (e.g. various 1.2 and 1.3), but I haven't used it enough recently to know if your code would manifest one of the previous problems or not. Also I don't know if they've fixed any stuff in this area.

  • Center a panel in another panel

    Good day:
    I am trying to center align (horizontal & vertical centering) a panel in another panel.
    How would I go about doing this?
    I have tried a few different layout managers, but they have not produced the results I am looking for.
    The parent panel is fixed sized, but the child panel is dynamic.
    Please help!!

    Thank you for your post, I greatly appreciate it. However, I tried both of those methods, and my child JPanel is always being placed in the upper left corner of the parent JPanel.
    Here is some code showing my initialization of the JPanel, and the adding of the child JPanel:
    Creating the parent JPanel:
            imagePreview = new JPanel();
            imagePreview.setBackground(Color.white);
            imagePreview.setBorder(new LineBorder(Color.black,1,true));
            getContentPane().add(imagePreview);Adding the child JPanel
    void displayThumbnail()
                  wallpaperChanger.imagePreview.removeAll();
                  wallpaperChanger.imagePreview.add(new viewer(THUMB_LOCATION));
                  wallpaperChanger.imagePreview.repaint();
             }If it helps, the viewer class:
    class viewer extends JPanel
         private Image image;
         public viewer(String fileName)
              Toolkit toolkit = Toolkit.getDefaultToolkit();
              image = toolkit.createImage(fileName);
              MediaTracker mediaTracker = new MediaTracker(this);
              mediaTracker.addImage(image, 0);
              try
                   mediaTracker.waitForID(0);
              catch (InterruptedException ie)
                   System.err.println(ie);
              setSize(image.getWidth(null), image.getHeight(null));
              //show();
         public void paint(Graphics graphics)
              graphics.drawImage(image, 0, 0, null);
    }

  • Whole screen is not repainted, need debug tips

    We are running an application which uses some jogl for animaties.
    Sometimes when the animation is finished and we set the GLCanvas to invisible, the normal
    java JPanels are not repainted.
    Also alt-tab to another windows application and back will not force a redraw.
    The application itself is still working, clicking on a (now) not visible button will trigger
    the jogl animations, and these are show correctly.
    Also from logging it appear that the AWT-thread is not blocking.
    We are looking for tips that can help find us the problem from logging
    as it only appears a few times a week and it is not reproducable.

    The problem is that most of the time it works, but after some hours/days, the java panels are not repainted.
    There is no memory leak.
    paintComponent is not overwritten, a object is made visible to do the animation.
    Pseudo code:
    public class AnimateTilePopup extends JPanel {
    GLCanvas glCanvas;
    public AnimateTilePopup() {
    super(null);
    setOpaque(true);
    glCanvas = new GLCanvas();
    glCanvas.setLocation(0,0);
    glCanvas.setSize(width, height);
    glCanvas.setVisible(false);
    glCanvas.setFocusable(false);
    add(glCanvas);
    flipRendererZoom = new AnimateRendererZoom();
    glCanvas.addGLEventListener(flipRendererZoom);
    public startAnimation() {
    glCanvas.setVisible(true);
    this.setVisible(true);
    public stopAnimation() {
    glCanvas.setVisible(false);
    this.setVisible(false);
    So sometimes when we call stopAnimation(), the animation is stoppped, but the underlying java JPanels are not repainted.
    When we now call startAnimation, the animation is shown and when stopped, no repaint for the normal JPanels.
    Most times it is working perfectly, only sometimes it failes.
    What can be the cause or what logging can be gather that might gives us a clue how to fix this problem.

  • Application's main window is not repainted

    Hello everybody.
    The system I am using
    Product Version: NetBeans IDE 6.5 (Build 200811100001)
    Java: 1.6.0_12; Java HotSpot(TM) Client VM 11.2-b01
    System: Windows Vista version 6.0 running on x86; Cp1251; ru_RU (nb)I created Java Desktop application (New project - Java Desktop Application (no CRUD)) and put a JTable like this:
    mainPanel[JPanel]
        jScrollPane1[JScrollPane]
            jTable1[JTable]
    I did not do anything more. But after building project I have a problem with my application - main window does not repaint itself after another window is positioned over it(calculator, for example). It repaints only after I resized main window or something like that ...
    What am I doing wrong?
    Thank you.

    I found a solution - to resolve this bug I have to set -Dsun.java2d.noddraw=true VM flag.
    I found the same bug in a database - [4139083|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4139083] and it's submit date is *15-MAY-1998* !!!
    There is also an issue about that kind of a problem - [6343853|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6343853], submit date 31-OCT-2005.
    So, I guess unfortunately there are a lot of things to think about ...

  • Switching a panel to another panel in the same frame.Is there a better way?

        public void actionPerformed(ActionEvent e) {
            if (e.getSource() instanceof toolButton){
                westPanel.remove(optionPanel);
                westPanel.setVisible(false);
                toolButton tb = (toolButton)e.getSource();
                optionPanel = tb.getPanel();
                westPanel.add(optionPanel);
                westPanel.setVisible(true);
        }This code above is what I used to execute when one of several JButtons is being pressed.
    In this program, one of the JPanel will be automatically switched to another JPanel when you press the respective JButtons.
    Here are my questions:
    1. Right now, I use westPanel.setVisible(false) and then change some stuff and then invoke westPanel.setVisible(true) to make it visible again. Although this works, I have a feeling that this is not quite right. I feel that there should be some better way to do this, switching the panel and request the program to redraw the replacing JPanel. Is there a better way for this?
    2. Most of the time, the JPanel changes the size according to the components on it. I have tried several LayoutManager, but it seems that those components have more priority. Is there a way to completely fix the JPanel so that they stay the same size?

    Look into using a Card Layout rather than manually swapping the panels: http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html

  • Position panel in centre of another panel

    This is one of those things that should be straightforward, but just isn't working out that way.
    I have a JPanel called PanelA.
    Prompted by a user action, I just want to add another (smaller) JPanel called PanelB in the centre of PanelA.
    I've tried using a BorderLayout on PanelA, and doing this :
    PanelA.add(PanelB, BorderLayout.CENTER);but this adds PanelB at the top of PanelA.
    Does anyone know how I can just have this smaller panel appear dead-centre in the larger panel?

    if you have licence for Borland JBCL library (VerticalFlowLayout)
    you can use this code here.
    public static final void addToPanel(Container xy, JPanel x, String title) {
        String name = x.getName();
        if (name == title) {
          System.err.print("ERROR PANEL IS ALREADY THERE");
          return;
        clearPanel(x);
        EtchedBorder border1 = new EtchedBorder(EtchedBorder.RAISED, Color.white,
                                                new Color(148, 145, 140));
        TitledBorder titledBorder1;
        titledBorder1 = new TitledBorder(border1, title);
        JPanel pan = new JPanel();
        JPanel pan2 = new JPanel();
        JPanel containerPanel = new JPanel();
        pan2.setLayout(new FlowLayout());
        VerticalFlowLayout vertical = new VerticalFlowLayout();
        vertical.setAlignment(VerticalFlowLayout.MIDDLE);
        pan.setLayout(vertical);
        containerPanel.setBorder(titledBorder1);
        containerPanel.add(xy, BorderLayout.CENTER);
        pan2.add(containerPanel);
        pan.add(pan2);
        x.add(pan, BorderLayout.CENTER);
        x.validate();
        x.repaint();
        // x.setName(title);
        x.updateUI();

  • How to use another panels in status line

    Hi Everyone:
    Can anybody tell me how can i use another panels in the
    Console's status line, I'm using the message line but i need to
    show the user's name and Date-Tiem in another section of the
    status line and not in display controls as i'm already doing it.
    Thanks.

    Do you really need a JSF component for that? You can use h:panelGroup and some JS. But a simple div with some JS is also sufficient.

  • How can transfer data from a dialog to another panel?

    Will anyone help me?Thanks.
    In our project,When the user need to fill some data into the textfield in a panel,he can simplify this action by click a button,when the button is clicked,then a dialog which contains a table of all the imformation of all customers will show,then the user can select one customer's information from the table,after click a button such as "OK",the selected information will show in corresponding textfiled in another panel.Because the dialog and the panel are two
    different object,so how can I transfer the data selected from the dialog to the panel and show the updated information timely??

    try this program. it exchanges some data between s adialog and a frame.
    akz
    * @version 1.20 01 Sep 1998
    * @author Cay Horstmann
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class DataExchangeTest extends JFrame
    implements ActionListener
    {  public DataExchangeTest()
    {  setTitle("DataExchangeTest");
    setSize(300, 300);
    JMenuBar mbar = new JMenuBar();
    setJMenuBar(mbar);
    JMenu fileMenu = new JMenu("File");
    mbar.add(fileMenu);
    connectItem = new JMenuItem("Connect");
    connectItem.addActionListener(this);
    fileMenu.add(connectItem);
    exitItem = new JMenuItem("Exit");
    exitItem.addActionListener(this);
    fileMenu.add(exitItem);
    public void actionPerformed(ActionEvent evt)
    {  Object source = evt.getSource();
    if (source == connectItem)
    {  ConnectInfo transfer= new ConnectInfo("yourname", "pw");
    if (dialog == null)
    dialog = new ConnectDialog(this);
    if (dialog.showDialog(transfer))
    {  String uname = transfer.username;
    String pwd = transfer.password;
    Container contentPane = getContentPane();
    contentPane.add(new JLabel("username=" + uname + ", password=" + pwd),"South");
    validate();
    else if(source == exitItem)
    System.exit(0);
    public static void main(String[] args)
    {  JFrame f = new DataExchangeTest();
    f.show();
    private ConnectDialog dialog = null;
    private JMenuItem connectItem;
    private JMenuItem exitItem;
    class ConnectInfo
    {  public String username;
    public String password;
    public ConnectInfo(String u, String p)
    { username = u; password = p; }
    class ConnectDialog extends JDialog implements ActionListener
    {  public ConnectDialog(JFrame parent)
    {  super(parent, "Connect", true);
    Container contentPane = getContentPane();
    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(2, 2));
    p1.add(new JLabel("User name:"));
    p1.add(username = new JTextField(""));
    p1.add(new JLabel("Password:"));
    p1.add(password = new JPasswordField(""));
    contentPane.add("Center", p1);
    Panel p2 = new Panel();
    okButton = addButton(p2, "Ok");
    cancelButton = addButton(p2, "Cancel");
    contentPane.add("South", p2);
    setSize(240, 120);
         //custom method to create and buttons to a container
    JButton addButton(Container c, String name)
    {  JButton button = new JButton(name);
    button.addActionListener(this);
    c.add(button);
    return button;
    public void actionPerformed(ActionEvent evt)
    {  Object source = evt.getSource();
    if(source == okButton)
    {  ok = true;
    setVisible(false);
    else if (source == cancelButton)
    setVisible(false);
    public boolean showDialog(ConnectInfo transfer)
    {  username.setText(transfer.username);
    password.setText(transfer.password);
    ok = false;
    show();
    if (ok)
    {  transfer.username = username.getText();
    transfer.password = password.getText();
    return ok;
    private JTextField username;
    private JTextField password;
    private boolean ok;
    private JButton okButton;
    private JButton cancelButton;

  • Module not unloading if embedded font was ever used

    So, I have a test app that uses modules with the font embeded. Using ModuleManager I am able to load up the module. Once I call   IModuleInfo.factory.create(), I am then able to setStyle("fontFamily", "BPDiet") and the font does show up. The issue I am now having is that once I have used a font from a module, even if my TextArea is no longer using it (I even tried removing the textArea, and replacing it with a new one), the module will not unload.
    I read through this "What We Know About Unloading Modules" and I think I am not leaving any references around.They are loaded using the load() defaults. There is no code (that is used) in the module. The modules are not being added to the display, so they never receive focus.
    Note that I am unable to run the profiler as suggested in the article as I don't have the premium Flash Builder 4. <grrr>
    Note that the first module that is loaded, I can never get to unload, even if I never used the font embedded in it, but all subsequent modules will unload, if I do not use the embedded font. I can live with the first one being pinned as long as I can unload the others that are not in use.
    Here is the code from one of my modules:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Module xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx">
        <fx:Script>
            <![CDATA[
                import spark.components.TextArea;
                [Embed(source='assets/BPDiet.otf',
                        fontName='BPDiet',
                           mimeType='application/x-font')]
                public static var BPDietNormal:Class;
                public function GetSampleTextArea():TextArea {
                    var SampleTextArea:TextArea = new TextArea();
                    SampleTextArea.text = "Test BPDiet please!";
                    SampleTextArea.setStyle("fontFamily", 'BPDiet');
                    return SampleTextArea;           
            ]]>
        </fx:Script>
    </mx:Module>
    And here is the App that is loading and using the modules:
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="400" minHeight="400">
        <fx:Script>
            <![CDATA[
                import mx.collections.ArrayCollection;
                import mx.core.UIComponent;
                import mx.events.FlexEvent;
                import mx.events.ModuleEvent;
                import mx.managers.SystemManager;
                import mx.modules.IModule;
                import mx.modules.IModuleInfo;
                import mx.modules.Module;
                import mx.modules.ModuleManager;
                import spark.components.TextArea;
                private var _ta:TextArea = null;
                protected var _moduleInfo:IModuleInfo;
                private function LoadFontTextArea(fontSwf:String):void {
                    status.text = "Loading the font pack";
                    _moduleInfo = ModuleManager.getModule(fontSwf);
                    // add some listeners
                    _moduleInfo.addEventListener(ModuleEvent.READY, onModuleReady);
                    _moduleInfo.addEventListener(ModuleEvent.ERROR, moduleLoadErrorHandler);
                    _moduleInfo.addEventListener(ModuleEvent.UNLOAD, moduleUnloadHandler);
                    _moduleInfo.load();
                private function onModuleReady(event:ModuleEvent):void {
                    status.text = "The font pack swf Ready \n" + event.module.url;
                    //All I had todo was create the module, then I could access the embeded font by name
                    var fontMod:* = event.module.factory.create();
                    //_ta = fontMod.GetSampleTextArea();
                    //panelToStuff.addElement(_ta);
                    fontMod = null;
                    //fontNameForSample = event.module.url.replace(".swf", "");
                private function moduleLoadErrorHandler(event:ModuleEvent):void {
                    status.text = "Font Module Load Error. \n" +
                        event.module.url + "\n"+ event.errorText;
                private function moduleUnloadHandler(event:ModuleEvent):void {
                    status.text = "Font Module Unload Event. \n" + event.module.url;
                private function fontChangedHandler():void {
                    unloadCurrentFont();
                    LoadFontTextArea(String(availFonts.selectedItem));
                private function unloadCurrentFont():void {
                    if (_ta != null) {
                        panelToStuff.removeElement(_ta);
                        _ta = null;
                    panelToStuff.removeElement(sampleTextArea);
                    sampleTextArea = null;
                    sampleTextArea = new TextArea();
                    sampleTextArea.id = "sampleTextArea";
                    sampleTextArea.text = "Some text for your viewing pleasure. " + colorForBK.toString(16);
                    panelToStuff.addElement(sampleTextArea);               
                    if (_moduleInfo != null)
                        _moduleInfo.release();
                        //_moduleInfo.unload();
                        _moduleInfo = null;
                    System.gc();
                private function DoNonImportantWork():void {
                    colorForBK -= 0xFAA;
                    if (colorForBK < 0x0) colorForBK = 0xFFFFFF;
                    var foo:* = {prop1: "yea" + colorForBK.toString(), prop2:"boo" + colorForBK.toString()};
                    var hmm:String = foo.prop1 + " " + foo.prop2;
                    regedFonts = new ArrayCollection(Font.enumerateFonts(false));
                [Bindable]
                private var colorForBK:int = 0xFFFFFF;
                [Bindable]
                private var fonts:ArrayCollection =
                    new ArrayCollection(new Array("AlexandriaFLF.swf", "BPDiet.swf", "ChanpagneFont.swf", "KidsFont.swf"));
                [Bindable]
                private var regedFonts:ArrayCollection;
                [Bindable]
                private var fontNameForSample:String = "";
            ]]>
        </fx:Script>
        <s:VGroup id="panelToStuff">
            <s:HGroup>
                <s:Label id="status" text="status area" backgroundColor="{colorForBK}"/>
                <s:VGroup>
                    <s:DropDownList id="availFonts" dataProvider="{fonts}" change="fontChangedHandler()" />
                    <s:Button label="UnLoad" enabled="true" click="unloadCurrentFont()"/>
                    <s:Button label="doSome" enabled="true" click="DoNonImportantWork()"/>
                </s:VGroup>
            </s:HGroup>
            <s:HGroup>
                <s:Button click="fontNameForSample = 'BPDiet';" label="BPDiet"/>
                <s:Button click="fontNameForSample = 'Champagne';" label="Champagne"/>
                <s:Button click="fontNameForSample = 'Kids';" label="Kids"/>
            </s:HGroup>
            <s:Label text="{regedFonts.length} reg'ed"/>
            <s:TextArea id="sampleTextArea" fontFamily="{fontNameForSample}" text="Some Sample text for your viewing"/>
        </s:VGroup>
    </s:Application>
    A couple things to note; I am calling System.rc() in the unloadCurrentFont() method just to speed up seeing the SWF unload in the debug console. The DoNonImportantWork() is there to just cause some events to happen and to create some objects that will need to be GC'ed. It also let me know that the fonts are not getting registered in Font.
    I'm going to have 30 fonts (and more, that designer is busy) that I will need to be able to dynamically load, but right now, loading them with CSS style modules blows up after about 15 because style modules register the font so I cannot unload the CSS swf.

    To help eliminate the question of whether the TextArea is being held by something else, I have removed it from the MXML, and now programatically create it. That did not help.
    So, I got the trial version of Flash Builder 4 installed on another machine in the office so that I can use the profiler. (The profiler is pretty cool by the way).
    After a lot of profiing, I found four paths to the module's FlexModuleFactory.
    Two of those paths go to EmbeddedFontRegistry, whose data is static. I could get into it and remove font entry and free up the moduleFactory from there. This is a hack, that entry in/on EmbeddedFontRegistry.font should have been cleaned up by the code removing the fontFamily from the TextArea. (Note that EmbeddedFontRegistry is marked [ExcludeClass], which I assume means I should not really be messing with it.
    The other two I cannot get to as they are anonymous. They also don't appear to be referenced, as the Object References shows them both as GC root objects. Here is a screen shot:
    I did a search through the sdk code and 'fbs' only shows up as a parameter on the init function of various Marshal support classes, but is not used in the init()
    Anyway, these references to the FlexModuleFactory do not get held if I do not use the embeded font in the module.
    Here is the updated code:
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="400" minHeight="400">
        <fx:Script>
            <![CDATA[
                import mx.collections.ArrayCollection;
                import mx.core.EmbeddedFont;
                import mx.core.EmbeddedFontRegistry;
                import mx.core.IEmbeddedFontRegistry;
                import mx.core.UIComponent;
                import mx.events.FlexEvent;
                import mx.events.ModuleEvent;
                import mx.managers.SystemManager;
                import mx.modules.IModule;
                import mx.modules.IModuleInfo;
                import mx.modules.Module;
                import mx.modules.ModuleManager;
                import spark.components.TextArea;
                private var _ta:TextArea = null;
                protected var _moduleInfo:IModuleInfo;
                private function LoadFontTextArea(fontSwf:String):void {
                    status.text = "Loading the font pack";
                    _moduleInfo = ModuleManager.getModule(fontSwf);
                    // add some listeners
                    _moduleInfo.addEventListener(ModuleEvent.READY, onModuleReady);
                    _moduleInfo.addEventListener(ModuleEvent.ERROR, moduleLoadErrorHandler);
                    _moduleInfo.addEventListener(ModuleEvent.UNLOAD, moduleUnloadHandler);
                    _moduleInfo.load();
                private function onModuleReady(event:ModuleEvent):void {
                    status.text = "The font pack swf Ready \n" + event.module.url;
                    //All I had todo was create the module, then I could access the embeded font by name
                    var fontMod:* = event.module.factory.create();
                    fontMod = null;
                private function moduleLoadErrorHandler(event:ModuleEvent):void {
                    status.text = "Font Module Load Error. \n" +
                        event.module.url + "\n"+ event.errorText;
                private function moduleUnloadHandler(event:ModuleEvent):void {
                    status.text = "Font Module Unload Event. \n" + event.module.url;
                private function fontChangedHandler():void {
                    unloadCurrentFont();
                    LoadFontTextArea(String(availFonts.selectedItem));
                private function unloadCurrentFont():void {
                    if (_ta != null && _moduleInfo != null) {
                        var fontName:String = _ta.getStyle("fontFamily");
                        _ta.setStyle("fontFamily", "");
                        _ta.validateProperties();
                        if (_ta.textDisplay) {
                            _ta.textDisplay.validateProperties();
                        panelToStuff.removeElement(_ta);               
                        _ta = null;
                        //This I should not have to do, but the framework is not doing it
                        var embFontReg:IEmbeddedFontRegistry = EmbeddedFontRegistry.getInstance();
                        var embFonts:Array = embFontReg.getFonts();
                        for each (var curEmbFont:EmbeddedFont in embFonts){
                            if (curEmbFont.fontName == fontName){
                                embFontReg.deregisterFont(curEmbFont, _moduleInfo.factory);
                    if (_moduleInfo != null)
                        _moduleInfo.unload();
                        _moduleInfo = null;
                    System.gc();
                private function AddTA():void {
                    _ta = new TextArea();
                    _ta.text = "Some text for your viewing pleasure. " + colorForBK.toString(16);
                    panelToStuff.addElement(_ta);
                private function DoNonImportantWork():void {
                    colorForBK -= 0xFAA;
                    if (colorForBK < 0x0) colorForBK = 0xFFFFFF;
                    var foo:* = {prop1: "yea" + colorForBK.toString(), prop2:"boo" + colorForBK.toString()};
                    var hmm:String = foo.prop1 + " " + foo.prop2;
                [Bindable]
                private var colorForBK:int = 0xFFFFFF;
                [Bindable]
                private var fonts:ArrayCollection =
                    new ArrayCollection(new Array("AlexandriaFLF.swf", "BPDiet.swf", "ChanpagneFont.swf", "KidsFont.swf"));
            ]]>
        </fx:Script>
        <s:VGroup id="panelToStuff">
            <s:HGroup>
                <s:Label id="status" text="status area" backgroundColor="{colorForBK}"/>
                <s:VGroup>
                    <s:DropDownList id="availFonts" dataProvider="{fonts}" change="fontChangedHandler()" />
                    <s:Button label="UnLoad" enabled="true" click="unloadCurrentFont()"/>
                    <s:Button label="AddTA" enabled="true" click="AddTA()"/>
                    <s:Button label="doSome" enabled="true" click="DoNonImportantWork()"/>
                </s:VGroup>
            </s:HGroup>
            <s:Button click="_ta.setStyle('fontFamily', 'BPDiet');" label="BPDiet"/>
        </s:VGroup>
    </s:Application>
    I really think I've reached the end of what I can do. This really seems like a bug.

  • Displaying thumbnail images in another panel when it  mouse clicked

    hi,
    I am using JAI, what i am trying to do is i am decoding the tiff file and creating thumbnail of that images and adding thumbnail images to one panel and enlarged images to another panel using DisplayJAI. Now when i will click i thumbnail images on left panel then that image should be display to another panel on right side. Adding both panel to JSplit panel.
    I have no idia how to do it, i tried to do in different way but not able to do that. I hope anybody can give me the hints about this.
    Thanks

    i am adding thumbnail of all images in left panel and enlarged view of each thumbnail is added in right panel , and what i require that when i click thumbnail in left side it's corresponding enlarged image should be visible, suppose in right panel page no. 1 is visible and when i click thumbnail of 13 page in left panel that should be in viewport of right panel.You should put your right panel inside a JScrollPane and call [scrollRectToVisible() |http://java.sun.com/javase/6/docs/api/javax/swing/JComponent.html#scrollRectToVisible(java.awt.Rectangle)] from your panel. You can put the rectangles corresponding to enlarged images in a hash map with the keys being some unique attribute of your thumbnails in left panel. That will help in getting the rectangle to make visible, real fast. Or, you can just put the rectangles in some array indexed according to the thumbnails in left panel.
    I also want to hide the left panel, i think it's possible by Frame.Yes it is possible, but you said you have both your panels in a split pane, so maybe you can use its setDividerLocation() function to hide your left panel.
    Thanks!

  • Moving canvas3d from one panel to another panel is causing problems

    Hi,
    I'm new to java3d and at present struggling to find a solution for the following problem:
    In my application there are 4 canvas3ds and there are no relation between them except they all share the same screen3d. added in a Jpanel using grid layout(2,2). all have different universe. when user double click s any one of them the clicked canvas is supposed to get maximized and again doing the same restores everything before double click.
    What i'm doing is using card layout adding two panels one for normal view(4 at a time) and one for maximized view. The first one uses grid and the other one uses border.
    In case of maiximizing i just remove the one that's clicked from the former jpanel and add it to the other panel.But some times it garbles the screen in a way such that on rotating any node or element moves other nodes that are not supposed to be.
    Any suggestions???

    well you should have posted in java3d forum, but at this point i'd say post code so we can see what you mean by "garbles"

  • Indexing - one document embedded within another

    Greetings,
    I am testing KM indexing in terms of examining how Trex handles the indexing of a scenario where you have one document embedded within another document.
    In this case I have chosen to embed a PowerPoint (.ppt document) within a Word document (.doc document).
    I index the Word document, expecting to therefore also have the PowerPoint document within indexed. When I search for the text within the embedded .ppt document I do not get results and therefore assume that Trex cannot index documents which are embedded in other documents. Please advise if I am correct. 
    Regards,
    Keith

    >
    Keith Kibuuka wrote:
    > Greetings,
    >
    > I am testing KM indexing in terms of examining how Trex handles the indexing of a scenario where you have one document embedded within another document.
    >
    > In this case I have chosen to embed a PowerPoint (.ppt document) within a Word document (.doc document).
    >
    > I index the Word document, expecting to therefore also have the PowerPoint document within indexed. When I search for the text within the embedded .ppt document I do not get results and therefore assume that Trex cannot index documents which are embedded in other documents. Please advise if I am correct. 
    >
    > Regards,
    > Keith
    Hi Keith,
    yes that's exactly correct from my knowledge's point of view.
    I had a similar issue with an HTML-document that contained another HTML-document as iframe and this is also not possible (I asked SAP about this, so for this I am sure).
    TREX does anyway a transformation for all sort of documents to HTML documents (so also DOCs or PDFs are firstly converted to HTML before they are indexed). And in here TREX never follows any embedded content.

Maybe you are looking for

  • SecurityMode.TransportWithMessageCredential Binding does not encrypt the message

    When I send a message with SecurityMode.TransportWithMessageCredential  Binding (over https), I can see the decrypted message in the service log file. Isn't the message supposed to be encrypted? Bob

  • Transporting TEM module

    Hello experts,        Can anybody suggest me the best method to transport all training and event management objects and relationships. Please help ... Thanks & regards, Pavan

  • ITunes: Is there a setting to keep the volume level the same?

    Anyone know whether there is a way to adjust playback volume when making a mixed playlist? Very annoying to have to always turn the volume up and down when listening.

  • Flash project audio button help needed

    Hi, I am just learning Actionscript 3 and trying to create buttons that turn a previous sound off before they turn a new one on. Also I want a button on the front that turns all sound off if it is pressed. I have attached my files in a zip folder. Th

  • Services in Portland, OR area

    This isn't totally a FCP question (FCP will be used for the end product) but I know many of you know other info that can help me out. I'm in the Los Angeles area and I'm working with a client in Porland, OR. I need someone to shoot a 1 minute of tale