Цвет фона не будет меняться на панели

Следующий код создает окно с кнопками, но появляется сообщение об ошибке, когда я запускаю i и фактически нажимаю кнопку. Согласно подсказке Spring:

Cannot make a static reference to the non-static method setBackground(Color) from the type JComponent

Насколько я могу судить, эта программа буквально вводится из моей строки учебника Java. Это старая книга, так что может быть несовместимость, но это маловероятно.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonTest
{
    public static void main(String[] args)
    {
        final ButtonFrame frame = new ButtonFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.show();
}
}

class ButtonFrame extends JFrame
{
    public ButtonFrame()
    {
    setTitle("Button Test");
    setSize(Default_width, Default_height);

        //panel
        ButtonPanel panel = new ButtonPanel();
        Container contentPane=getContentPane();
        contentPane.add(panel);
    }

    public static final int Default_width = 300;
public static final int Default_height = 200;
}

class ButtonPanel extends JPanel
{
public ButtonPanel()
{
    JButton yellowButton = new JButton("Yellow");
    JButton blueButton = new JButton("Blue");
    JButton redButton = new JButton("Red");

    add(yellowButton);
    add(blueButton);
    add(redButton);

    ColorAction yellowAction= new ColorAction(Color.YELLOW);
    ColorAction redAction = new ColorAction(Color.RED);
    ColorAction blueAction = new ColorAction(Color.BLUE);

    yellowButton.addActionListener(yellowAction);
    blueButton.addActionListener(blueAction);
    redButton.addActionListener(redAction);
    }
}

    class ColorAction implements ActionListener
    {
        public ColorAction(Color c)
    {
        backgroundColor=c;
    }

    public void actionPerformed(ActionEvent event)
    {
    ButtonPanel.setBackground(backgroundColor);
    }

        private Color backgroundColor;
}

3 ответа

Решение

Один из подходов - гнездиться ColorAction как внутренний класс в ButtonPanel где он имеет неявный доступ к ограждающей панели.

Приложение: Как отмечается в комментариях @Andrew Thompson и @nachokk, неявная доступность может быть сделана явной путем квалификации this используя имя включающего класса. См. JLS §15.8.4. квалифицированный this для деталей. В этом примере эти два вызова эквивалентны:

 setBackground(backgroundColor);
 ButtonPanel.this.setBackground(backgroundColor);

В качестве более общей альтернативы рассмотрите возможность инкапсуляции целевой панели и цвета в Action, как изложено здесь.

образ

class ButtonPanel extends JPanel {

    public ButtonPanel() {
        JButton yellowButton = new JButton("Yellow");
        JButton blueButton = new JButton("Blue");
        JButton redButton = new JButton("Red");

        add(yellowButton);
        add(blueButton);
        add(redButton);

        ColorAction yellowAction = new ColorAction(Color.YELLOW);
        ColorAction redAction = new ColorAction(Color.RED);
        ColorAction blueAction = new ColorAction(Color.BLUE);

        yellowButton.addActionListener(yellowAction);
        blueButton.addActionListener(blueAction);
        redButton.addActionListener(redAction);
    }

    private class ColorAction implements ActionListener {

        public ColorAction(Color c) {
            backgroundColor = c;
        }

         @Override
         public void actionPerformed(ActionEvent event) {
            setBackground(backgroundColor);
        }
        private Color backgroundColor;
    }
}

ButtonPanel.setBackground() не является статическим методом, поэтому его нельзя вызывать как единое целое. Вам нужен конкретный экземпляр ButtonPanel для установки фона.

ButtonPanel bp = new ButtonPanel();
bp.setBackground(backgroundColor);

Также может помочь изменение внешнего вида:

//UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
Другие вопросы по тегам