Java Swing报错cannot find symbol method getRootPane()如何解决
问题根因
你遇到的报错和导入语句无关,核心是getRootPane()方法调用主体错误:
getRootPane()是JFrame类的实例方法,必须通过你创建的JFrame实例对象调用- 你在静态main方法中直接裸写
getRootPane(),Java会尝试查找当前gui类下的同名方法,但gui类没有定义该方法,因此触发报错。
修正方案
- 修改边框设置的代码行,明确指定调用
frame对象的getRootPane()方法:// 原错误写法 // getRootPane().setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.RED)); // 修正后写法 frame.getRootPane().setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.RED)); - 可选优化:
JFrame提供了专门的菜单栏设置方法,不需要手动把菜单栏添加到内容面板的NORTH位置,避免跨平台显示异常:- 删除原有代码
frame.getContentPane().add(BorderLayout.NORTH, mb); - 在添加组件的代码段补充
frame.setJMenuBar(mb);
- 删除原有代码
修正后完整可运行代码
package com.company; import java.awt.*; import javax.swing.*; class gui{ public static void main(String[] args){ //Create the window/frame JFrame frame = new JFrame("Text Editor"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(600,600); // 修正边框调用 frame.getRootPane().setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.RED)); //Creating the MenuBar and adding components JMenuBar mb = new JMenuBar(); JMenu m1 = new JMenu("File"); JMenu m2 = new JMenu("Help"); mb.add(m1); mb.add(m2); JMenuItem m11 = new JMenuItem("Open"); JMenuItem m12 = new JMenuItem("Save as"); m1.add(m11); m1.add(m12); JMenuItem m21 = new JMenuItem("Wiki"); JMenuItem m22 = new JMenuItem("More..."); m2.add(m21); m2.add(m22); // 标准方式设置菜单栏 frame.setJMenuBar(mb); //Create the panel and the contents JPanel panel1 = new JPanel(); JButton button = new JButton("Something I can put here"); panel1.add(button); //Creates a Text Area JTextArea ta = new JTextArea(); //Add contents to the window/frame frame.getContentPane().add(BorderLayout.SOUTH, panel1); frame.getContentPane().add(BorderLayout.CENTER, ta); frame.setVisible(true); } } public class Main { public static void main(String[] args) { gui.main(args); } }
内容的提问来源于stack exchange,提问作者Jai Sloper
相关产品推荐
相关产品推荐

