JSplitPane 前面的 JLabel

JLabel in front of JSplitPane

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

如何使用 JLayerHow to Decorate Components with the JLayer Class (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)

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);
    });
  }
}

考虑到您的描述,我更喜欢使用 paintComponent 方法。您只需在组件的背景上绘制 2 个矩形,然后像往常一样定位组件,就这么简单:

  JFrame f = new JFrame();
  f.setPreferredSize(new Dimension(600, 600));
  f.pack();
  f.setLayout(new BorderLayout());
  JPanel p = new JPanel(new FlowLayout()) {
     @Override
     protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        int perc = (int)((float)getWidth()*0.3f); // set % to fill
        g.setColor(Color.RED);
        g.fillRect(0, 0, perc, g.getClipBounds().height);
        g.setColor(Color.BLUE);
        g.fillRect(perc, 0, getWidth()-perc, getHeight());
     }

  };
  f.add(p);
  p.add(new JButton("test"));
  f.setVisible(true);

我的示例是在 JPanel 上完成的,但它可以直接在 JFrame 上完成,然后使用 FlowLayout 在其上放置 JButton。这是结果: