尝试使用JavaSpace将数据永久存储在JList上

时间:2018-12-14 14:08:54

标签: java javaspaces

从下面的代码中,我可以向相关的JList添加主题和注释。我可以将代码存储在java空间中,并在必要时进行检索,但是,我想将数据永久存储在JList中,以便当新用户登录时可以看到输入的数据。

使用下面的代码,有人可以建议我该怎么做。

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 net.jini.space.JavaSpace05;
import net.jini.space.MatchSet;

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


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
public static MRQueueTopicCreate users = new MRQueueTopicCreate();
public LoginPage login;
public String currentUser;
public DefaultListModel<MRQueueTopicCreate> topicListModel;
public DefaultListModel<MRQueueTopicCreate> allListModel;
public DefaultListModel<MRQueueTopicCreate> selectTopicsModel;
public DefaultListModel<MRQueueCommentCreate> commentListModel;


String User = users.TopicUserID;
private JavaSpace space;
private JTextField newComment, jobNumberOut, topicIn, usernameString;
private Label username;
private JList topicPostArea, topicStoreArea;
private DefaultComboBoxModel combo;
private JTextArea box, privateArea;
public static  boolean hasRunMethod = false;
private JList list, allDetailsList, selectTopicsList, newList;




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

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();
    JLabel privateField = 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<>();
    list = new JList(topicListModel);

    allListModel = new DefaultListModel<>();
    allDetailsList = new JList(allListModel);

    selectTopicsModel = new DefaultListModel<>();
    selectTopicsList = new JList(selectTopicsModel);

    commentListModel = new DefaultListModel<>();
    selectTopicsList = new JList(commentListModel);

    newList = new JList();
    topicStoreArea = new JList();

    JScrollPane pane = new JScrollPane(list);
    JScrollPane newListPane = new JScrollPane(newList);
    JScrollPane addCommentPane = new JScrollPane(selectTopicsList);

    jpanel3.add(topicStoreArea);

    box = new JTextArea(30, 30);

    //buttons
    JButton getButton = new JButton();

    JButton addTopicButton = new JButton();

    JButton deleteTopicButton = new JButton();

    JButton addCommentButton = new JButton();


    jpanel3.add(box);
    box.setEditable(false);

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


    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(privateField);
    jPanel1.add(userNameLabel);

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






    /*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);*/




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

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


    /*addNotificationButton.addListSelectionListener(e -> {
        notify(); //add Notification
    });*/


    newList.addListSelectionListener(e -> {
        if (hasRunMethod == false) {
          //  ViewTopicsPosts();

        }
        else{
            hasRunMethod = true;
        }
    });


    jPanel2.add(addTopicButton);

    jPanel2.add(addCommentButton);

    jPanel2.add(getButton);

    jPanel2.add(deleteTopicButton);



    cp.add(jPanel1, "North");
    cp.add(jPanel2, "South");
    cp.add(jpanel3, "East");
    add(pane, BorderLayout.WEST);
    add(newListPane, BorderLayout.CENTER);
    add(addCommentPane, BorderLayout.NORTH);
    //add(allListPane, BorderLayout.WEST);

   // add(selectTopicsPane, BorderLayout.CENTER);







 /*

    list.addMouseListener(new MouseAdapter() {
                              @Override
                              public void mouseClicked(MouseEvent e) {

                                  MRQueueTopicCreate template = new MRQueueTopicCreate();
                                  MatchSet set = null;

                                  try {
                                      set = ((JavaSpace05) space).contents(Collections.singletonList(template), null, 1000 * 2, Long.MAX_VALUE);
                                      MRQueueTopicCreate topic = null;

                                      super.mouseClicked(e);
                                      try {
                                          topic = (MRQueueTopicCreate) set.next();
                                          while (topic != null) {
                                              if (e.getButton() == MouseEvent.NOBUTTON) {
                                                  //textArea.setText("No button clicked...");
                                                  topicListModel.addElement(topic);
                                                  topicListModel.addElement(MRHomePage.users);

                                              }
                                          }


                                      } catch (RemoteException et) {
                                          et.printStackTrace();


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


                              });
*/




}


//methods



  public void addComment(java.awt.event.ActionEvent evt) {

    String comment = newComment.getText();
    String topic = topicIn.getText();
    String userID = usernameString.getText();


    try {

        MRQueueCommentCreate topicLog = new MRQueueCommentCreate(comment,topic);
        topicLog.setComment(comment);
        topicLog.CommentUserId = userID;
        topicLog.Comment = comment;
        ;

        //ViewTopicsPosts();


        MRQueueTopicCreate template = topicListModel.elementAt(list.getSelectedIndex());

       topicListModel.getElementAt(list.getSelectedIndex());

        topicLog.CommentUserId = LoginPage.user.getUsername();

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

        commentListModel.addElement(topicLog);

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

    allDetailsList.setModel(commentListModel);

}



public void deleteTopic(java.awt.event.ActionEvent evt) {
    String comment = newComment.getText();
    String topic = topicIn.getText();
    String userID = usernameString.getText();
    Integer bound1 = 0;
    Integer bound2 = -1;

    try {
        MRQueueTopicCreate topicLog = new MRQueueTopicCreate(comment, topic, userID);
        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);
        //if (template.owner = currentUser.username) {
        //topicListModel.remove(list.getSelectedIndex());


        MRQueueTopicCreate template = topicListModel.elementAt(list.getSelectedIndex());
        MRQueueTopicCreate template1 = allListModel.elementAt(list.getSelectedIndex());
        if(template.TopicUserID == LoginPage.user.getUsername())
        {
            topicListModel.remove(list.getSelectedIndex());
            commentListModel.remove(list.getSelectedIndex());
            //allListModel.remove(allDetailsList.getSelectedIndex());
            System.out.println("user matches, topic removed");

        }
        else {
            System.out.println("ugh");
        }

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

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

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

    try {

        MRQueueTopicCreate topicLog = new MRQueueTopicCreate(comment, topic, userID);
        topicLog.Topic = topic;
        topicLog.Comment = comment;
        topicLog.TopicUserID = userID;

        MRQueueTopicCreate topicLogger = new MRQueueTopicCreate(comment, topic, userID);
        topicLogger.Topic = topic;

        //ViewTopicsPosts();


        topicLog.TopicUserID = LoginPage.user.getUsername();

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


        topicListModel.addElement(topicLog);
        allListModel.addElement(topicLogger);
        //allTopics.getItemAt(allTopics.getSelectedIndex());



        //adds to the textfield on the left handside of the page
        //box.append("[" + "User:" + " " + LoginPage.user.getUsername() + " - " + "Topic: " + topic + "]" + "\n");

        //topicPostArea.append("[" + "User:" + " " + user + " - " + "Topic: " + topic + " - " + "Comment: " + comment + "]" + "\n");


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

    list.setModel(topicListModel);

    //allDetailsList.setModel(allListModel);

}



  public void getSobj(java.awt.event.ActionEvent evt) {
    MRQueueTopicCreate template = new MRQueueTopicCreate();
    MatchSet set = null;
    try {
        set = ((JavaSpace05) space).contents(Collections.singletonList(template), null, 1000 * 2, Long.MAX_VALUE);


        MRQueueTopicCreate topic = null;




        MRQueueTopicCreate got = (MRQueueTopicCreate) space.take(template, null, Lease.FOREVER);
        if (got == null)
            box.setText("No object found");
        else if (list.isSelectedIndex(1))
        {

        }
        else // use this to diplay all contents into the outstring textfield.

            box.setText(got.getTopic());

    } catch (Exception e) {
        e.printStackTrace();
    }
    //newList.setModel(topicListModel);
}


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 ViewTopicsPosts() {
int selectedIndex = list.getSelectedIndex();


if (selectedIndex == -1) {

} else {
    MRQueueTopicCreate topic = new MRQueueTopicCreate();
    topic.Topic = topic.Topic;
    topic.Comment = topic.Comment;
    MatchSet set = null;

    try {
        set = ((JavaSpace05) space).contents(Collections.singletonList(topic), null, 1000 * 2, Long.MAX_VALUE);
        MRQueueTopicCreate topicPosts = null;

        try {
            newList.clearSelection();
            topicPosts = (MRQueueTopicCreate) set.next();
            while (topicPosts != null) {

                if (topic.TopicUserID.equals(LoginPage.user.userID)) {
                    newList.setModel(topicListModel);
                    topicListModel.addElement(topic);
                    topicListModel.addElement(MRHomePage.users);
                }

                else  {
                    System.out.println("");

                }
                topicPosts = (MRQueueTopicCreate) set.next();
                hasRunMethod = true;
            }

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

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



  /* public void getAllTopics() {
    MRQueueTopicCreate template = new MRQueueTopicCreate();
    MatchSet set = null;
    try {
        set = ((JavaSpace05) space).contents(Collections.singletonList(template), null, 1000 * 2, Long.MAX_VALUE);
        MRQueueTopicCreate topic = null;

        try {
            topic = (MRQueueTopicCreate) set.next();
            while (topic != null) {
                if (topic.TopicUserID.equals(LoginPage.user.userID)) {
                    topicListModel.addElement(topic);
                    topicListModel.addElement(MRHomePage.users);

                    newList.setModel(topicListModel);

                } else {
                    topicListModel.addElement(topic);
                }
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    //newList.setModel(topicListModel);


}*/



public void registerForEvents() {

}


@Override
public void notify(RemoteEvent remoteEvent) throws UnknownEventException, RemoteException {
    //look for Gary's code on this
    //the below code is from week 7 lecture notes

    // this is the method called when we are notified
    // of an object of interest
    //Sobj template = new Sobj();

    try {
      //  Sobj result = (Sobj)space.take(template, null, Long.MAX_VALUE);
        //System.out.println(result.contents);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // that's all we need to do in this demo so we can quit...
    System.exit(0);

}
}

0 个答案:

没有答案