Java JScrollPane- Multiple components

a 夏天 提交于 2019-12-31 02:48:04

问题


I'm trying to add 2 images inside the JScrollPane. the first image is a background and the second one overlap the first one. The problem shows only the second image when i run my program!

please help

ImageIcon ii = new ImageIcon("mini_map.png");
JLabel label1=new JLabel(ii);

Icon icon = new ImageIcon("Mg.gif");
JLabel label2 = new JLabel(icon);

JScrollPane jsp=new JScrollPane();

jsp.getViewport().add(label1);
jsp.getViewport().add(label2 );

回答1:


JViewport is a single-child container, you can't add two components.

To achieve an overlap (that is stack components in z-direction) in any container, you'r mostly on your own, the built-in support is poor. Either have to manage them in LayeredPane (as mentioned already) or try OverlapLayout




回答2:


If you want to have components on top of each other use a layered pane.




回答3:


Put both labels in the same panel and add it to the JScrollPane:

ImageIcon ii = new ImageIcon("mini_map.png");
JLabel label1=new JLabel(ii);

Icon icon = new ImageIcon("Mg.gif");
JLabel label2 = new JLabel(icon);

JPanel pContainer = new JPanel();
pContainer.add(label1);
pContainer.add(label2);
JScrollPane jsp=new JScrollPane(pContainer);



回答4:


This is how I would do it for your particular problem.

Since you say you have one image which serves the role of a background, thus I would override paintComponent() like in BackgroundPanel below. This way you have a panel which serves as a background only. To it you can add any type of component, in your case a JLabel with an ImageIcon.

This way you have an effect of one being over another and you are still able to use layout manager to control where your components are.

If your problem is more complex or you want to generally set Components one over another then do as all are saying here ---> use JLayeredPane. Note that if you use JLayeredPane sadly layout managers will not help you since it doesn't respects them. You will have to proceed similarly to a situation when you use a null manager, i.e. setBounds() for components.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class PaintInScroll
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    Image backgroundImage = new ImageIcon(new URL(
                            "http://www.jvsearch.com/adidocs7_images/JAVAORANGE.JPG")).getImage();
                    BackgroundPanel bP = new BackgroundPanel(backgroundImage);
                    bP.setLayout(new BorderLayout());
                    bP.setPreferredSize(new Dimension(500, 500));
                    JLabel label = new JLabel(new ImageIcon(new URL(
                            "https://blogs.oracle.com/theplanetarium/resource/thumb-java-duke-guitar.png")));
                    bP.add(label, BorderLayout.CENTER);
                    JScrollPane scrollPane = new JScrollPane(bP);
                    scrollPane.setPreferredSize(new Dimension(300, 400));
                    JPanel contentPane = new JPanel();
                    contentPane.add(scrollPane);
                    JFrame f = new JFrame();
                    f.setContentPane(contentPane);
                    f.setSize(800, 600);
                    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    f.setVisible(true);
                }catch(MalformedURLException ex)
                {
                    Logger.getLogger(PaintInScroll.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
}

class BackgroundPanel extends JPanel
{
    private Image image;

    public BackgroundPanel(Image image)
    {
        this.image = image;
    }
    private static final long serialVersionUID = 1L;

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
    }
}

NOTE: Images are URLs thus i-net connection is required to run the example.

EDIT1: Example showing how to use JLayeredPane with use of layout managers for each layer.

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class PaintInScrollRespectingLayoutManagers extends JPanel
{
    private static final long serialVersionUID = 1L;
    private JLayeredPane layeredPane;
    private JLabel imageContainer = new JLabel();
    private JButton infoB = new JButton("i");
    private JScrollPane scrollPane;

    public PaintInScrollRespectingLayoutManagers(ImageIcon image)
    {
        super();
        this.imageContainer.setIcon(image);
        scrollPane = new JScrollPane(imageContainer);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setPreferredSize(new Dimension(125, 90));
        JPanel iSPP = new JPanel();//image scroll pane panel
        iSPP.setOpaque(false);
        iSPP.add(scrollPane);
        JPanel iBP = new JPanel();//info button panel
        iBP.setOpaque(false);
        iBP.add(infoB);
        this.layeredPane = new JLayeredPane();
        layeredPane.add(iSPP, new Integer(50));
        layeredPane.add(iBP, new Integer(100));
        this.setLayout(new BorderLayout());
        this.add(layeredPane, BorderLayout.CENTER);
        this.add(new JButton("A button"), BorderLayout.SOUTH);
        layeredPane.addComponentListener(layeredPaneCL);
        setPreferredSize(new Dimension(300, 300));
    }
    private ComponentListener layeredPaneCL = new ComponentAdapter()
    {
        @Override
        public void componentResized(ComponentEvent e)
        {
            super.componentResized(e);
            System.out.println("componentResized");
            for(Component c : layeredPane.getComponents())
                c.setSize(layeredPane.getSize());
        }
    };

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    JFrame frame = new JFrame();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new PaintInScrollRespectingLayoutManagers(new ImageIcon(new URL(
                            "http://www.prodeveloper.org/wp-content/uploads/2008/10/stackoverflow-logo-250.png"))));
                    frame.pack();
                    frame.setVisible(true);
                }catch(MalformedURLException ex)
                {
                    Logger.getLogger(PaintInScrollRespectingLayoutManagers.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
}

NOTE 2: The only reason that the scroll panes have setPrefferedSize is so you can see the scrollbars. Otherwise do not use it let the layout take care of controlling scroll pane.



来源:https://stackoverflow.com/questions/5840075/java-jscrollpane-multiple-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!