如何将 JMenuBar 添加到 JTextArea?

我有一个JTextArea,我想JMenuBar在其中添加一个,但似乎不起作用。


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.

有什么办法可以添加JMenuBar吗JTextArea?


达令说
浏览 72回答 1
1回答

噜噜哒

将 JTextArea 放入 JScrollPane ——始终将 JScrollPane 添加到使用 BorderLayout 的 JPanel 的 BorderLayout.CENTER 位置使用 JPanel 将 JMenuBar 添加到同一 BorderLayout 的 BorderLayout.PAGE_START 位置完毕例如。,JTextArea ta = new JTextArea(40, 20); // give columns and rowsJScrollPane 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 hereborderLayoutPanel.add(menuBar, BorderLayout.PAGE_START);旁注:您调用的代码ta.getWidth()可能会返回宽度值 0,因为它似乎是在呈现 JTextArea之前调用的。您几乎永远不想将组件直接添加到 JTextArea 本身,因为这可能会干扰文本区域的功能。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java