开发者

Does Container.getComponents() return references to the original components?

I'm using Container.getComponents() to get an array of Components stored inside the Container. I'm then modifying one of these Components (which happens to be a JLabel), but the changes are not showing on the GUI.

So I'm thinking maybe the method creates new instances of each Component which prevents me from making changes to the original component?

Here's my code:

Component[] components = source.getComponents();
if(components.length >= 2) {
 开发者_开发问答   if(components[1] instanceof JLabel) {
        JLabel htmlArea = (JLabel) components[1];
        htmlArea.setText("<html>new changes here</html>");
        htmlArea.revalidate();
    }
}


It is either another problem outside of the code, or you are doing this from the wrong thread.

Any changes on Swing components should be done in the event dispatch thread. Often is it most easy to surround the changing code with EventQueue.invokeLater(...) (or SwingUtilities.invokeLater, this is the same).

And make sure your component is actually visible on the screen.


There is no need to revalidate() or repaint() anything (unless you are doing something really strange)!

Where is your SSCCE that demonstrates your problem???

It works fine for me:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class TabbedPaneLabel extends JFrame
{
    JTabbedPane tabbedPane;

    public TabbedPaneLabel()
    {
        tabbedPane = new JTabbedPane();
        add(tabbedPane);

        tabbedPane.addTab("First", createPanel("<html>label with text</html>"));
        tabbedPane.addTab("Second", createPanel("another label"));

        JButton remove = new JButton("Change Label on first tab");
        add(remove, BorderLayout.SOUTH);
        remove.addActionListener( new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                Component[] components = tabbedPane.getComponents();
                JPanel panel = (JPanel)components[0];
                JLabel label = (JLabel)panel.getComponent(0);
                String date = new Date().toString();
                label.setText("<html>" + date + "</html>");
            }
        });
    }

    private JPanel createPanel(String text)
    {
        JPanel panel = new JPanel();
        panel.add( new JLabel(text) );
        return panel;
    }

    public static void main(String args[])
    {
        TabbedPaneLabel frame = new TabbedPaneLabel();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.setSize(300, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜