如何在 Java 中设置方向并沿 x 轴分割组件?

java 8object oriented programmingprogramming更新于 2025/9/13 3:24:17

首先,我们创建要分割的组件。这里,我们有两个标签 −

JComponent one = new JLabel("Label One");
one.setBorder(BorderFactory.createLineBorder(Color.red));
JComponent two = new JLabel("Label Two");
two.setBorder(BorderFactory.createLineBorder(Color.blue));

现在,设置方向并使用 HORIZONTAL_SPLIT 沿 x 轴分割 −

JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
split.setLeftComponent(one);
split.setRightComponent(two);

以下是在 Java 中设置方向并沿 x 轴分割组件的示例 −

示例

package my;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSplitPane;
public class SwingDemo {
   public static void main(String[] a) {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JComponent one = new JLabel("Label One");
      one.setBorder(BorderFactory.createLineBorder(Color.red));
      JComponent two = new JLabel("Label Two");
      two.setBorder(BorderFactory.createLineBorder(Color.blue));
      JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
      split.setLeftComponent(one);
      split.setRightComponent(two);
      frame.add(split, BorderLayout.NORTH);
      frame.setSize(550, 250);
      frame.setVisible(true);
   }
}

这将产生以下输出 −


相关文章