试图让两个按钮相互叠加

时间:2015-10-21 21:46:55

标签: java swing layout-manager

我想尝试一个顶部按钮和一个按钮按钮。但只有buttom按钮被绘制。 这是代码

    add(panel1,BorderLayout.NORTH); 
    add(panel2,BorderLayout.NORTH);

完整的功能

private void initUI() {

    /////////////////////////////////////////////////////////////////////////////
    //  set upui
    setTitle("Simple example");

    // Set size to match screen
    mWidth=(int)Toolkit.getDefaultToolkit().getScreenSize().getWidth()-50;
    mHeight=(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight()-50;
    setSize( mWidth, mHeight);
    setLocationRelativeTo(null);

    // Set close operation to exit
    setDefaultCloseOperation(EXIT_ON_CLOSE);


    JPanel panel1 =new JPanel();
    JButton btn = new JButton("Top Button"); // Button is a Component
    btn.addActionListener(this);
    panel1.add(btn); 

    JPanel panel2 =new JPanel();
    JButton btn2 = new JButton("Buttom Button"); // Button is a Component
    panel2.add(btn2); 

    add(panel1,BorderLayout.NORTH); 
    add(panel2,BorderLayout.NORTH); 
    // Add the chart
    // NOTE class DrawCompoment is defifin below where the drawing ooeration is overidden
    DrawComponent test = new DrawComponent();
    add(test,BorderLayout.CENTER);  

    ///////////////////////////////////////////////////////////////////////////////

    // sert up vscreen
    vStartX=(double)10;  
    vStartY=10;
    vWidth=mWidth-40;
    vHeight=mHeight-80;

    dx=vWidth/t.daySize;
    dy=vHeight/t.dayBiggest;

    // save fdata in spreads sheet
    createSpreadSheet();


}

1 个答案:

答案 0 :(得分:3)

您将panel1和panel2都添加到相同的BorderLayout位置,并且只能添加一个。您可能需要另一个JPanel来保存它们,然后将其添加到BorderLayout.NORTH点。

如,

JPanel panel1 = new JPanel();
JButton btn = new JButton("Top Button"); // Button is a Component
btn.addActionListener(this);
panel1.add(btn);

JPanel panel2 = new JPanel();
JButton btn2 = new JButton("Buttom Button"); // Button is a Component
panel2.add(btn2);

// A JPanel to hold both panel1 and panel2
JPanel containerPanel = new JPanel(new GridLayout(2, 1));
containerPanel.add(panel1);
containerPanel.add(panel2);

// add only one component to the BorderLayout.NORTH position of the JFrame
add(containerPanel, BorderLayout.NORTH);