gpt4 book ai didi

java - JLabel 位于 JSplitPane 前面

转载 作者:行者123 更新时间:2023-11-30 02:00:34 27 4
gpt4 key购买 nike

我的目标是有一个窗口,其中背景有 2 个不同颜色的面板。它们各自覆盖屏幕的特定百分比,并且会定期变化。我通过创建一个 JSplitPane 来做到这一点。但现在我想添加一个 JLabel 在屏幕中间的所有这些前面显示一些数据。我该怎么做?

最佳答案

使用JLayer怎么样:How to Decorate Components with the JLayer Class (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)

screenshot

import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.*;

public class JLayerTest {
public Component makeUI() {
JSplitPane splitPane = new JSplitPane();
splitPane.setResizeWeight(.4);
splitPane.setLeftComponent(makeLabel(Color.RED));
splitPane.setRightComponent(makeLabel(Color.GREEN));
//splitPane.setEnabled(false);
//splitPane.setDividerSize(0);

JPanel rubberStamp = new JPanel();
JLabel label = makeLabel(Color.BLUE);
label.setText("JLabel");
label.setForeground(Color.WHITE);
label.setBorder(BorderFactory.createLineBorder(Color.BLUE, 50));
LayerUI<JSplitPane> layerUI = new LayerUI<JSplitPane>() {
@Override public void paint(Graphics g, JComponent c) {
super.paint(g, c);
Dimension d = label.getPreferredSize();
int x = (c.getWidth() - d.width) / 2;
int y = (c.getHeight() - d.height) / 2;
SwingUtilities.paintComponent(g, label, rubberStamp, x, y, d.width, d.height);
}
};
return new JLayer<>(splitPane, layerUI);
}
public static JLabel makeLabel(Color color) {
JLabel label = new JLabel();
label.setOpaque(true);
label.setBackground(color);
return label;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new JLayerTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}

关于java - JLabel 位于 JSplitPane 前面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52989795/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com