【问题标题】:Add 3 panels to a frame in java with JSplitPane?使用 JSplitPane 将 3 个面板添加到 java 中的框架?
【发布时间】:2015-03-28 17:25:56
【问题描述】:

尝试使用 JSplitPane 将我创建的 3 个面板添加到 Java 框架中。用 2 个面板尝试过这个,效果很好,但是用 3 个它仍然不能满足我的要求。

已经阅读了一些关于制作 2 个 JSplitPanes 并将一个放在另一个中的内容,但这实际上并不能达到我想要的效果。

我的代码显示有3个面板,但是大小都错了..应该填写。

我的代码:

    frame = new JFrame(); // Create a new frame
    frame.setVisible(true); // Makes it visible     
    frame.setSize(900, 500); // Sets size         
    frame.setTitle(""); // Sets title
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null); // Sets the window on the center of the screen   

    temp_panel = new JPanel(); // Creates new JPanel
    water_panel = new JPanel(); // Creates new JPanel
    power_panel = new JPanel(); // Creates new JPanel

    temp_panel.setBackground(Color.decode("#2ecc71")); // Sets color
    water_panel.setBackground(Color.decode("#3498db")); // Sets color
    power_panel.setBackground(Color.decode("#f1c40f")); // Sets color

    temp_label = new JLabel("This is Temperature");
    water_label = new JLabel("This is Water consumption");
    power_label = new JLabel("This is Power consumption");

    // Add labels on panel
    temp_panel.add(temp_label);
    water_panel.add(water_label);
    power_panel.add(power_label); 

    JSplitPane splitPaneLeft = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    JSplitPane splitPaneRight = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    splitPaneLeft.setLeftComponent( temp_panel );
    splitPaneLeft.setRightComponent( water_panel );
    splitPaneRight.setLeftComponent( splitPaneLeft );
    splitPaneRight.setRightComponent( power_panel );

    splitPaneLeft.setEnabled(false);
    splitPaneLeft.setDividerSize(0);

    splitPaneRight.setEnabled(false);
    splitPaneRight.setDividerSize(0);

    // put splitPaneRight onto a single panel
    JPanel panelSplit = new JPanel();
    panelSplit.add( splitPaneRight );

    frame.add(panelSplit, BorderLayout.CENTER);

它应该看起来像这样,但只有 3 个具有 3 种不同颜色的面板,而不是 2 个!

希望有人能帮忙

【问题讨论】:

  • 为什么选择 JSplitPane?为什么不将您的 3 个 JPanel 放入另一个使用 GridLayout 的 JPanel 中呢?是否有需要使用 JSplitPane 的特定原因?
  • 不知道你能做到这一点……马上试试。谢谢

标签: java swing jframe jpanel jsplitpane


【解决方案1】:

如果您不需要在运行时更改组件的相对大小,请不要使用 JSplitPane。而是创建一个使用 GridLayout 的容器 JPanel,例如 new GridLayout(1, 0) 用于 1 行和可变数量的列,将您的三个彩色 JPanel 添加到使用 GridLayout 的 JPanel,然后将其添加到 JFrame。

【讨论】:

  • 相对尺寸是什么意思...我的程序会改变,但只有标签会随着时间而改变。
  • 它现在可以工作了.. 我制作了另一个面板并在该面板上使用了 GridLayout,现在我得到了 3 行 :) thx man
【解决方案2】:

您可以将其中一个面板制作成另一个 JSplitPane,遗憾的是没有其他解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    相关资源
    最近更新 更多