Попытка преобразовать JLabel в JList с помощью setCellRenderer - PullRequest
0 голосов
/ 11 декабря 2018

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

Если бы кто-то мог посоветовать, как это можно сделать, используя код, который у меня уже есть, это было бы полезно.

import net.jini.core.event.RemoteEvent;
import net.jini.core.event.RemoteEventListener;
import net.jini.core.event.UnknownEventException;
import net.jini.core.lease.Lease;
import net.jini.space.JavaSpace;

import javax.swing.*;
import java.awt.*;
import java.rmi.RemoteException;


public class MRHomePage extends JFrame implements RemoteEventListener {

private static final long TWO_SECONDS = 2 * 1000;  // two thousand milliseconds
private static final long ONESECOND = 1000;  // one thousand milliseconds
private JavaSpace space;
private JTextField newComment, jobNumberOut, topicIn, usernameString;
private Label username;
private JList topicPostArea, topicStoreArea;
private JTextArea box, privateArea;
public LoginPage login;
public JComboBox allTopics;
public String currentUser;
public DefaultListModel<MRQueueTopicCreate> topicListModel;


public MRHomePage() {
    space = SpaceUtils.getSpace();
    if (space == null) {
        System.err.println("Failed to find the javaspace");
        System.exit(1);
    }
    initComponents();
    pack();
    printPosts();
    startUP();
    //addTopic();
    setVisible(true);

}

public static void main(String[] args) {

    new MRHomePage().setVisible(true);
}

public void initComponents() {

    addWindowListener(new java.awt.event.WindowAdapter() {
        public void windowClosing(java.awt.event.WindowEvent evt) {
            System.exit(0);
        }
    });

    //container
    Container cp = getContentPane();
    cp.setLayout(new BorderLayout());

    //panels
    JPanel jPanel1 = new JPanel();
    jPanel1.setLayout(new FlowLayout(FlowLayout.LEFT));

    JPanel jPanel2 = new JPanel();
    jPanel2.setLayout(new FlowLayout());

    JPanel jpanel3 = new JPanel();
    jpanel3.setLayout(new FlowLayout());



    //labels
    JLabel commentLabel = new JLabel();
    JLabel topicLabel = new JLabel();
    JLabel userNameLabel = new JLabel();


    //text fields
    usernameString = new JTextField(12);
    topicIn = new JTextField(7);
    newComment = new JTextField(3);
    jobNumberOut = new JTextField(2);

    //text Area
    privateArea = new JTextArea(30,30);

    topicListModel = new DefaultListModel<>();

    topicPostArea = new JList();
    topicStoreArea = new JList();



    topicPostArea.setCellRenderer(new ListCellRenderer<MRQueueTopicCreate>() {
        @Override
        public Component getListCellRendererComponent(JList list, MRQueueTopicCreate value, int index, boolean isSelected, boolean cellHasFocus) {
            JLabel jLabel = new JLabel();
            jLabel.setText( "[" + "User:" + " "  + " - " + "Topic: " +
                    value.Topic + " - " + "Comment: " + value.Comment + "]" + "\n");
            return jLabel;
        }
    });
    topicPostArea.setModel(topicListModel);
    box = new JTextArea(30, 30);



    //buttons
    JButton getButton = new JButton();

    JButton addTopicButton = new JButton();

    JButton deleteTopicButton = new JButton();


    //add areas to panels
    jpanel3.add(box);
    box.setEditable(false);
    jpanel3.add(topicPostArea);
    //topicPostArea.setEditable(false);
    jpanel3.add(privateArea);
    privateArea.setEditable(false);


    //set label text
    topicLabel.setText("Topic ");
    commentLabel.setText("Comment ");
    userNameLabel.setText("Username ");
    getButton.setText(" Get ");
    addTopicButton.setText("Post Topic");
    deleteTopicButton.setText("Delete private content");


    topicIn.setText("");
    newComment.setText("");
    jobNumberOut.setText("");


    jPanel2.add(topicLabel);
    jPanel2.add(topicIn);
    topicIn.setEditable(true);


    jPanel2.add(commentLabel);
    jPanel2.add(newComment);
    newComment.setEditable(true);

    jobNumberOut.setEditable(true);
    jPanel1.add(jobNumberOut);


    jPanel1.add(userNameLabel);

    currentUser = LoginPage.user.getUsername();
    usernameString.setText(LoginPage.user.getUsername());
    usernameString.setEditable(false);
    jPanel1.add(usernameString);







    //action performed


    getButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            getSobj(evt);
        }
    });

    addTopicButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            addTopic(evt);
        }
    });


    deleteTopicButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            deleteTopic(evt);
        }
    });


    jPanel2.add(addTopicButton);

    jPanel2.add(getButton);

    jPanel2.add(deleteTopicButton);


    cp.add(jPanel1, "North");
    cp.add(jPanel2, "South");
    cp.add(jpanel3, "Center");

}


//methods


public void deleteTopic(java.awt.event.ActionEvent evt) {
    String comment = newComment.getText();
    String topic =  topicIn.getText();

    try {

        MRQueueTopicCreate topicLog = new MRQueueTopicCreate(comment, topic);
        space.write(topicLog, null, Long.MAX_VALUE);
        topicLog.setTopic(topic);
        topicLog.setComment(comment);

        space.write(topicLog, null, Lease.FOREVER);

        //jobNumberOut.setText("" + topic);
        // jobNameIn.setText("" + comment);
        MRQueueTopicCreate template = topicListModel.elementAt(topicPostArea.getSelectedIndex());
        //if (template.owner = currentUser.username) {
        topicListModel.remove(topicPostArea.getSelectedIndex());


        space.take(template, null, 1000*2);
        //}

    }catch (Exception e) {
        e.printStackTrace();
    }
}

public void addTopic(java.awt.event.ActionEvent evt) {
    String comment = newComment.getText();
    String topic = topicIn.getText();

        try {

            MRQueueTopicCreate topicLog = new MRQueueTopicCreate(comment, topic);
            space.write(topicLog, null, Long.MAX_VALUE);
            topicLog.setTopic(topic);
            topicLog.setComment(comment);

            space.write(topicLog, null, Lease.FOREVER);

            //jobNumberOut.setText("" + topic);
           // jobNameIn.setText("" + comment);
            topicListModel.addElement(topicLog);

            //box.append("[" + "User:" + " " + LoginPage.user.getUsername() + " - " + "Topic: " + topic + "]" + "\n");

            //topicPostArea.append("[" + "User:" + " " + user + " - " + "Topic: " + topic + " - " + "Comment: " + comment + "]" + "\n");
    }catch (Exception e) {
        e.printStackTrace();
    }
}

public void printPosts() {
    try {
        QueueItem qiTemplate = new QueueItem();
        QueueItem nextJob = (QueueItem) space.take(qiTemplate, null, TWO_SECONDS);
        if (nextJob == null) {
            // no print job was found, so sleep for a couple of seconds and try again
            Thread.sleep(TWO_SECONDS);
        } else {
            // we have a job to process
            int nextJobNumber = nextJob.jobNumber;
            String nextJobName = nextJob.filename;
            String nextTopic = nextJob.topicName;
            box.append("Job Number: " + nextJobNumber + " " + "Topic" + nextTopic + " " + "\n");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

public void getSobj(java.awt.event.ActionEvent evt) {
    QueueLogin template = new QueueLogin();
    try {
        QueueLogin got = (QueueLogin) space.take(template, null, TWO_SECONDS);
        if (got == null)
            usernameString.setText("No object found");
        else // use this to diplay all contents into the outstring textfield.
            usernameString.setText(got.username);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void startUP() {
    JavaSpace space = SpaceUtils.getSpace();

    if (space == null) {
        System.err.println("Failed to find the javaspace");
        System.exit(1);
    }

    QueueStatus template = new QueueStatus();
    try {
        QueueStatus returnedObject = (QueueStatus) space.readIfExists(template, null, ONESECOND);
        if (returnedObject == null) {
            // there is no object in the space, so create one
            try {
                QueueStatus qs = new QueueStatus(0);
                space.write(qs, null, Lease.FOREVER);
                System.out.println("QueueStatus object added to space");
                System.exit(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            // there is already an object available, so don't create one
            System.out.println("QueueStatus object is already in the space");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

public void registerForEvents() {

}

@Override
public void notify(RemoteEvent remoteEvent) throws UnknownEventException, RemoteException {
    //look for Gary's code on this
}
}

Модель

import net.jini.core.entry.Entry;

public class MRQueueTopicCreate implements Entry {
// Variables
public String Topic;
public String Comment;

// No arg contructor
public MRQueueTopicCreate() {
}

// Arg constructor
public MRQueueTopicCreate(String tp, String cm) {
    this.Topic = tp;
    this.Comment = cm;
}

public String getTopic() {
    return Topic;
}
public String getComment() {
    return Comment;
}

public void setTopic(String topics) {
    this.Topic = topics;
}
public void setComment(String comments) {
    this.Comment = comments;
}

}

1 Ответ

0 голосов
/ 11 декабря 2018

Компоненты Swing по умолчанию отображают строковую форму каждого объекта данных.Таким образом, вы можете удалить средство визуализации ячеек и предоставить метод toString в своем классе MRQueueTopicCreate:

public class MRQueueTopicCreate implements Entry {
    // ...

    @Override
    public String toString() {
        return "[" + "User:" + " " + " - " + "Topic: " +
            Topic + " - " + "Comment: " + Comment + "]";
    }

В качестве бонуса ваш JList будет доступен - значит, он будет работать спрограммы чтения с экрана, используемые пользователями с нарушениями зрения, без каких-либо дополнительных усилий с вашей стороны.Пользовательские средства визуализации, с другой стороны, не могут быть интерпретированы с помощью вспомогательных технологий.

Нет смысла ставить \n в конце текста.JList уже разделяет элементы визуально.

В будущем, если вы захотите внедрить средство визуализации ячеек по любой другой причине, вам следует расширить DefaultListCellRenderer.Ваш пользовательский рендерер каждый раз создает новую JLabel, что является дорогостоящим (поскольку рендереры часто называются очень , когда пользователь взаимодействует с ними) и может даже ухудшить производительность.

...