2013-10-06 4 views
3

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

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; 
} 
+0

'frame.show()' Не игнорировать предупреждения устаревания. –

+0

+1 для [sscce] (http://sscce.org/). – trashgod

ответ

4

Один подход заключается в nestColorAction как внутреннего класса в ButtonPanel, где она имеет неявный доступ к панели вмещающей.

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

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

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

image

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; 
    } 
} 
+0

См. Также [§15.8.4. Квалифицировано это] (http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.8.4). - Это комментарий, отправленный на (теперь удаленный) ответ, который был единственной частью, которую стоит повторить. –

+0

@AndrewThompson: Я откладываю вам, но я нашел ваш аргумент для ясности, чтобы быть убедительным, если вы восстановите свой ответ. – trashgod

+0

Основная часть ответа была неправильной для этого вопроса (с учетом структуры кода). Если бы я воскресил любую его часть, это было бы только как комментарий. –

2

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

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

изменить Также в выглядеть и чувствовать себя может помочь:

//UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); 
Смежные вопросы