سؤال

I have tried several ways, but still havent found the solution. I have a jgraph in a frame and I want to add a Jbutton in that frame also in a specific location. However I only get one of them when i run the program, because they expand to the whole window. Any ideas how to fix this?

Thanks in advance.

public class GUIquery extends JFrame {

    JFrame frame;
    static JGraph jgraph;
    final mxGraph graph = new mxGraph();
    final mxGraphComponent graphComponent = new mxGraphComponent(graph);

    public GUIquery() {
        super("Test");
        GraphD();
        imgbtn();
    }

    public void GraphD() {
        Object parent = graph.getDefaultParent();
        graph.getModel().beginUpdate();
        try {
          ........         
        }catch  {
          ........  
        } finally  {
           graph.getModel().endUpdate();
        }
        getContentPane().add(graphComponent);    
    }    

    public void imgbtn() {
        JPanel jpanel = new JPanel();
        jpanel.setSize(100, 100);
        jpanel.setLocation(1200, 60);
        JButton imgbtn = new JButton("Export as Image");
        imgbtn.setSize(100, 100);
        imgbtn.setLocation(1200, 60);
        jpanel.add(imgbtn);
        add(jpanel);
    }

    public static void main(String[] args) {
        GUIquery frame = new GUIquery();
        frame.setLayout(null);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 320);
        frame.setVisible(true);
    }
}
هل كانت مفيدة؟

المحلول

Don't use null layouts. They inevitably result in trouble.

From your code snippet it is impossible to tell where you want them to be relative to each other, the following puts the button below the graph.

The content pane uses BorderLayout by default. For BorderLayout, you need to use place components at different positions:

// the default position, but it does not hurt to be explicit
add(graph, BorderLayout.CENTER);

...

// and the panel
add(jpanel, BorderLayout.SOUTH);

If the positioning is not what you want, take a look at the visual guide to layout managers to pick the layout manager that suits your needs best.

In the button panel the setLocation() and setSize() calls are useless. The layout manager of the panel is responsible for setting the button's bounds. If the default FlowLayout is not what you want for it, use the guide to pick another for the panel too.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top