java如何在ImageIcon前面移动JLabel?
我认为代码中的所有内容都是正确的,我只需要知道如何分类不同的层
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.KeyStroke;
class FullSceenToggleAction extends AbstractAction {
private JFrame frame;
private GraphicsDevice fullscreenDevice;
public FullSceenToggleAction(JFrame frame) {
this(frame, GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice());
}
public FullSceenToggleAction(JFrame frame, GraphicsDevice fullscreenDevice) {
this.frame = frame;
this.fullscreenDevice = fullscreenDevice;
}
@Override
public void actionPerformed(ActionEvent e) {
frame.dispose();
if (frame.isUndecorated()) {
fullscreenDevice.setFullScreenWindow(null);
frame.setUndecorated(false);
} else {
frame.setUndecorated(true);
fullscreenDevice.setFullScreenWindow(frame);
}
frame.setVisible(true);
frame.repaint();
}
}
public class Main {
public static final void addKeyBinding(JComponent c, String key, final Action action) {
c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(key), key);
c.getActionMap().put(key, action);
c.setFocusable(true);
}
public static void main(String[] args) {
final JFrame frame = new JFrame("Fullscreen Toggle Test");
Container contentPane = frame.getContentPane();
contentPane.add(new JLabel("Hey"), BorderLayout.CENTER);
frame.add(new JLabel(new ImageIcon("C:/Users/SamBr/Pictures/DesktopBackgrounds/image.png")));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(960, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setTitle("Virtual World");
addKeyBinding(frame.getRootPane(), "F11", new FullSceenToggleAction(frame));
}
}
当我运行代码时,我看到了图像,但在图像前面或屏幕上的任何地方都没有文本“嘿”,我不明白为什么它没有显示,或者我如何使它在图像前面可见
# 1 楼答案
谁知道你到底想做什么
但以下是一些根据您的要求在不同位置显示标签上文本的示例:
简单的解决方案只是使用一个带有图标和文本的标签。其他人使用其他组件并利用布局管理器
# 2 楼答案
我在之前告诉过你原因,你在contentPane中添加了两个组件,第二个组件取代了第一个组件
请注意,这两行代码向JFrame的contentPane容器添加了一个组件:
因为根据the JFrame API:
此外,contentPane默认情况下使用BorderLayout,如果添加的组件不使用第二个参数常量,则默认情况下会将组件添加到BorderLayout中。中心位置
如果希望两者都显示,则