gpt4 book ai didi

java - JGraphX 正在破坏 Swing 组件的界限

转载 作者:行者123 更新时间:2023-12-02 10:35:49 24 4
gpt4 key购买 nike

我正在尝试实现一些自己编写的 GUI 元素(如 Java-swing 按钮)和 JGraphX 之间的交互。为了做到这一点,我首先只想在 JGraph-Element 旁边显示一个按钮 - 但我被卡住了。

我的显示按钮本身的代码工作正常:

import javax.swing.*;    

public class HelloWorld extends JFrame {

public HelloWorld()
{
super("Everything works");
}

public static void main(String[] args)
{
hello_world frame = new hello_world();
frame.setTitle("bub");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);

button.setBounds(10, 10, 100, 50);

frame.setVisible(true);

frame.add(button);
}
}

This is the Button as it is supposed to be shown

但是一旦我添加 JGraph 组件,按钮就会全屏显示。我不知道为什么以及如何防止这种情况。我的代码:

import javax.swing.*;

import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.view.mxGraph;

public class HelloWorld extends JFrame {

private mxGraph graph;
private Object window;

public HelloWorld()
{
super("Nothing works");

graph = new mxGraph();
window = graph.getDefaultParent();

graph.getModel().beginUpdate();

try
{
Object v2 = graph.insertVertex(window, null, "Hello World!", 200, 150, 80, 30);

}
finally
{
graph.getModel().endUpdate();
}

mxGraphComponent graphComponent = new mxGraphComponent(graph);
getContentPane().add(graphComponent);
}

public static void main(String[] args)
{
hello_world frame = new hello_world();


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);

JButton button = new JButton("left");
button.setBounds(10, 10, 100, 50);

frame.setVisible(true);

frame.add(button);
}

}

结果如下所示(我手动调整了窗口大小以向您显示按钮。当然,按钮只会填充 JGraph 组件后面的空间,因此将不可见):

This is the Button, filling up the whole screen.

最佳答案

Swing 使用布局管理器。 JFrame 的默认布局管理器是 BorderLayout。当您向框架添加组件时,使用的默认约束是BorderLayout.CENTER。只能将单个组件添加到 BorderLayoutCENTER 中。

setBounds(...) 只能暂时起作用。一旦调整框架大小,就会调用布局管理器,并且将根据布局管理器的规则为按钮指定新的大小/位置。

解决方案是正确使用布局管理器。我不确定您想要实现什么布局,所以我只能建议您阅读 Layout Managers 上的 Swing 教程。获取帮助您入门的工作示例。然后您可以使用不同的布局管理器嵌套面板以达到您想要的效果。

从一些简单的事情开始,例如:

frame.add(button, BorderLayout.PAGE_END);
frame.setVisible(true);
//frame.add(button);

上面将在框架中心显示您的图表,并在底部显示按钮。

关于java - JGraphX 正在破坏 Swing 组件的界限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53304408/

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