2014-03-26 2 views
-1

Я пытаюсь получить текст JLabel как случайный выбранный вопрос (или строку) из ArrayList, который я создал в отдельном классе.Настройка текста JLabel для случайной строки из ArrayList

Я попытался, как упомянуто другим пользователем этого кода, но он говорит, что не может решить MUSquestions

Question = new JLabel(); 
    getContentPane().add(Question); 
    Question.setText(MUSquestions.get(Math.random()*MUSquestions.size())); 
    Question.setBounds(38, 61, 383, 29); 

Код ArrayList является следующим

import java.util.*; 
public class Questions { 
public static void main(String[] args) { 
    ArrayList<String> SPOquestions = new ArrayList<String>(); // adding the sports questions for the quiz 

    SPOquestions.add("Who won the 2005 Formula One World Championship?"); 
    SPOquestions.add("Which team has the most Formula One Constructors titles?"); 
    SPOquestions.add("In what year did Roger Federer win his first 'Grand Slam'?"); 
    SPOquestions.add("How many 'Grand Slams' has Rafael Nadal won?"); 
    SPOquestions.add("Who has scored the most amount of goals in the Premier League?"); 
    SPOquestions.add("Who has won the most World Cups in football?"); 
    SPOquestions.add("How many MotoGP titles does Valentino Rossi hold?"); 
    SPOquestions.add("Who was the 2013 MotoGP champion?"); 
    SPOquestions.add("Who won the 2003 Rugby World Cup?"); 
    SPOquestions.add("In rugby league, how many points are awarded for a try?"); 
    SPOquestions.add("Who is the youngest ever snooker World Champion?"); 
    SPOquestions.add("In snooker, what is the highest maximum possible break?"); 
    SPOquestions.add("How many majors has Tiger Woods won?"); 
    SPOquestions.add("In golf, what is the tournament between the USA and Europe called?"); 
    SPOquestions.add("How many World Championships has darts player Phil Taylor won?"); 
    SPOquestions.add("What is the maximum possible amount of points a player can earn from throwing three darts?"); 
    SPOquestions.add("How many gold medals did Michael Phelps win at the 2008 Beijing Olympics?"); 
    SPOquestions.add("Who won the 2012 Olympic 100 metres mens race?"); 
    SPOquestions.add("Which of these events are not a part of the heptathlon?"); 
    SPOquestions.add("When was the first modern Olympics held?"); 


    ArrayList<String> MUSquestions = new ArrayList<String>(); // adding the music questions 

    MUSquestions.add("'Slash' was a member of which US rock band?"); 
    MUSquestions.add("Brian May was a member of which English rock band?"); 
    MUSquestions.add("What is the name of the music festival held annually in the town of Boom, Belgium?"); 
    MUSquestions.add("The rapper Tupac Shakuer '2Pac' died in which year?"); 
    MUSquestions.add("Which of these bands headlined the 2013 Glastonbury music festival?"); 
    MUSquestions.add("Which of these people designed the 'Les Paul' series of guitars?"); 
    MUSquestions.add("Keith Moon was a drummer for which English rock band?"); 
    MUSquestions.add("Kanye West has a total of how many Grammy awards?"); 
    MUSquestions.add("Beyonce Knowles was formally a member of which US group?"); 
    MUSquestions.add("In which US city was rapper 'Biggie Smalls' born?"); 
    MUSquestions.add("Michael Jackson's first number one single in the UK as a solo artist was what?"); 
    MUSquestions.add("The best selling album of all time in the UK is what?"); 
    MUSquestions.add("The best selling album of all time in the US is what?"); 
    MUSquestions.add("What is the artist known as 'Tiesto's real name?"); 
    MUSquestions.add("Which of these was not a member of The Beatles?"); 

    ArrayList<String> GENquestions = new ArrayList<String>(); // adding general knowledge questions 

    GENquestions.add("Who was the second President of the United States?"); 
    GENquestions.add("The youngest son of Bob Marley was who?"); 
    GENquestions.add("In the film '8 Mile', the character portrayed by Eminem is known as what?"); 
    GENquestions.add("What is the capital city of New Zealand?"); 
    GENquestions.add("What is the capital city of Australia?"); 
    GENquestions.add("How many millilitres are there in an English pint?"); 
    GENquestions.add("What was the biggest selling game for the PS2 worldwide?"); 
    GENquestions.add("What is the last letter of the Greek alphabet?"); 
    GENquestions.add("Who created the television series Futurama?"); 
    GENquestions.add("A word which reads the same backwards as it does forwards is known as a what?"); 
    GENquestions.add("A 'baker's dozen' consists of how many items?"); 
    GENquestions.add("World War 1 officially occured on which date?"); 
    GENquestions.add("'Trouble and strife' is cockney rhyming slang for what?"); 
    GENquestions.add("Who was the last Prime Minister to hail from the labour party in the UK?"); 
    GENquestions.add("WalMart is the parent company of which UK based supermarket chain?"); 




} 

}

+0

'MUSquestions' объявлен как локальная переменная внутри 'main' и поэтому не может ссылаться на другие методы. Возможно, было бы лучше спросить плакат с вопросом о помощи, а затем повторно отправить вопрос ... – MadProgrammer

ответ

1

У вас есть ссылочный проблема ...

В вашем методе main вы объявляете три локальные переменные;

public static void main(String[] args) { 
    ArrayList<String> SPOquestions = new ArrayList<String>(); // adding the sports questions for the quiz 
    //... 
    ArrayList<String> MUSquestions = new ArrayList<String>(); // adding the music questions 
    //... 
    ArrayList<String> GENquestions = new ArrayList<String>(); // adding general knowledge questions 
    //... 
} 

Это означает, что эти переменные не могут ссылаться из любого другого контекста, кроме main. «Простое» решение может заключаться в том, чтобы сделать их static переменными класса класса Questions. Хотя это будет работать, это создает проблемы и представляет собой более крупную долгосрочную проблему, static не отвечает на доступ к переменным, а представляет собой проблему с дизайном.

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

public class QuestionPane extends JPanel { 

    private ArrayList<String> SPOquestions = new ArrayList<String>(); // adding the sports questions for the quiz 
    private ArrayList<String> MUSquestions = new ArrayList<String>(); // adding the music questions 
    private ArrayList<String> GENquestions = new ArrayList<String>(); // adding general knowledge questions 

Таким образом, QuestionPane может получить доступ к каждой из переменных внутри его контекста (любой метод, объявленный в QuestionPane)

Например ...

import java.awt.BorderLayout; 
import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.ArrayList; 
import java.util.Collections; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

public class RandomStuff { 

    public static void main(String[] args) { 
     new RandomStuff(); 
    } 

    public RandomStuff() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(new QuestionPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class QuestionPane extends JPanel { 

     private ArrayList<String> SPOquestions = new ArrayList<String>(); // adding the sports questions for the quiz 
     private ArrayList<String> MUSquestions = new ArrayList<String>(); // adding the music questions 
     private ArrayList<String> GENquestions = new ArrayList<String>(); // adding general knowledge questions 

     private JLabel questionLabel; 
     private JButton randomButton; 

     public QuestionPane() { 

      setLayout(new GridBagLayout()); 
      GridBagConstraints gbc = new GridBagConstraints(); 
      gbc.gridwidth = GridBagConstraints.REMAINDER; 

      questionLabel = new JLabel(); 
      randomButton = new JButton("Next question"); 
      randomButton.addActionListener(new ActionListener() { 
       @Override 
       public void actionPerformed(ActionEvent e) { 
        String text = "?"; 
        switch ((int)Math.round(Math.random() * 2)) { 
         case 0: 
          Collections.shuffle(SPOquestions); 
          text = SPOquestions.get(0); 
          break; 
         case 1: 
          Collections.shuffle(MUSquestions); 
          text = MUSquestions.get(0); 
          break; 
         case 2: 
          Collections.shuffle(GENquestions); 
          text = GENquestions.get(0); 
          break; 
        } 
        questionLabel.setText(text); 
       } 
      }); 

      add(questionLabel, gbc); 
      add(randomButton, gbc); 

      SPOquestions.add("Who won the 2005 Formula One World Championship?"); 
      SPOquestions.add("Which team has the most Formula One Constructors titles?"); 
      SPOquestions.add("In what year did Roger Federer win his first 'Grand Slam'?"); 
      SPOquestions.add("How many 'Grand Slams' has Rafael Nadal won?"); 
      SPOquestions.add("Who has scored the most amount of goals in the Premier League?"); 
      SPOquestions.add("Who has won the most World Cups in football?"); 
      SPOquestions.add("How many MotoGP titles does Valentino Rossi hold?"); 
      SPOquestions.add("Who was the 2013 MotoGP champion?"); 
      SPOquestions.add("Who won the 2003 Rugby World Cup?"); 
      SPOquestions.add("In rugby league, how many points are awarded for a try?"); 
      SPOquestions.add("Who is the youngest ever snooker World Champion?"); 
      SPOquestions.add("In snooker, what is the highest maximum possible break?"); 
      SPOquestions.add("How many majors has Tiger Woods won?"); 
      SPOquestions.add("In golf, what is the tournament between the USA and Europe called?"); 
      SPOquestions.add("How many World Championships has darts player Phil Taylor won?"); 
      SPOquestions.add("What is the maximum possible amount of points a player can earn from throwing three darts?"); 
      SPOquestions.add("How many gold medals did Michael Phelps win at the 2008 Beijing Olympics?"); 
      SPOquestions.add("Who won the 2012 Olympic 100 metres mens race?"); 
      SPOquestions.add("Which of these events are not a part of the heptathlon?"); 
      SPOquestions.add("When was the first modern Olympics held?"); 

      MUSquestions.add("'Slash' was a member of which US rock band?"); 
      MUSquestions.add("Brian May was a member of which English rock band?"); 
      MUSquestions.add("What is the name of the music festival held annually in the town of Boom, Belgium?"); 
      MUSquestions.add("The rapper Tupac Shakuer '2Pac' died in which year?"); 
      MUSquestions.add("Which of these bands headlined the 2013 Glastonbury music festival?"); 
      MUSquestions.add("Which of these people designed the 'Les Paul' series of guitars?"); 
      MUSquestions.add("Keith Moon was a drummer for which English rock band?"); 
      MUSquestions.add("Kanye West has a total of how many Grammy awards?"); 
      MUSquestions.add("Beyonce Knowles was formally a member of which US group?"); 
      MUSquestions.add("In which US city was rapper 'Biggie Smalls' born?"); 
      MUSquestions.add("Michael Jackson's first number one single in the UK as a solo artist was what?"); 
      MUSquestions.add("The best selling album of all time in the UK is what?"); 
      MUSquestions.add("The best selling album of all time in the US is what?"); 
      MUSquestions.add("What is the artist known as 'Tiesto's real name?"); 
      MUSquestions.add("Which of these was not a member of The Beatles?"); 

      GENquestions.add("Who was the second President of the United States?"); 
      GENquestions.add("The youngest son of Bob Marley was who?"); 
      GENquestions.add("In the film '8 Mile', the character portrayed by Eminem is known as what?"); 
      GENquestions.add("What is the capital city of New Zealand?"); 
      GENquestions.add("What is the capital city of Australia?"); 
      GENquestions.add("How many millilitres are there in an English pint?"); 
      GENquestions.add("What was the biggest selling game for the PS2 worldwide?"); 
      GENquestions.add("What is the last letter of the Greek alphabet?"); 
      GENquestions.add("Who created the television series Futurama?"); 
      GENquestions.add("A word which reads the same backwards as it does forwards is known as a what?"); 
      GENquestions.add("A 'baker's dozen' consists of how many items?"); 
      GENquestions.add("World War 1 officially occured on which date?"); 
      GENquestions.add("'Trouble and strife' is cockney rhyming slang for what?"); 
      GENquestions.add("Who was the last Prime Minister to hail from the labour party in the UK?"); 
      GENquestions.add("WalMart is the parent company of which UK based supermarket chain?"); 

      randomButton.doClick(); 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(400, 200); 
     } 

    } 

} 

Вы также можете взглянуть на Code Conventions for the Java Programming Language, это делает его более легким для других, чтобы прочитать вам код;)

Вы также можете иметь чтения через Language Basics: Variables, Understanding Class Members и Creating a GUI With JFC/Swing

+0

Ничего себе, ваш код работает довольно сильно. Спасибо за помощь. Я также смотрю, как делать подобные вещи, но для радио-кнопок (как они будут отвечать на мои вопросы), и поэтому все меняется вместе ... вы могли бы мне помочь и направить меня с этим? – user3455584

+0

Я думал, что вы можете двигаться в этом направлении. Проблема, с которой вы столкнетесь, связана с «вопросами» с «ответами». Есть несколько способов, которыми вы могли бы достичь, если бы это был я, я бы начал с пользовательского объекта, который содержал «вопрос» в виде списка «ответов» и некоторых способов, с помощью которых вы могли бы определить правильный ответ ... – MadProgrammer

+0

Ну, мне также нужно настроить его так, чтобы отображалась только определенная категория вопросов, в зависимости от того, какая кнопка радио, нажата на моем главном экране, возможно, я должен сделать это первым! Вся ваша помощь приветствуется – user3455584

0

Попробуйте использовать

main.MUSquestions 

вместо

MUSquestions 

Или заменить главный с какой-либо вашего класса вы создали список в назван.

Или, чтобы сохранить ссылки короче и сделать это быстрее, объявить новый список, добавляя

ArrayList<String> MUSquestions = main.MUSquestions 

к тому, что в вашем вопросе верхний класс - как то, что вы записали не может найти MUSquestions, потому что он не определен, поскольку он доступен только в другом классе. (Как @MadProgrammer сказал)

+0

Не могли бы вы пояснить, что вы имели в виду с последним фрагментом кода? Как вы сказали, если он ускоряется, я попытаюсь его реализовать, я просто не знаю, где добавить ArrayList MUSquestions = main.MUSquestions – user3455584

+1

Я также не предлагал бы использовать «статические» или глобальные переменные;) – MadProgrammer

+0

чуть выше того, что вы написали - так 'ArrayList MUSquestions = main.MUSquestions; Вопрос = новый JLabel(); getContentPane(). Добавить (вопрос); Question.setText (MUSquestions.get (Math.random() * MUSquestions.size())); Question.setBounds (38, 61, 383, 29); 'Что вы получите – Marenthyu

0

Здесь я создал новый ответ:

Это основной класс для запуска приложения, и показать использование класса вопросов, которые я сделал.

import javax.swing.JLabel; 

public class Main { 

    Questions questions = new Questions(); 

    public static void main(String[] args) { 
     new Main(); 
    } 

    public Main() { 
     JLabel label = new JLabel(); 
     label.setText(questions.getRandomQuestion(questions.getSpoQuestions())); 
    } 
} 

Это класс вопросов, который предоставляет некоторые методы и вопросы, связанные с их вопросами.

import java.util.ArrayList; 
import java.util.Random; 

public class Questions { 

    private ArrayList<String> spoQuestions = new ArrayList(); 
    private ArrayList<String> musQuestions = new ArrayList(); 
    private ArrayList<String> genQuestions = new ArrayList(); 

    public Questions() { 
     createSpoQuestions(); 
     createMusQuestions(); 
     createGenQuestions(); 
    } 

    public ArrayList<String> getSpoQuestions() { 
     return spoQuestions; 
    } 

    public ArrayList<String> getMusQuestions() { 
     return musQuestions; 
    } 

    public ArrayList<String> getGenQuestions() { 
     return genQuestions; 
    } 

    public String getRandomQuestion(ArrayList<String> list) { 
     return list.get(new Random().nextInt(list.size())); 
    } 

    private void createSpoQuestions() { 
     spoQuestions.add("Who won the 2005 Formula One World Championship?"); 
     spoQuestions.add("Which team has the most Formula One Constructors titles?"); 
     spoQuestions.add("In what year did Roger Federer win his first 'Grand Slam'?"); 
     spoQuestions.add("How many 'Grand Slams' has Rafael Nadal won?"); 
     spoQuestions.add("Who has scored the most amount of goals in the Premier League?"); 
     spoQuestions.add("Who has won the most World Cups in football?"); 
     spoQuestions.add("How many MotoGP titles does Valentino Rossi hold?"); 
     spoQuestions.add("Who was the 2013 MotoGP champion?"); 
     spoQuestions.add("Who won the 2003 Rugby World Cup?"); 
     spoQuestions.add("In rugby league, how many points are awarded for a try?"); 
     spoQuestions.add("Who is the youngest ever snooker World Champion?"); 
     spoQuestions.add("In snooker, what is the highest maximum possible break?"); 
     spoQuestions.add("How many majors has Tiger Woods won?"); 
     spoQuestions.add("In golf, what is the tournament between the USA and Europe called?"); 
     spoQuestions.add("How many World Championships has darts player Phil Taylor won?"); 
     spoQuestions.add("What is the maximum possible amount of points a player can earn from throwing three darts?"); 
     spoQuestions.add("How many gold medals did Michael Phelps win at the 2008 Beijing Olympics?"); 
     spoQuestions.add("Who won the 2012 Olympic 100 metres mens race?"); 
     spoQuestions.add("Which of these events are not a part of the heptathlon?"); 
     spoQuestions.add("When was the first modern Olympics held?"); 
    } 

    private void createMusQuestions() { 
     musQuestions.add("'Slash' was a member of which US rock band?"); 
     musQuestions.add("Brian May was a member of which English rock band?"); 
     musQuestions.add("What is the name of the music festival held annually in the town of Boom, Belgium?"); 
     musQuestions.add("The rapper Tupac Shakuer '2Pac' died in which year?"); 
     musQuestions.add("Which of these bands headlined the 2013 Glastonbury music festival?"); 
     musQuestions.add("Which of these people designed the 'Les Paul' series of guitars?"); 
     musQuestions.add("Keith Moon was a drummer for which English rock band?"); 
     musQuestions.add("Kanye West has a total of how many Grammy awards?"); 
     musQuestions.add("Beyonce Knowles was formally a member of which US group?"); 
     musQuestions.add("In which US city was rapper 'Biggie Smalls' born?"); 
     musQuestions.add("Michael Jackson's first number one single in the UK as a solo artist was what?"); 
     musQuestions.add("The best selling album of all time in the UK is what?"); 
     musQuestions.add("The best selling album of all time in the US is what?"); 
     musQuestions.add("What is the artist known as 'Tiesto's real name?"); 
     musQuestions.add("Which of these was not a member of The Beatles?"); 
    } 

    private void createGenQuestions() { 
     genQuestions.add("Who was the second President of the United States?"); 
     genQuestions.add("The youngest son of Bob Marley was who?"); 
     genQuestions.add("In the film '8 Mile', the character portrayed by Eminem is known as what?"); 
     genQuestions.add("What is the capital city of New Zealand?"); 
     genQuestions.add("What is the capital city of Australia?"); 
     genQuestions.add("How many millilitres are there in an English pint?"); 
     genQuestions.add("What was the biggest selling game for the PS2 worldwide?"); 
     genQuestions.add("What is the last letter of the Greek alphabet?"); 
     genQuestions.add("Who created the television series Futurama?"); 
     genQuestions.add("A word which reads the same backwards as it does forwards is known as a what?"); 
     genQuestions.add("A 'baker's dozen' consists of how many items?"); 
     genQuestions.add("World War 1 officially occured on which date?"); 
     genQuestions.add("'Trouble and strife' is cockney rhyming slang for what?"); 
     genQuestions.add("Who was the last Prime Minister to hail from the labour party in the UK?"); 
     genQuestions.add("WalMart is the parent company of which UK based supermarket chain?"); 
    } 
} 

Эти два кода являются полностью работающим приложением. Я не создавал контекст графического интерфейса, поскольку цель состоит в том, чтобы показать вам, как использовать его в ярлыке.

Метод

public String getRandomQuestion(ArrayList<String> list) { 
     return list.get(new Random().nextInt(list.size())); 
    } 

будет возвращать строку, случайно вытащил из списка, приведенного с методом. Итак, глядя на пример основного класса, вы можете увидеть, что я вывожу случайный вопрос из spoQuestions ArrayList, вызвав getter для этого списка.

+0

Нет, не стоит. 'static' - не ответ, но проблема - IMHO – MadProgrammer

+0

Я не говорю, что это правильный путь. Но в этом контексте, не переписывая класс, он может использовать статический. Вам не разрешено использовать статические, если вы делаете экземпляры этого вопроса, что здесь не так. Идеальный способ - использовать геттеры в правильно создаваемом классе или синглете. – Limnic

+0

Итак, как же я мог бы затем вызвать одну из этих строк для отображения в тексте в моей JLabel? – user3455584

Смежные вопросы