Использование производного класса элемента управления Java Swing для создания слушателя для себя - PullRequest
2 голосов
/ 23 июля 2011

С самого начала: я знаю, что я занимаюсь плохим дизайном.Я пытаюсь сделать это, чтобы лучше понять Java - что возможно, что нет и почему?

Я написал следующий код:

    import java.awt.*;
    import java.awt.event.*;

    import javax.swing.*;

    public class ButtonTest
    {
        public static void main(String[] args)
        {
            EventQueue.invokeLater(new Runnable()
            {
                @Override
                public void run()
                {
                    ButtonFrame frame = new ButtonFrame();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setVisible(true);
                }
            });
        }
    }

    @SuppressWarnings("serial")
    class ButtonFrame extends JFrame
    {
        private final static int DEFAULT_WIDTH = 300;
        private final static int DEFAULT_HEIGHT = 200;
        private final JPanel buttonPanel;

        public ButtonFrame()
        {
            this.setTitle("Button Frame");
            this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

            PanelButton yellowButton = new PanelButton("Yellow", Color.YELLOW, this);
            PanelButton redButton = new PanelButton("Red", Color.RED, this);
            PanelButton blueButton = new PanelButton("Blue", Color.BLUE, this);

            this.buttonPanel = new JPanel();
            this.buttonPanel.add(yellowButton);
            this.buttonPanel.add(redButton);
            this.buttonPanel.add(blueButton);

            // add panel to frame
            this.add(this.buttonPanel);
        }
    }

    @SuppressWarnings("serial")
    class PanelButton extends JButton implements ActionListener
    {
        private final Color buttonColor;
        private final ButtonFrame containingFrame;

        public PanelButton(String title, Color buttonColor,
                ButtonFrame containingFrame)
        {
            super(title);
            this.buttonColor = buttonColor;
            this.containingFrame = containingFrame;
            this.addActionListener(this);
        }

        @Override
        public void actionPerformed(ActionEvent event)
        {
            this.containingFrame.setBackground(this.buttonColor);
        }
    }

Но это не работает.Из отладчика я вижу, что actionPerformed() вызывается и имеет ожидаемые значения.Я не могу понять, что здесь происходит.Может кто-нибудь помочь мне?

Ответы [ 2 ]

4 голосов
/ 23 июля 2011

Вы устанавливаете цвет фона JFrame, но JPanel, содержащийся в JFrame, который затем удерживает ваши кнопки, занимает все пространство JFrame, так что цвет фона не меняется.

Это работает.

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ButtonTest
{
    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                ButtonFrame frame = new ButtonFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

@SuppressWarnings("serial")
class ButtonFrame extends JFrame
{
    private final static int DEFAULT_WIDTH = 300;
    private final static int DEFAULT_HEIGHT = 200;
    private final JPanel buttonPanel;

    public ButtonFrame()
    {
        this.setTitle("Button Frame");
        this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

        this.buttonPanel = new JPanel();

        PanelButton yellowButton = new PanelButton("Yellow", Color.YELLOW, buttonPanel);
        PanelButton redButton = new PanelButton("Red", Color.RED, buttonPanel);
        PanelButton blueButton = new PanelButton("Blue", Color.BLUE, buttonPanel);

        this.buttonPanel.add(yellowButton);
        this.buttonPanel.add(redButton);
        this.buttonPanel.add(blueButton);

        // add panel to frame
        this.add(this.buttonPanel);
    }
}

@SuppressWarnings("serial")
class PanelButton extends JButton implements ActionListener
{
    private final Color buttonColor;
    private final JPanel buttonPanel;

    public PanelButton(String title, Color buttonColor,
            JPanel buttonPanel)
    {
        super(title);
        this.buttonColor = buttonColor;
        this.buttonPanel = buttonPanel;
        this.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent event)
    {
        buttonPanel.setBackground(this.buttonColor);
    }
}
3 голосов
/ 23 июля 2011

Вы можете пропустить прохождение контейнера и просто сделать

@Override
public void actionPerformed(ActionEvent event)
{
    this.getParent().setBackground(buttonColor);
}
...