Вопрос

In the process of writing a class that demonstrates a linked list and I'm not getting the results I need. I have written a class that contains an inner node class as well as an insert method that adds a name and score to the list, limits the list to ten by removing the person with the lowest score. I have also created a test GUI program. When ran and type the insert command the list doesn't display anything, however the window size changes slightly depending on what i type the command text field indicating to me, that the pack() method can "see" what I'm writing. I suspect my problem to be somewhere in my toString() method located in the GamerList class.

Linked List (GamerList) class:

class GameList
{
    //node class

    private class Node
    {
        String name;
        int score;
        Node next;

        //Node constructor
        Node(String namVal, int scrVal, Node n)
        {
            name = namVal;
            score = scrVal;
            next = n;
        }

        //Constructor
        Node(String namVal, int scrVal)
        {
            this(namVal, scrVal, null);
        }
    }

    private Node first; //head
    private Node last;  //last element in list

    //Constructor

    public GameList()
    {
        first = null;
        last = null;
    }

    //isEmpty method: checks if param first is empty
    public boolean isEmpty()
    {
        return first == null;
    }

    public int size()
    {
        int count = 0;
        Node p = first;

        while(p != null)
        {
            count++;
            p = p.next;
        }
        return count;
    }

  public String toString()
{
  StringBuilder strBuilder = new StringBuilder();

  Node p = first;
  Node r = first;
  while (p != null)
  {
     strBuilder.append(p.name + " ");
     p = p.next;
  }
      while (r != null)
  {
     strBuilder.append(r.score + "\n");
     r = r.next;
  }      
  return strBuilder.toString(); 
}

    public void insert(String name, int score)
    {
        Node node = new Node(name, score);
        final int MAX_LIST_LEN = 10;

        if(isEmpty())
        {
            first = node;
            first.next = last;
        }

        else if(first.score <= node.score)
        {
            node.next = first;
            first = node;
        }

        else
        {
            Node frontNode = first;
            while(frontNode.score > node.score && frontNode.next != null)
            {
                frontNode = frontNode.next;
            }
            node.next = frontNode.next;
            frontNode.next = node;
        }

        if(size() > MAX_LIST_LEN)
        {
            Node player = first;
            for(int i = 0; i < 9; i++)
            {
                player = player.next;
            }
            player.next = null;
        }
    }
}

GUI test program:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

/**
 This class is used to demonstrate
 the operations in the GameList class.
 */

public class GameListGui extends JFrame
{
    private  GameList topGamers;
    private JTextArea  listView;
    private JTextField cmdTextField;

    public GameListGui()
    {
        topGamers = new GameList();
        listView = new JTextArea();
        cmdTextField = new JTextField();

        // Create a panel and label for result field
        JPanel resultPanel = new JPanel(new GridLayout(1,2));
        resultPanel.add(new JLabel("Command Result"));
        add(resultPanel, BorderLayout.NORTH);

        // Put the textArea in the center of the frame
        add(listView);
        listView.setEditable(false);
        listView.setBackground(Color.WHITE);

        // Create a panel and label for the command text field
        JPanel cmdPanel = new JPanel(new GridLayout(1,2));
        cmdPanel.add(new JLabel("Command:"));
        cmdPanel.add(cmdTextField);
        add(cmdPanel, BorderLayout.SOUTH);
        cmdTextField.addActionListener(new CmdTextListener());

        // Set up the frame
        setTitle("Linked List Demo");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    private class CmdTextListener
            implements ActionListener
    {
        public void actionPerformed(ActionEvent evt)
        {
            String cmdText = cmdTextField.getText();
            Scanner sc = new Scanner(cmdText);
            String cmd = sc.next();
            if (cmd.equals("insert")){
            if (sc.hasNext())
            {
                // add index element
                String name = sc.next();
                int score = sc.nextInt();

                topGamers.insert(name, score);                
            }
            listView.setText(topGamers.toString());
            pack();
            return;
            }
        }
    }
    public static void main(String [ ] args)
    {
        new GameListGui();
    }
}
Это было полезно?

Решение

You interface is a little clunky. You could use a JTextField for the name a JSpinner for the score and JButton to insert the values into the linked list, but that's just me...

Overall, the information is getting to the JTextArea just fine, the formatting is wrong.

To start with, construct the listView with rows and columns

listView = new JTextArea(5, 20);

This will make the JTextArea occupy more space by default.

Second, place the JTextArea in a JScrollPane, this will allow the content to scroll automatically beyond the viewable size of the window, this means you can get rid of the pack in the ActionListener

Third, change the toString method in GameList. Having to separate loops doesn't seem to make sense, instead, include all the information you need in each iteration of a single loop, for example...

public String toString() {
    StringBuilder strBuilder = new StringBuilder();

    Node p = first;
    //Node r = first;
    while (p != null) {
        strBuilder.append(p.name).append(" ");
        strBuilder.append(p.score).append("\n");
        p = p.next;
    }
    //while (r != null) {
    //    strBuilder.append(r.score).append("\n");
    //    r = r.next;
    //}
    return strBuilder.toString();
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top