java - 如何将 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
?
解决方案
- 将 JTextArea 放入 JScrollPane - 总是
- 将 JScrollPane 添加到使用 BorderLayout 的 JPanel 的 BorderLayout.CENTER 位置
- 使用 JPanel 将 JMenuBar 添加到相同 BorderLayout 的 BorderLayout.PAGE_START 位置
完毕
例如,
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);
旁注:
- 您调用的代码
ta.getWidth()
可能返回 0 的宽度值,因为它似乎是在呈现 JTextArea之前调用的。 - 您几乎不想将组件直接添加到 JTextArea 本身,因为这可能会干扰文本区域的功能。
推荐阅读
- reactjs - 尝试使用 react-bootstrap 包创建带有下拉菜单的侧边栏
- node.js - 如何使用 javascript neo4j 驱动程序处理死锁?
- .net - 在 WinForms 中托管应用程序时 WPF Telerik 控件消失
- go - 使用 Error.Is 函数比较动态错误消息
- python - Python中的狄拉克三角洲和FFT
- airflow-scheduler - 一段时间后,Apache Airflow 调度程序未运行
- javascript - 移动设备上带有 html2canvas 的画布视口
- google-cloud-automl - 将 AutoML 翻译的自定义模型迁移到另一个 GCP 项目
- microsoft-graph-api - 图形 API 端点以列出抛出 401 Forbidden 错误的托管设备
- java - 如何使用高效的 Java 流将 Map 转换为 CSV?