简体   繁体   中英

Trying to convert a JLabel to JList using a setCellRenderer

I am trying to convert the data that I am storing in my Jlabel into a JList using the "topicPostArea.setCellRenderer" method within the code, reason being that I have some delete functionality that requires the data to be stored in a list before I can delete the content.

If someone could advise how this can be done using the code that I have already in place that would be appreciated.

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
}
}

Model

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;
}

}

Swing components, by default, display the string form of each data object. So, you can remove the cell renderer, and provide a toString method in your MRQueueTopicCreate class:

public class MRQueueTopicCreate implements Entry {
    // ...

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

As a bonus, your JList will be accessible —meaning, it will work with screen readers used by sight impaired users, with no additional effort on your part. Custom renderers, on the other hand, cannot be interpreted by assistive technology.

There is no reason to place \\n at the end of the text. JList already separates items visually.

In the future, if you happen implement a cell renderer for any other reason, you should extend DefaultListCellRenderer. Your custom renderer is creating a new JLabel every time, which is costly (since renderers are called very frequently when the user interacts with them) and may even impair performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM