滚动后JLabel消失 [英] JLabel disappears after scrolling
问题描述
我有一个包含ImageIcon
的滚动面板.我想添加JLabel
,其绝对位置以px为单位.我所拥有的:
I've got scroll panel which contains ImageIcon
. I want to add JLabel
with absolute position in px. What I've got:
代码:
public class HelloWorld {
HelloWorld() {
JFrame jfrm = new JFrame("Hello, World!");
jfrm.setSize(640, 480);
JPanel mapPanel = new JPanel();
mapPanel.setLayout(null);
mapPanel.setSize(600,400);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon imageIcon = new ImageIcon("src\\SwingExp\\img\\map.gif");
JScrollPane scrollPane = new JScrollPane(new JLabel(imageIcon));
scrollPane.setBounds(5,5,600,400);
JLabel usaLabel = new JLabel("U.S.A.");
usaLabel.setBounds(210,200,50,25);
mapPanel.add(usaLabel);
mapPanel.add(scrollPane);
jfrm.add(mapPanel);
jfrm.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new HelloWorld();
}
});
}
}
但是,如果我稍微滚动一下,美国标签将从地图上消失:
But if I'll scroll a little, USA label will disappear from map:
JLabel
位置必须是绝对位置.如何避免这种情况?
JLabel
positions must be absolute, as you see. How to avoid this?
推荐答案
将usaLabel
添加到包含图标而不是滚动窗格的标签中:
Add the usaLabel
to the label containing the icon, not the scrollpane:
ImageIcon imageIcon = new ImageIcon("src\\SwingExp\\img\\map.gif");
JLabel map = new JLabel( imageIcon );
JScrollPane scrollPane = new JScrollPane( map );
//JScrollPane scrollPane = new JScrollPane(new JLabel(imageIcon));
scrollPane.setBounds(5,5,600,400);
JLabel usaLabel = new JLabel("U.S.A.");
usaLabel.setBounds(210,200,50,25);
map.add( usaLabel );
//mapPanel.add(usaLabel);
也不要在任何地方使用null布局.不需要您的mapPanel变量.只需将滚动窗格直接添加到框架的内容窗格即可.默认情况下,滚动窗格将添加到CENTER,并将占用框架中的所有可用空间.
Also stop using a null layout everywhere. There is no need for your mapPanel variable. Just add the scrollpane directly to the content pane of the frame. By default the scrollpane will be added to the CENTER and will take up all the space available in the frame.
这篇关于滚动后JLabel消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!