Java 无法从类型组件对非静态方法setBackground(颜色)进行静态引用

Java 无法从类型组件对非静态方法setBackground(颜色)进行静态引用,java,eclipse,Java,Eclipse,我得到这个错误,不能用这段代码从类型组件静态引用非静态方法setBackground(Color) public class ColourChoice { private static JPanel myContentPane = new JPanel(); public static void main(String args[]) { Object[] colourchoice = {"Default", "Orange"};

我得到这个错误,不能用这段代码从类型组件静态引用非静态方法setBackground(Color)

    public class ColourChoice {
        private static JPanel myContentPane = new JPanel();
        public static void main(String args[]) {

            Object[] colourchoice = {"Default", "Orange"};   
            String UserInput = (String) JOptionPane.showInputDialog(null, "Please choose a colour","ColourChoice",JOptionPane.PLAIN_MESSAGE, null,colourchoice, "Default");
             if (UserInput.equals("Orange")) myContentPane.setBackground(Color.ORANGE);

            JFrame window = new JFrame();
            window.setVisible(true);
            window.setSize(100, 100);
            JPanel myContentPane = new JPanel();
            window.setContentPane(myContentPane);

     }
  }
我有一个JFrame,里面有一个JPanel,通过框架和面板加载,用户可以从下拉菜单中选择颜色,该菜单将在实际窗口加载之前出现,但是,当我为颜色“panel.setBackground(color.Orange);”编写代码时它给了我上述的错误

  • 首先,不要使用
    ==
    来比较字符串,而是使用
    .equals(…)
    方法。正如在本网站上讨论的那样,
    ==
    检查一个对象是否是一个对象,是否与另一个对象相同;它检查标识,而equals(或equalsIgnoreCase)方法检查字符串是否具有相同顺序的相同字符,这正是您感兴趣的
  • 接下来,确保您是在变量、实例上调用方法,而不是在类
    java.AWT.Panel
    上调用方法。请注意,变量名称应以小写字母开头。无论如何都要这样做,以避免混淆自己和他人
  • 此练习的关键是获取对要更改其背景颜色的JPanel的有效引用。应该将该对象分配给非静态类字段,以便其他方法可以获得该对象的句柄并对其调用方法

  • 编辑
    关于更新的代码,您的问题如下:

    // likely in some constructor or method
    Object[] colourchoice = {"Default", "Orange"};   
    String UserInput = (String) JOptionPane.showInputDialog(null, "Please choose a colour","ColourChoice",JOptionPane.PLAIN_MESSAGE, null,colourchoice, "Default");
    if (UserInput == "Orange") Panel.setBackground(Color.ORANGE);
    
    GUIDesign window = new GUIDesign();
    window.setVisible(true);
    window.setSize(100, 100);
    JPanel Panel = new JPanel();  // ***** here
    window.setContentPane(Panel);
    
    问题:

    • 不要将变量命名为“Panel”。同样,变量名应该以小写字母开头
    • 由于在方法或构造函数中声明此变量,这意味着*它仅在同一变量或构造函数中可见
    • 同样该变量应在类级别声明为非静态变量
    • 在得到建议后,您仍然使用
      ==
      比较字符串--为什么
    e、 g

    现在你可以在课堂的任何地方使用myContentPane


    编辑2
    例如

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.event.*;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class ColorBackground {
       private static final int PREF_W = 600;
       private static final int PREF_H = 450;
    
       // my main JPanel. I declare it in the class
       private JPanel mainPanel = new JPanel() {
          public Dimension getPreferredSize() {
             // so kleopatra doesn't down-vote me
             return ColorBackground.this.getPreferredSize();
          };
       };
       private JComboBox colorBox = new JComboBox(ColorChoices.values());
    
       public ColorBackground() {
          mainPanel.add(colorBox);
    
          colorBox.addActionListener(new ActionListener() {
    
             @Override
             public void actionPerformed(ActionEvent e) {
                ColorChoices choice = (ColorChoices) colorBox.getSelectedItem();
                mainPanel.setBackground(choice.getColor()); // now I can call methods on the field
             }
          });
       }
    
       public JComponent getMainPanel() {
          return mainPanel;
       }
    
       public Dimension getPreferredSize() {
          return new Dimension(PREF_W, PREF_H);
       }
    
       private static void createAndShowGui() {
          JFrame frame = new JFrame("Color Background");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(new ColorBackground().getMainPanel());
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    
    enum ColorChoices {
       DEFAULT("Default", null), ORANGE("Orange", Color.orange), BLUE("Blue",
             Color.blue), HOT_PINK("Hot Pink", new Color(255, 64, 128));
    
       public String getName() {
          return name;
       }
    
       @Override
       public String toString() {
          return name;
       }
    
       public Color getColor() {
          return color;
       }
    
       private ColorChoices(String name, Color color) {
          this.name = name;
          this.color = color;
       }
    
       private String name;
       private Color color;
    }
    

    编辑3
    关于您的最新代码更新:

    • 从main方法中获取所有代码
    • 创建一个真正的OOP投诉程序,其中包含构造函数、非静态字段和非静态方法
    • 在学习Swing之前先学习Java

    您正在对该方法进行静态引用。从面板中创建对象并调用setBackground。@CherryW:是的,所有状态更改方法都应该在方法、构造函数或其他代码块内部调用,而不是在类中自由调用,如果这是您所要求的,但这不是您出错的原因。原因是您试图对类而不是对象进行方法调用。@CherryW:正如我所说的,这不是您出错的原因。同样,您需要对引用对象的变量进行方法调用,而不是对类进行方法调用。@CherryW:再次,通过对对象调用方法
    setBackground(…)
    。你需要首先得到一个你想要设置背景的任何东西的参考,而我们无法帮助你获得你迄今为止分享的有限信息。如果您需要更多帮助,请向我们展示更多信息,特别是我们如何获得对保存您的GUI的JPanel的引用,该引用已添加到JFrame的contentPane中。@CherryW:关键是获得对要更改其背景颜色的JPanel的有效引用。此对象应分配给非静态类字段,以便其他方法可以获得该字段的句柄。对不起,我应该粘贴完整的代码,我以前粘贴的代码位于主类中,如果这对程序的运行方式有任何影响的话。
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.event.*;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class ColorBackground {
       private static final int PREF_W = 600;
       private static final int PREF_H = 450;
    
       // my main JPanel. I declare it in the class
       private JPanel mainPanel = new JPanel() {
          public Dimension getPreferredSize() {
             // so kleopatra doesn't down-vote me
             return ColorBackground.this.getPreferredSize();
          };
       };
       private JComboBox colorBox = new JComboBox(ColorChoices.values());
    
       public ColorBackground() {
          mainPanel.add(colorBox);
    
          colorBox.addActionListener(new ActionListener() {
    
             @Override
             public void actionPerformed(ActionEvent e) {
                ColorChoices choice = (ColorChoices) colorBox.getSelectedItem();
                mainPanel.setBackground(choice.getColor()); // now I can call methods on the field
             }
          });
       }
    
       public JComponent getMainPanel() {
          return mainPanel;
       }
    
       public Dimension getPreferredSize() {
          return new Dimension(PREF_W, PREF_H);
       }
    
       private static void createAndShowGui() {
          JFrame frame = new JFrame("Color Background");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(new ColorBackground().getMainPanel());
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    
    enum ColorChoices {
       DEFAULT("Default", null), ORANGE("Orange", Color.orange), BLUE("Blue",
             Color.blue), HOT_PINK("Hot Pink", new Color(255, 64, 128));
    
       public String getName() {
          return name;
       }
    
       @Override
       public String toString() {
          return name;
       }
    
       public Color getColor() {
          return color;
       }
    
       private ColorChoices(String name, Color color) {
          this.name = name;
          this.color = color;
       }
    
       private String name;
       private Color color;
    }