ArrayList into JList. A RMI Chatprogram with clientlist\channellist

817 views Asked by At

I'm having a hard time figuring out how i can add an arraylist into a Jlist generated with the inbuilt Netbeans Swing.

My goal is to have one list updating automatically every time a client joins a channel, just like IRC, with both clientlist and channel list.

Atm i have these classes with the following methods, allowing people to join channels, chat, leave, whisper etc.

So, i've read up a bit on the ListModel class, but im having some problems figuring out in which class i should add the listmodel.

The clientlist is arraylist, but the channellist is a hashtable. When im in a channel, i would want to get all the clients inside the same channel. How would that code go?

Btw, the code is mainly in Norwegian. If thats a problem, let me know, and ill translate it.

class ChatFrontImpl extends UnicastRemoteObject implements ChatFront {

private BrukerDAO b = new BrukerDAO();
private Hashtable<String, ArrayList<String>> kanaler = new Hashtable<String, ArrayList<String>>();
private ArrayList<Klient> klientene = new ArrayList<Klient>();

public ChatFrontImpl() throws RemoteException {
}

public synchronized boolean registrerMeg(Klient klient, String passord) throws RemoteException {
    if(!b.loggInn(klient.finnNavn(), passord)){
        System.out.println("feil brukernavn eller passord");
        return false;
    }
if (!klientene.contains(klient)) {
        try {
            klientene.add(klient);
      System.out.println("Na er " + klient.finnNavn() + " registrert.");    
  } catch (Exception e){
      System.out.println("Feil oppstatt i registrerMeg(): " + e);
      }
          return true;
     } else
        return false;
}

public String kobleTilKanal(String brukernavn, String kanal) throws RemoteException{ 
    if(erBrukerRegistrert(brukernavn)){
       if (!kanaler.containsKey(kanal)) {
        String melding = "Bruker " + brukernavn + " har ankommet kanalen";
        kanaler.put(kanal, new ArrayList<String>());
        kanaler.get(kanal).add(brukernavn);
        varsleKanalSystem(kanal, "SYSTEM", melding);
        varsleSelv(brukernavn, "Skriv /? for mulige kommandoer");
        return("Kanal opprettet, og bruker satt i kanalen.");
    }
    else{
        if(kanaler.get(kanal).contains(brukernavn)){
            return ("Brukeren er allerede i kanalen.");
        } else {
            kanaler.get(kanal).add(brukernavn);
                String melding = "Bruker " + brukernavn + " har ankommet kanalen";
                varsleKanalSystem(kanal, "SYSTEM", melding);
            return ("Kanal fantes allerede. Bruker satt i kanalen.");
          }
    }
    }
    return "";
}

public String kobleFraKanal(String brukernavn, String kanal) throws RemoteException{
    if(finnesBrukerIKanalX(brukernavn, kanal)){
        kanaler.get(kanal).remove(brukernavn);
        String melding = "Bruker " + brukernavn + " har forlatt kanalen.";
        varsleSelv(brukernavn, " Du har nå forlatt kanalen " + kanal);
        varsleKanalSystem(kanal, "SYSTEM", melding);
        if(kanaler.get(kanal).isEmpty()){
            kanaler.remove(kanal);
        } 
    }
    return ("Bruker har forlatt kanalen.");
}

I have a GUILogic class as well, fetching some methods from the ChatFrontImpl class, and making the connection to the RMI server.

And then theres the GUI Class, which is made by Netbeans.

import java.awt.Color;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author sindre
 */

public class GUI extends javax.swing.JFrame {

    GUILogikk gl = new GUILogikk(this);

    /** Creates new form GUI */
    public GUI() throws RemoteException, Exception {
        initComponents();
        String brukernavn = JOptionPane.showInputDialog("Hva er ditt brukernavn?");
        gl.setBrukernavn(brukernavn);
        String passord = JOptionPane.showInputDialog("Skriv inn passord.");
        gl.setPassord(passord);
        gl.OpprettCFKobling(brukernavn, passord);
        chatFelt.setEditable(false);
        skrivTekst.requestFocus();

private void KobleTilKanalActionPerformed(java.awt.event.ActionEvent evt) {                                              
    String kanal = JOptionPane.showInputDialog("Hvilken kanal vil du koble til?");
    gl.setKanal(kanal);
    try {
        gl.kobleTilKanal(gl.getBrukernavn(), gl.getKanal());
    } catch (RemoteException ex) {
        System.out.println(ex);
    } catch (NullPointerException ex) {
        JOptionPane.showMessageDialog(rootPane, "Ingen bruker er pålogget.");
    }
}                                             

private void kobleFraKanalActionPerformed(java.awt.event.ActionEvent evt) {                                              
    String kanal = JOptionPane.showInputDialog("Hvilken kanal vil du koble fra?");
    try {
        gl.kobleFraKanal(gl.getBrukernavn(), kanal);
    } catch (RemoteException ex) {
        Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NullPointerException ex) {
        JOptionPane.showMessageDialog(rootPane, "Ingen bruker er pålogget.");
    }
}                                             

private void skrivTekstActionPerformed(java.awt.event.ActionEvent evt) {                                           
    String tekst = null;
    tekst = skrivTekst.getText();
    gl.setTekst(tekst);
        try {
            gl.analyserTekst(gl.getBrukernavn(), gl.getKanal(), gl.getTekst());
        } catch (RemoteException ex) {
            Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NullPointerException ep){
            try {
                gl.feilmelding(gl.getBrukernavn(), "Du må være i en kanal for å kunne skrive. Bruk /join 'kanal' eller knappen til høyre for å joine en kanal");
            } catch (RemoteException ex) {
                Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        skrivTekst.setText("");
        skrivTekst.requestFocus();
}                                          

private void meldingPrivatActionPerformed(java.awt.event.ActionEvent evt) {                                              
    String til = JOptionPane.showInputDialog("Hvem vil du skrive til?");
    String melding = JOptionPane.showInputDialog("Hva vil du skrive?");
        try {
            gl.nyMeldingPrivat(gl.getBrukernavn(), til, melding);
        } catch (RemoteException ex) {
            Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
        }
}                                             

    private void muligeKommandoerActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        Object[] options = { "/Join", "/leave", "/Whisper", "/Quit", "Lukk" };
        int valg = JOptionPane.showOptionDialog(rootPane, "Hva vil du gjøre? ", null, WIDTH, WIDTH, null, options, rootPane);       
        switch (valg) {
                case 0:
                    skrivTekst.setText("/Join ");
                    skrivTekst.requestFocus();
                    break;
                case 1:
                    skrivTekst.setText("/Leave ");
                    skrivTekst.requestFocus();
                    break;
                case 2:
                    skrivTekst.setText("/Whisper ");
                    skrivTekst.requestFocus();
                    break;
                case 3:
                    skrivTekst.setText("/Quit");
                    skrivTekst.requestFocus();
                    break;
                case 4:
                    skrivTekst.requestFocus();
                    break;
        }
    }                                                

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        System.exit(DISPOSE_ON_CLOSE);
    }                                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            gl.hentAktiveKanaler(gl.getBrukernavn());
        } catch (RemoteException ex) {
            Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void nyMeldingKanal(String fraBruker, String tilKanal, String melding) throws RemoteException {
        chatFelt.append(fraBruker + "(" + tilKanal + ")" + ": " + melding + "\n");
        chatFelt.setCaretPosition(chatFelt.getText().length());
    }

    public void nyMeldingPrivat(String fra, String til, String melding) {
        chatFelt.append(fra + "sier: " + melding + "\n");
        chatFelt.setCaretPosition(chatFelt.getText().length());
    }

    public void nyMeldingSystem(String fraBruker, String tilKanal, String melding){
        chatFelt.setForeground(Color.red);
        chatFelt.append(fraBruker + "(" + tilKanal + ")" + ": " + melding + "\n");
        chatFelt.setCaretPosition(chatFelt.getText().length());
    }

    public void feilmelding(String til, String melding){
        chatFelt.append("" + melding + "\n");
        chatFelt.setCaretPosition(chatFelt.getText().length());
    }

    }
    // Variables declaration - do not modify
    private javax.swing.JButton KobleTilKanal;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JTextArea chatFelt;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JLayeredPane jLayeredPane2;
    private javax.swing.JList jList1;
    private javax.swing.JList jList2;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JPopupMenu jPopupMenu2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton kobleFraKanal;
    private javax.swing.JButton meldingPrivat;
    private javax.swing.JButton muligeKommandoer;
    private javax.swing.JTextField skrivTekst;
    // End of variables declaration
}
1

There are 1 answers

2
mKorbel On BEST ANSWER

define DefaultListModel that accesible throught all Java methods and Classes, this DefaultListModel can holds your Objects, for example there is JList in the JDialog,

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

// based on @trashgod code
/** @see http://stackoverflow.com/questions/5759131 */

public class ListDialog {

    private static final int N = 12;
    private JDialog dlg = new JDialog();
    private DefaultListModel model = new DefaultListModel();
    private JList list = new JList(model);
    private JScrollPane sp = new JScrollPane(list);
    private int count;

    public ListDialog() {
        list.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        JPanel panel = new JPanel();
        panel.add(new JButton(new AbstractAction("Add") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                append();
                if (count <= N) {
                    list.setVisibleRowCount(count);
                    dlg.pack();
                }
            }
        }));
        panel.add(new JButton(new AbstractAction("Remove") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                int itemNo = list.getSelectedIndex();
                if (itemNo > -1) {
                    removeActionPerformed(e, itemNo);
                }
            }
        }));
        for (int i = 0; i < N - 2; i++) {
            this.append();
        }
        list.setVisibleRowCount(N - 2);
        dlg.add(sp, BorderLayout.CENTER);
        dlg.add(panel, BorderLayout.SOUTH);
        dlg.pack();
        dlg.setLocationRelativeTo(null);
        dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dlg.setVisible(true);
    }

    private void removeActionPerformed(ActionEvent e, int itemNo) {
        System.out.println("made_list's model: " + list.getModel());
        System.out.println("Model from a fresh JList: " + new JList().getModel());
        model = (DefaultListModel) list.getModel();
        if (model.size() > 0) {
            if (itemNo > -1) {
                model.remove(itemNo);
            }
        }
    }

    private void append() {
        model.addElement("String " + String.valueOf(++count));
        list.ensureIndexIsVisible(count - 1);
    }

    public static void main(String[] a_args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                ListDialog pd = new ListDialog();
            }
        });
    }
}