Is it possible to make a Stack with JList?

1

My program should perform the function of a stack (Stack). I did it with an interface, I used a texfield and a button to put the data that will be entered into the stack (JList) and if they are entered in the JList the problem is that I do not know how to do so They are piled up.

Example: I must enter 10, 20, 30, 40 y 50 , then in the JList they should appear like this:

50 
40
30
20
10

I leave my code and an image of the interface.

package epila;

import java.awt.Color;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

public class Pilas extends javax.swing.JFrame {

    DefaultListModel Numeros  = new DefaultListModel();    

    public Pilas() {
        setTitle("Programa de Pila ");
        setResizable(false);
        initComponents();
        jLabel4.setVisible(false);
        jLabel1.setVisible(false);
        jLabel2.setVisible(false);
        Pila.setVisible(false); //Para no mostrar luego los datos en la pila.
        Pila.setSelectionBackground(Color.yellow); /*Hace que algun elemento que
        se seleccione del JList cambie al color indicado.*/
        Pila.setToolTipText("Pila");
    }
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        Pilas pilita = new Pilas();
        String dato;
        int Dato, numeros=0;
        try{
            Dato = Integer.parseInt(Tex1.getText()); 
            Numeros.addElement(Dato);
            Pila.setModel(Numeros);
            Tex1.setText(null);
            jLabel4.setText(String.valueOf(Numeros.getSize()));
        }
        catch(RuntimeException e){
            JOptionPane.showMessageDialog(null, "Debes ingresar un valor");
        }
    }                                        
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        Numeros.removeAllElements();
        jLabel4.setText(String.valueOf(Numeros.getSize()));
    }                                        
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
        if(Numeros.getSize()>0){
        int n = Pila.getSelectedIndex();
        Numeros.removeElementAt(n);
        Pila.setSelectedIndex(0);
        }
        jLabel4.setText(String.valueOf(Numeros.getSize()));
    }                                        

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
        jLabel4.setVisible(true);
        jLabel1.setVisible(true);
        jLabel2.setVisible(true);
    }
}
    
asked by Hector Vargas Rodriguez 08.11.2016 в 08:15
source

2 answers

0

JList does not allow adding or removing items directly. Instead, what you own is an internal ListModel which contains the list of elements that it has. Depending on the implementation of ListModel to choose, for example DefaultListModel allows you to add the elements dynamically there. What you can do is to have your instance of DefaultListModel treat it like a stack.

Example:

DefaultListModel<Integer> pila = new DefaultListModel<>();
JList<Integer> lista = new JList(pila);

//...

public void push(Integer numero) {
    pila.addElement(numero);
}

public void pop() {
    if (!pila.isEmpty()) {
        pila.removeElementAt(pila.size() - 1);
    }
}
    
answered by 08.11.2016 в 16:43
0

I leave the file: / *  * To change this license header, choose License Headers in Project Properties.  * To change this template file, choose Tools | Templates  * and open the template in the editor.  * /

package pilagrafica;

import javax.swing.DefaultListModel;
import javax.swing.JList;

/**
 *
 * @author Harlericho
 */
public class Pila {

Pila cima;
int tope;
String dato;
Pila siguiente;

public Pila() {
    cima = null;
    tope = 0;
}

public Pila(String elemento) {
    dato = elemento;
    siguiente = null;

}

public void insertarPila(String ele) {
    Pila insertar = new Pila(ele);
    insertar.siguiente = cima;
    cima = insertar;
    tope++;
}

public String eliminarPila() {
    String aux = cima.dato;
    cima = cima.siguiente;
    tope--;
    return aux;
}

public boolean vaciaPila() {
    return cima == null;
}

public int topePila() {
    return tope;
}

public void inprimirPila() {
    Pila aux = cima;
    String cadena = "";
    while (aux != null) {
        cadena = cadena + aux.dato + "\n";

        aux = aux.siguiente;
    }
    System.out.println("" + cadena);
}
}

--------------------- / *  / *  * To change this license header, choose License Headers in Project Properties.  * To change this template file, choose Tools | Templates  * and open the template in the editor.  * /

package pilagrafica;

import com.sun.xml.internal.ws.api.streaming.XMLStreamReaderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JOptionPane;

/**
 *
 * @author Harlericho
 */
public class PilaGraf extends javax.swing.JFrame {

Pila pili = new Pila();

/**
 * Creates new form PilaGraf
 */
public PilaGraf() {
    initComponents();

}

public void mostrarPila() {
    DefaultListModel modelo = new DefaultListModel();
    Pila aux = pili.cima;
    String cadena = "";
    while (aux != null) {
        cadena =  aux.dato + "\n";
        modelo.addElement(cadena);
        aux = aux.siguiente;
    }
    jLiPila.setModel(modelo);

}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {

    jcMousePanel1 = new jcMousePanel.jcMousePanel();
    jtxtTexto = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jLiPila = new javax.swing.JList<>();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Pila");

    jcMousePanel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/Playing_God.jpg"))); // NOI18N
    jcMousePanel1.setVisibleLogo(false);

    jLabel1.setText("Datos a la Pila:");

    jScrollPane1.setViewportView(jLiPila);

    jButton1.setText("Añadir");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jButton2.setText("Tope");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    jButton3.setText("Borrar");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jcMousePanel1Layout = new javax.swing.GroupLayout(jcMousePanel1);
    jcMousePanel1.setLayout(jcMousePanel1Layout);
    jcMousePanel1Layout.setHorizontalGroup(
        jcMousePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jcMousePanel1Layout.createSequentialGroup()
            .addGap(66, 66, 66)
            .addGroup(jcMousePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jcMousePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jcMousePanel1Layout.createSequentialGroup()
                    .addGap(18, 18, 18)
                    .addComponent(jtxtTexto, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jcMousePanel1Layout.createSequentialGroup()
                    .addGap(44, 44, 44)
                    .addGroup(jcMousePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
            .addContainerGap(58, Short.MAX_VALUE))
    );
    jcMousePanel1Layout.setVerticalGroup(
        jcMousePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jcMousePanel1Layout.createSequentialGroup()
            .addGap(71, 71, 71)
            .addGroup(jcMousePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jtxtTexto))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jcMousePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(jcMousePanel1Layout.createSequentialGroup()
                    .addComponent(jButton1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jButton2)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jButton3)))
            .addContainerGap(113, Short.MAX_VALUE))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jcMousePanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 378, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jcMousePanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 345, Short.MAX_VALUE)
    );

    pack();
}// </editor-fold>//GEN-END:initComponents

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    pili.insertarPila(jtxtTexto.getText());
    mostrarPila();
}//GEN-LAST:event_jButton1ActionPerformed

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    // TODO add your handling code here:
    JOptionPane.showMessageDialog(null, "Tope es: "+pili.topePila());
}//GEN-LAST:event_jButton2ActionPerformed

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    // TODO add your handling code here:
    pili.eliminarPila();
    mostrarPila();
}//GEN-LAST:event_jButton3ActionPerformed

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(PilaGraf.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(PilaGraf.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(PilaGraf.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(PilaGraf.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new PilaGraf().setVisible(true);
        }
    });
}

// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JList<String> jLiPila;
private javax.swing.JScrollPane jScrollPane1;
private jcMousePanel.jcMousePanel jcMousePanel1;
private javax.swing.JTextField jtxtTexto;
// End of variables declaration//GEN-END:variables
}
    
answered by 06.12.2018 в 21:26