Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 213
  • Last Modified:

Set two toolbars

How can I put two JToolBar in a frame? The following code puts only one toolbar.

import java.awt.*;
import javax.swing.*;

public class Test2
{

    public static void main(String[] args)
    {
     TestFrame frame=new TestFrame();
     frame.show();
    }

}

class TestFrame extends JFrame
{

    TestFrame()
    {
     setSize(300, 300);
     JToolBar toolBar1= new JToolBar();
     toolBar1.add(new JButton("Test1"));
     
          JToolBar toolBar2= new JToolBar();
     toolBar2.add(new JButton("Test2"));
     
     Container contentPane = getContentPane();
     contentPane.add(toolBar1, BorderLayout.NORTH);
          contentPane.add(toolBar2, BorderLayout.NORTH);
    }


}
0
asukai
Asked:
asukai
  • 2
1 Solution
 
girionisCommented:
 This is because you try to add them both at the NORTH location so the second overlaps the first. Change this line:

  contentPane.add(toolBar2, BorderLayout.NORTH);

  to

  contentPane.add(toolBar2, BorderLayout.SOUTH);

  and you will see them both.
0
 
asukaiAuthor Commented:
Yes, but this will display the second toolbar to the bottom of the frame. How can I display the second toolbar just below the first one?
0
 
girionisCommented:
 You have to change the layout then. Try using GridLayout instead and add it to a panel. Then add the panel to the North of he frame:

TestFrame()
     {
          setSize(300, 300);
          JToolBar toolBar1= new JToolBar();
          toolBar1.add(new JButton("Test1"));

          JToolBar toolBar2= new JToolBar();
          toolBar2.add(new JButton("Test2"));
          Container contentPane = getContentPane();
          JPanel panel = new JPanel();
          panel.setLayout(new GridLayout(2, 0));
          panel.add(toolBar1);
          panel.add(toolBar2);
          contentPane.add(panel, BorderLayout.NORTH);
         
     }
0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now