Search code examples
javaswingjtextareajmenu

How do I add JMenuBar to JTextArea?


I have a JTextArea, and I want to add a JMenuBar to it, but it doesn't seem to work.

ta = new JTextArea();
ta.setBackground(Color.RED);
// ta.setLayout(null); I tried with a null layout and 
                       non-null


pane = new JScrollPane(ta);
pane.setBounds(Main.WIDTH - (Main.WIDTH - 20), Main.HEIGHT - (Main.HEIGHT - 20), Main.WIDTH - 60, Main.HEIGHT - 500);

bar = new JMenuBar();
bar.setBounds(0, 0, ta.getWidth(), 20); // This won't be there if 
                                        // there is a non-null layout.
ta.add(bar); // I also tried pane.add(bar); that didn't work either.

Is there any way to add JMenuBar to JTextArea?


Solution

    1. Put the JTextArea into a JScrollPane -- always
    2. Add the JScrollPane to the BorderLayout.CENTER position of a JPanel that uses BorderLayout
    3. Add the JMenuBar to the BorderLayout.PAGE_START position of the same BorderLayout using JPanel

    Done

    e.g.,

    JTextArea ta = new JTextArea(40, 20); // give columns and rows
    JScrollPane scrollPane = new JScrollPane(ta);
    
    JPanel borderLayoutPanel = new JPanel(new BorderLayout());
    borderLayoutPanel.add(scrollPane, BorderLayout.CENTER);
    
    JMenuBar menuBar = new JMenuBar();
    // add menu's to the menu bar here
    
    borderLayoutPanel.add(menuBar, BorderLayout.PAGE_START);
    

    Side notes:

    • The code where you call, ta.getWidth() is likely returning a width value of 0, since it appears to be called before the JTextArea has been rendered.
    • You almost never want to add components directly to the JTextArea itself as that potentially interferes with the functioning of the text area.