Запись выбора пользователя java - PullRequest
0 голосов
/ 24 февраля 2012

У меня есть поле прокрутки, где пользователь может выбирать между вариантами.Если я хочу, чтобы пользователь выбрал печать в другом месте, что мне нужно будет позвонить?У меня уже есть где я хочу выбор пользователя.

 results.setText(); 

Что будет в скобках?

import javax.swing.*;

import java.awt.*;
import java.util.ArrayList;

import java.awt.event.*;

public class container implements ActionListener
{
    JPanel panels;
    Timer timer;
    JTextField userTypingRegion;
    JTextArea results;
    JComboBox<Integer> ageEntries;
    JComboBox<String> raceList;

    public void init(Container pane)
    {
        JButton switcher = new JButton("Next / Back");
        switcher.addActionListener(this);

        JPanel infoPage = new JPanel();
        infoPage.setBackground(Color.BLACK);

        //CENTER        
        JPanel panelCenter = new JPanel();
        panelCenter.setBackground(Color.GRAY);
        panelCenter.setLayout(new BoxLayout(panelCenter, BoxLayout.Y_AXIS));
        infoPage.add(BorderLayout.CENTER, panelCenter);


        ///Gender
        JPanel genderSelection = new JPanel();
        JLabel gender = new JLabel("Gender:");
        JCheckBox checkGenderMale = new JCheckBox("Male");
        JCheckBox checkGenderFemale = new JCheckBox("Female");

        genderSelection.add(gender);
        genderSelection.add(checkGenderMale);
        genderSelection.add(checkGenderFemale);

        panelCenter.add(genderSelection);

        ///Age
        JPanel ageSelection = new JPanel();
        JLabel age = new JLabel("Age:");

        ArrayList<Integer> ageList = new ArrayList<Integer>   ();

        for (int i = 1; i <= 100; ++i) 
        {
            ageList.add(i);
        }

        DefaultComboBoxModel<Integer> modelAge = new DefaultComboBoxModel<Integer>();
        for (Integer i : ageList) 
        {
            modelAge.addElement(i);
        }

        JComboBox<Integer> ageEntries = new JComboBox<Integer>();
        ageEntries.setModel(modelAge);                  

        ageSelection.add(age);
        ageSelection.add(ageEntries);

        panelCenter.add(ageSelection);              

        ///Race
        JPanel raceSelection = new JPanel();
        JLabel race = new JLabel("Race/Ethnicity:");
        String[] raceEntries = {"White", "Black", "Hispanic"
                                       , "Asian/Pacific Islander"
                                       , "Alaska Native/American Indian", "Confused"};
        JComboBox<String> raceList = new JComboBox<String>(raceEntries);


        raceList.addActionListener(new transferInfo());

        raceSelection.add(race);
        raceSelection.add(raceList);

        panelCenter.add(raceSelection);

        ///Question 1
        JPanel firstQuestion = new JPanel();

        JLabel one = new JLabel("How often do you read?");
        String[] oneEntries = {"Always", "Often", "Sometimes"
                                       , "Not Often", "What is reading?"};
        JComboBox<String> oneAnswer = new JComboBox<String>(oneEntries);

        firstQuestion.add(one);
        firstQuestion.add(oneAnswer);   

        panelCenter.add(firstQuestion);

        ///Question 2
        JPanel secondQuestion = new JPanel();

        JLabel two = new JLabel("Average time (in minutes) " +
                                          "spent on the computer per day:");
        ArrayList<Integer> hourList = new ArrayList<Integer>();

        for (int z = 0; z <= 1440; z = z + 30) 
        {
            hourList.add(z);
        }

        DefaultComboBoxModel<Integer> modelHour = new DefaultComboBoxModel<Integer>();
        for (Integer z : hourList) 
        {
            modelHour.addElement(z);
        }

        JComboBox<Integer> hourEntries = new JComboBox<Integer>();
        hourEntries.setModel(modelHour);

        secondQuestion.add(two);
        secondQuestion.add(hourEntries);

        panelCenter.add(secondQuestion);

        ///Question 3 
        JPanel thirdQuestion = new JPanel();

        JLabel three = new JLabel("Favorite Subject");
        String[] threeEntries = {"English", "Math", "Science"
                                   , "Foreign Languages", "History", "Hate them all"};
        JComboBox<String> threeAnswer = new JComboBox<String>(threeEntries);

        thirdQuestion.add(three);
        thirdQuestion.add(threeAnswer);

        panelCenter.add(thirdQuestion);

        ///Question 4
        JPanel fourthQuestion = new JPanel();

        JLabel four = new JLabel("Average sleep (in minutes) per night:");

        ArrayList<Integer> sleepTimeList = new ArrayList<Integer>();

        for (int y = 0; y <= 1440; y = y + 30) 
        {
            sleepTimeList.add(y);
        }

        DefaultComboBoxModel<Integer> modelSleepTime = new DefaultComboBoxModel<Integer>();
        for (Integer z : sleepTimeList) 
        {
            modelSleepTime.addElement(z);
        }

        JComboBox<Integer> sleepTimeEntries = new JComboBox<Integer>();
        sleepTimeEntries.setModel(modelSleepTime);

        fourthQuestion.add(four);
        fourthQuestion.add(sleepTimeEntries);

        panelCenter.add(fourthQuestion);                

        ///Question 5
        JPanel fifthQuestion = new JPanel();

        JLabel five = new JLabel("I am...");
        String [] fiveEntries = {"Outgoing", "In the middle", "Shy"};
        JComboBox<String> fiveAnswer = new JComboBox<String>(fiveEntries);

        fifthQuestion.add(five);
        fifthQuestion.add(fiveAnswer);

        panelCenter.add(fifthQuestion);

        ///Question 6
        JPanel sixthQuestion = new JPanel();

        JLabel six = new JLabel("I am...");
        String [] sixEntries = {"Adventurous", "In the middle", "Lazy"};
        JComboBox<String> sixAnswer = new JComboBox<String>(sixEntries);

        sixthQuestion.add(six);
        sixthQuestion.add(sixAnswer);

        panelCenter.add(sixthQuestion);

        ///Question 7
        JPanel seventhQuestion = new JPanel();

        JLabel seven = new JLabel("I live in the...");
        String [] sevenEntries = {"City", "Suburb", "Country", "Narnia"};
        JComboBox<String> sevenAnswer = new JComboBox<String>(sevenEntries);

        seventhQuestion.add(seven);
        seventhQuestion.add(sevenAnswer);

        panelCenter.add(seventhQuestion);   

        ///Question 8
        JPanel eighthQuestion = new JPanel();

        JLabel eight = new JLabel("Please choose the painting you like.");

        eighthQuestion.add(eight);

        panelCenter.add(eighthQuestion);

        ///Adding Picture
        JPanel pictures = new JPanel();

        ImageIcon image = new ImageIcon("C:\\Users\\Kevin\\Desktop\\Left and Right.jpg");
        JLabel imageButton = new JLabel();

        imageButton.setIcon(image);

        pictures.add(imageButton);

        panelCenter.add(pictures);

        ///Question 9
        JPanel ninthQuestion = new JPanel();

        JCheckBox checkLeft = new JCheckBox("I like the left one!");
        JCheckBox checkRight = new JCheckBox("I like the right one!");

        ninthQuestion.add(checkLeft);
        ninthQuestion.add(checkRight);

        panelCenter.add(ninthQuestion);

        ////Second Card

        JPanel programFrame = new JPanel();
        programFrame.setBackground(Color.BLACK);

        programFrame.setMinimumSize(new Dimension(200, 300));
        programFrame.setMaximumSize(new Dimension(800, 700));   
        programFrame.setPreferredSize(new Dimension(500, 500));


    ///CENTER DATA COLLECTION REGION
    JPanel dataCollectionRegion = new JPanel();

    dataCollectionRegion.setBackground(Color.LIGHT_GRAY);
    dataCollectionRegion.setLayout(
                      new BoxLayout(dataCollectionRegion, BoxLayout.Y_AXIS));
    programFrame.add(BorderLayout.CENTER, dataCollectionRegion);

    ///South Region
    JPanel southRegion = new JPanel();

    southRegion.setBackground(Color.BLACK);
    southRegion.setLayout(new BoxLayout(southRegion, BoxLayout.Y_AXIS));
    programFrame.add(BorderLayout.NORTH, southRegion);

    ///Data Components

    JLabel sampleWriting = new JLabel("<html>7 Dear friends, let us love one another, for love comes from God. <br>Everyone  who loves has been born of God and knows God. 8 Whoever <br>does not love  does not know God, because God is love. 9 This is how  <br>God showed his love among us: He sent his one and only Son into <br>the world that we  might live through him. 10 This is love: not that we <br>loved God, but that  he loved us and sent his Son as an atoning sacrifice <br> for our sins. 11 Dear friends, since God so loved us, we also ought <br>to love one another. 12  No one has ever seen God; but if we love one <br> another,  God lives in  us and his love is made complete in us. <br> 1 Everyone who believes that Jesus is the Christ is born of God, and everyone <br> who loves the father loves his child as well. 2 This is how we know <br> that we love the children of God: by loving God and carrying out his commands. <br> 3 In fact, this is love for God: to keep his commands. And his commands <br> are not burdensome, 4 for everyone born of God overcomes the world. <br> This is the victory that has overcome the world, even our faith. 5 Who <br> is it that overcomes the world? Only the one who believes that Jesus is the Son of God.</html>");

    userTypingRegion = new JTextField();

    userTypingRegion.addActionListener( this);


    dataCollectionRegion.add(sampleWriting);
    dataCollectionRegion.add(userTypingRegion);

    ///Instructions South

    JLabel instructions = new JLabel("Instruction: Type the " +
                               "passage as fast as possible in the space provided.");
    instructions.setForeground(Color.white);

    JLabel showResult = new JLabel("- - - Results - - -");

    showResult.setForeground(Color.white);
    showResult.setHorizontalTextPosition(JLabel.CENTER);

    results = new JTextArea();
    results.setEditable(false);

    southRegion.add(instructions);
    southRegion.add(Box.createRigidArea(new Dimension(0,5)));
    southRegion.add(showResult);
    southRegion.add(Box.createRigidArea(new Dimension(0,5)));
    southRegion.add(results);

    ///add cards
        panels = new JPanel(new CardLayout());
        panels.add(infoPage);
        panels.add(programFrame);

        pane.add(switcher, BorderLayout.PAGE_START);
        pane.add(panels, BorderLayout.CENTER);

    }

    public void actionPerformed(ActionEvent evt)
    {
        CardLayout layout = (CardLayout)(panels.getLayout());
        layout.next(panels);
    }

    class transferInfo implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            results.setText("Selected: " + raceList.getSelectedItem());    
        }
    }

    public static void main(String[] args) 
    {
        JFrame frame = new JFrame("Biometric Keystroke Dynamics");
        container TabChanger = new container();
        TabChanger.init(frame.getContentPane());
        frame.pack();
        frame.setResizable(false);
        frame.setVisible(true);  
    }  
}

Вы можете увидеть мою попытку решить эту проблему в конце кода.Я заранее прошу прощения за грязное кодирование.(это мой первый)

1 Ответ

0 голосов
/ 24 февраля 2012

Прежде всего ошибки, которые вы совершаете в своем коде:

  1. Вы объявляете JComboBox<Integer> ageEntries; и JComboBox<String> raceList; в качестве переменных вашего экземпляра и в качестве локальных переменных внутри вашего метода init (...). Не объявляйте их дважды, используйте только переменные экземпляра или локальные переменные, если это необходимо, но не используйте их дважды.
  2. Всегда делайте это своей привычкой, добавляя это значение frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);, когда вы создаете объект JFrame, это помогает правильно закрыть окно JFrame.

Теперь для чего писать в results.setText();. Вы можете создать один метод проверки внутри класса контейнера, который будет возвращать boolean и будет вызываться внутри actionPerformed(...) метода NextButton, а внутри этого метода проверять значения, введенные пользователем, как допустимые или нет, если они являются допустимыми значениями, затем используйте StringBuilder, чтобы добавить его, как, скажем,

StringBuilder sb = new StringBuilder(); // this will be your instance variable not local.
sb.append((String) ageEntries.getSelectedItem());
sb.append(" ");  // Add this space to distinguish between two values.
// and so on for other values.

После этого вы можете написать results.setText(containerObject.sb.toString());, чтобы показать эти значения.

...