Как сохранить выбранный JRadioButton из ButtonGroup?

Моя программа пытается сохранить состояние ButtonGroup, чтобы его можно было записать в файл в конце программы или восстановить кнопки, если пользователь выбирает «Назад».

Я ранее нашел этот вопрос:

Как узнать, какой JRadioButton выбран из Группа кнопок

Однако мой код ниже приводит к ошибкам при компиляции, поскольку ButtonGroup не распознается при использовании в методе ActionPerformed.

    import javax.swing.*;
    import java.awt.FlowLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.util.Enumeration;

    public class GraphicalInterface implements ActionListener
    {
        private static String[] tweetList =
        {"/Users/Chris/Desktop/Code/Tweets/One.jpg", "/Users/Chris/Desktop/Code/Tweets/Two.jpg", "/Users/Chris/Desktop/Code/Tweets/Three.jpg",
        "/Users/Chris/Desktop/Code/Tweets/Four.jpg", "/Users/Chris/Desktop/Code/Tweets/Five.jpg", "/Users/Chris/Desktop/Code/Tweets/Six.jpg",
        "/Users/Chris/Desktop/Code/Tweets/Seven.jpg", "/Users/Chris/Desktop/Code/Tweets/Eight.jpg"};

        private int[] answers = {4, 4, 4, 4, 4, 4, 4, 4};
        private int currentTweet = 0;

        JFrame surveyFrame = new JFrame("User Survey");
        JPanel surveyPanel = new JPanel(new FlowLayout());

        JButton buttonBack = new JButton("Back");
        JButton buttonNext = new JButton("Next");
        JButton buttonFinish = new JButton("Finish");

        JRadioButton cred1 = new JRadioButton("Extrememly Credible");
        JRadioButton cred2 = new JRadioButton("Credible");
        JRadioButton cred3 = new JRadioButton("Somewhat Credible");
        JRadioButton cred4 = new JRadioButton("Undecided");
        JRadioButton cred5 = new JRadioButton("Somewhat Incredible");
        JRadioButton cred6 = new JRadioButton("Incredible");
        JRadioButton cred7 = new JRadioButton("Extrememly Incredible");

        JLabel tweetLabel = new JLabel(new ImageIcon(tweetList[currentTweet]));

        public void Interface()
        {
            surveyFrame.setVisible(true);
            surveyFrame.setSize(500, 350);
            surveyFrame.add(surveyPanel);
            surveyFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            surveyPanel.add(tweetLabel);
            surveyPanel.add(buttonNext);
            surveyPanel.add(buttonBack);
            surveyPanel.add(buttonFinish);
            surveyPanel.add(cred1);
            surveyPanel.add(cred2);
            surveyPanel.add(cred3);
            surveyPanel.add(cred4);
            surveyPanel.add(cred5);
            surveyPanel.add(cred6);
            surveyPanel.add(cred7);
            cred4.setSelected(true);

            ButtonGroup tweetCredibility = new ButtonGroup();
            tweetCredibility.add(cred1);
            tweetCredibility.add(cred2);
            tweetCredibility.add(cred3);
            tweetCredibility.add(cred4);
            tweetCredibility.add(cred5);
            tweetCredibility.add(cred6);
            tweetCredibility.add(cred7);

            buttonNext.addActionListener(this);
            buttonBack.addActionListener(this);
            buttonFinish.addActionListener(this);
        }

        public void actionPerformed(ActionEvent input)
        {
            Object source = input.getSource();

            if (source == buttonNext)
            {
                if (currentTweet < tweetList.length-1)
                {
                    answers[currentTweet] = getCredRating(tweetCredibility);
                    currentTweet++;
                    ImageIcon nextTweet = new ImageIcon(tweetList[currentTweet]);
                    tweetLabel.setIcon(nextTweet);
                    // restore button from next image
                }
            }

            if (source == buttonBack)
            {
                if (currentTweet > 0)
                {
                    answers[currentTweet] = getCredRating(tweetCredibility);
                    currentTweet--;
                    ImageIcon nextTweet = new ImageIcon(tweetList[currentTweet]);
                    tweetLabel.setIcon(nextTweet);
                    // restore button from previous image
                }
            }

            if (source == buttonFinish)
            {
                // save answers to file
            }
        }

        public int getCredRating(ButtonGroup input)
        {
            int n = 1;
            for (Enumeration<AbstractButton> buttons = input.getElements(); buttons.hasMoreElements(); n++)
            {
                AbstractButton button = buttons.nextElement();
                if (button.isSelected())
                {
                    return n;
                }
            }
        }
    }

Complier: не удается найти переменную tweetCredibility

Есть идеи, почему это происходит?

Спасибо.


person CreditChris    schedule 09.04.2015    source источник
comment
tweetCredibility определяется как локальная переменная внутри метода Interface (), и вы пытаетесь получить доступ к ней снаружи, в каком-то другом методе, в данном случае это метод actionPerformed ( ... ), который фактически вызывает эту проблему.   -  person nIcE cOw    schedule 09.04.2015


Ответы (1)


ButtonGroup tweetCredibility = new ButtonGroup();

Вы определяете ButtonGroup как локальную переменную. То есть об этом знает только конструктор GraphicalInterface().

Вам нужно определить группу кнопок как переменную экземпляра, чтобы ее можно было использовать любым методом класса. Поэтому определите ButtonGroup, где вы определяете JRadioButtons.

Кроме того, оператор surveyFrame.setVisibe(true) следует вызывать как последний оператор конструктора ПОСЛЕ того, как все компоненты были добавлены в фрейм.

person camickr    schedule 09.04.2015