简体   繁体   English

如何将JMenuBar添加到JTextArea?

[英]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. 我有一个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.

Is there any way to add JMenuBar to JTextArea ? 有什么方法可以将JMenuBar添加到JTextArea吗?

  1. Put the JTextArea into a JScrollPane -- always 将JTextArea放入JScrollPane中-始终
  2. Add the JScrollPane to the BorderLayout.CENTER position of a JPanel that uses BorderLayout 将JScrollPane添加到使用BorderLayout的JPanel的BorderLayout.CENTER位置
  3. Add the JMenuBar to the BorderLayout.PAGE_START position of the same BorderLayout using JPanel 使用JPanel将JMenuBar添加到同一BorderLayout的BorderLayout.PAGE_START位置

Done 完成

eg, 例如,

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. 您调用的代码ta.getWidth()可能返回宽度值0,因为它似乎在呈现JTextArea 之前被调用。
  • You almost never want to add components directly to the JTextArea itself as that potentially interferes with the functioning of the text area. 您几乎永远都不想直接将组件添加到JTextArea本身,因为这可能会干扰文本区域的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM