I am trying to implement an interaction between some self-written GUI-Elements (like Java-swing Buttons) and JGraphX. In order to do that, I first just want to display a Button next to a JGraph-Element - and I'm stuck.
My code to display the Button itself works fine:
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);
}
}
But as soon as I am adding the JGraph-Component, the Button ist displayed fullscreen. I have no Idea why and how to prevent that. My Code:
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);
}
}
The result looks like this (I manually resized the window to show you the button. Naturally, the button would just fill the space behind the JGraph-Component and therefor would be invisible):
Swing uses layout managers. The default layout manager for a JFrame is the BorderLayout
. When you add a component to the frame the default constraint used is BorderLayout.CENTER
. Only a single component can be added to the CENTER
of the BorderLayout
.
The setBounds(...) will only work temporarily. As soon as the frame is resized the layout manager is invoked and the button will be given the new size/location based on the rules of the layout manager.
The solution is to use layout managers properly. I'm not sure what layout you are trying to achieve so all I can suggest is that you read the Swing tutorial on Layout Managers for working examples to get you started. Then you can nest panels with different layout managers to achieve your desired effect.
Start with something simple like:
frame.add(button, BorderLayout.PAGE_END);
frame.setVisible(true);
//frame.add(button);
The above will display your graph in the center of the frame and the button at the bottom.