-2

I'm starting programming, learning a little Swing. I was praticing using the the Visual IDE of Netbeans; that is easy. I just click on the components to add to Form. I found an example in internet that have two JLists. I need to add a third, but I don't know cause there's no graphic interface; it was did in code. Can you help me to add a third at the end of Form?

This iss the modified code and a photo of the original aplication running:

https://i.stack.imgur.com/AORrZ.jpg

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.swing.AbstractListModel;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;

import br.com.project.receita.dao.IngredienteDao;
import br.com.project.receita.vo.IngredienteVo;

public class DualListBox extends JPanel {

  private static final Insets EMPTY_INSETS = new Insets(0, 0, 0, 0);

  private static final String ADD_BUTTON_LABEL = "Adicionar >>";

  private static final String REMOVE_BUTTON_LABEL = "<< Remover";

  private static final String INGREDIENTES_DISPONIVEIS = "Ingredientes Disponíveis";

  private static final String INGREDIENTES_SELECIONADOS = "Ingredientes Selecionados";

  private static final String RECEITAS_DISPONIVEIS = "Receitas Disponíveis";

  private JLabel sourceLabel;

  private JList sourceList;

  private SortedListModel sourceListModel;

  private JList destList;

  private SortedListModel destListModel;

  private JLabel destLabel;

  private JButton addButton;

  private JButton removeButton;


  public DualListBox() {
    initScreen();
  }

  public String getSourceChoicesTitle() {
    return sourceLabel.getText();
  }

  public void setSourceChoicesTitle(String newValue) {
    sourceLabel.setText(newValue);
  }

  public String getDestinationChoicesTitle() {
    return destLabel.getText();
  }

  public void setDestinationChoicesTitle(String newValue) {
    destLabel.setText(newValue);
  }

  public void clearSourceListModel() {
    sourceListModel.clear();
  }

  public void clearDestinationListModel() {
    destListModel.clear();
  }

  public void addSourceElements(ListModel newValue) {
    fillListModel(sourceListModel, newValue);
  }

  public void setSourceElements(ListModel newValue) {
    clearSourceListModel();
    addSourceElements(newValue);
  }

  public void addDestinationElements(ListModel newValue) {
    fillListModel(destListModel, newValue);
  }

  private void fillListModel(SortedListModel model, ListModel newValues) {
    int size = newValues.getSize();
    for (int i = 0; i < size; i++) {
      model.add(newValues.getElementAt(i));
    }
  }

  public void addSourceElements(Object newValue[]) {
    fillListModel(sourceListModel, newValue);
  }

  public void setSourceElements(Object newValue[]) {
    clearSourceListModel();
    addSourceElements(newValue);
  }

  public void addDestinationElements(Object newValue[]) {
    fillListModel(destListModel, newValue);
  }

  private void fillListModel(SortedListModel model, Object newValues[]) {
    model.addAll(newValues);
  }

  public Iterator sourceIterator() {
    return sourceListModel.iterator();
  }

  public Iterator destinationIterator() {
    return destListModel.iterator();
  }

  public void setSourceCellRenderer(ListCellRenderer newValue) {
    sourceList.setCellRenderer(newValue);
  }

  public ListCellRenderer getSourceCellRenderer() {
    return sourceList.getCellRenderer();
  }

  public void setDestinationCellRenderer(ListCellRenderer newValue) {
    destList.setCellRenderer(newValue);
  }

  public ListCellRenderer getDestinationCellRenderer() {
    return destList.getCellRenderer();
  }

  public void setVisibleRowCount(int newValue) {
    sourceList.setVisibleRowCount(newValue);
    destList.setVisibleRowCount(newValue);
  }

  public int getVisibleRowCount() {
    return sourceList.getVisibleRowCount();
  }

  public void setSelectionBackground(Color newValue) {
    sourceList.setSelectionBackground(newValue);
    destList.setSelectionBackground(newValue);
  }

  public Color getSelectionBackground() {
    return sourceList.getSelectionBackground();
  }

  public void setSelectionForeground(Color newValue) {
    sourceList.setSelectionForeground(newValue);
    destList.setSelectionForeground(newValue);
  }

  public Color getSelectionForeground() {
    return sourceList.getSelectionForeground();
  }

  private void clearSourceSelected() {
    Object selected[] = sourceList.getSelectedValues();
    for (int i = selected.length - 1; i >= 0; --i) {
      sourceListModel.removeElement(selected[i]);
    }
    sourceList.getSelectionModel().clearSelection();
  }

  private void clearDestinationSelected() {
    Object selected[] = destList.getSelectedValues();
    for (int i = selected.length - 1; i >= 0; --i) {
      destListModel.removeElement(selected[i]);
    }
    destList.getSelectionModel().clearSelection();
  }

  private void initScreen() {
    setBorder(BorderFactory.createEtchedBorder());
    setLayout(new GridBagLayout());
    sourceLabel = new JLabel(INGREDIENTES_DISPONIVEIS);
    JButton button = new JButton("Buscar");
    add(button, new GridBagConstraints(1, 3, 1, 2, 0, .25,
        GridBagConstraints.CENTER, GridBagConstraints.NONE,
        EMPTY_INSETS, 0, 0));
    button.addActionListener(new PrintListener());

    sourceListModel = new SortedListModel();
    sourceList = new JList(sourceListModel);
    add(sourceLabel, new GridBagConstraints(0, 0, 1, 1, 0, 0,
        GridBagConstraints.CENTER, GridBagConstraints.NONE,
        EMPTY_INSETS, 0, 0));
    add(new JScrollPane(sourceList), new GridBagConstraints(0, 1, 1, 5, .5,
        1, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
        EMPTY_INSETS, 0, 0));

    addButton = new JButton(ADD_BUTTON_LABEL);
    add(addButton, new GridBagConstraints(1, 2, 1, 2, 0, .25,
        GridBagConstraints.CENTER, GridBagConstraints.NONE,
        EMPTY_INSETS, 0, 0));
    addButton.addActionListener(new AddListener());
    removeButton = new JButton(REMOVE_BUTTON_LABEL);
    add(removeButton, new GridBagConstraints(1, 4, 1, 2, 0, .25,
        GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(
            0, 5, 0, 5), 0, 0));
    removeButton.addActionListener(new RemoveListener());

    destLabel = new JLabel(INGREDIENTES_SELECIONADOS);
    destListModel = new SortedListModel();
    destList = new JList(destListModel);
    add(destLabel, new GridBagConstraints(2, 0, 1, 1, 0, 0,
        GridBagConstraints.CENTER, GridBagConstraints.NONE,
        EMPTY_INSETS, 0, 0));
    add(new JScrollPane(destList), new GridBagConstraints(2, 1, 1, 5, .5,
        1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
        EMPTY_INSETS, 0, 0));
  }

  public static void main(String args[]) {
    JFrame f = new JFrame("Dual List Box Tester");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    List<IngredienteVo> listaIngredientes = new ArrayList<IngredienteVo>();
    DualListBox dual = new DualListBox();
    Map<String, IngredienteVo> mapCodigoIngredientes = new HashMap();
    int i = 0;
    IngredienteDao ingredienteDao = new IngredienteDao();

    listaIngredientes = ingredienteDao.getIngredientesList();

    String[] myArray = new String[listaIngredientes.size()];

    for (IngredienteVo IngredienteVo : listaIngredientes) {
        myArray[i] = IngredienteVo.getNome();
        i++;

        mapCodigoIngredientes.put(IngredienteVo.getNome(), IngredienteVo);
    }

    dual.addSourceElements(myArray);

    f.getContentPane().add(dual, BorderLayout.CENTER);
    f.setSize(400, 300);
    f.setVisible(true);
  }

  private class AddListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      Object selected[] = sourceList.getSelectedValues();
      addDestinationElements(selected);
      clearSourceSelected();
    }
  }

  private class RemoveListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      Object selected[] = destList.getSelectedValues();
      addSourceElements(selected);
      clearDestinationSelected();
    }
  }

    class PrintListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
      int selected[] = destList.getSelectedIndices();
      System.out.println("Selected Elements:  ");

      for (int i = 0; i < destList.getModel().getSize(); i++) {
        Object element = destList.getModel().getElementAt(i);
        System.out.println("Item - " + element);
      }
    }
  }
}

class SortedListModel extends AbstractListModel {

  SortedSet model;

  public SortedListModel() {
    model = new TreeSet();
  }

  public int getSize() {
    return model.size();
  }

  public Object getElementAt(int index) {
    return model.toArray()[index];
  }

  public void add(Object element) {
    if (model.add(element)) {
      fireContentsChanged(this, 0, getSize());
    }
  }

  public void addAll(Object elements[]) {
    Collection c = Arrays.asList(elements);
    model.addAll(c);
    fireContentsChanged(this, 0, getSize());
  }

  public void clear() {
    model.clear();
    fireContentsChanged(this, 0, getSize());
  }

  public boolean contains(Object element) {
    return model.contains(element);
  }

  public Object firstElement() {
    return model.first();
  }

  public Iterator iterator() {
    return model.iterator();
  }

  public Object lastElement() {
    return model.last();
  }

  public boolean removeElement(Object element) {
    boolean removed = model.remove(element);
    if (removed) {
      fireContentsChanged(this, 0, getSize());
    }
    return removed;
  }

}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Henry
  • 35
  • 5
  • 2
    Please don't dump 350 lines of code like this. Make a [mcve]. Refer also to [ask]. – Tunaki Jun 11 '16 at 22:43
  • 2
    `I found a example in internet that have 2 Jlists, i need to add a third, but i dont know cause there's no graphic interface` - well I hope you don't ask a question every time you find some code that doesn't do exactly what you want it to do. The point of code examples is for you to learn some basics and then modify it. If you want add another component to this panel, then I suggest you start by reading the section from the Swing tutorial on [How to Use GridBagLayout](http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html). It will explain how all the constraints are used. – camickr Jun 11 '16 at 22:44
  • 1
    Or the other option is to just add the JList to the frame itself. Then you can just add it to the `BorderLayout.PAGE_END` of the content pane. The tutorial also has a section on `How to Use a BorderLayout` which is the default layout manager of the content pane of the frame. – camickr Jun 11 '16 at 22:49

1 Answers1

1

Starting from the example cited here and in your previous question on this topic, and focusing on just the layout, add the relevant fields and components as shown below. Note how the GridBagConstraints are identical to those of the previous column except that gridx is now 3, representing the new fourth column.

image

private JList newList;
private SortedListModel newListModel;
…
private void initScreen() {
    …
    JLabel newLabel = new JLabel("More Choices");
    newListModel = new SortedListModel<>();
    newList = new JList(newListModel);
    add(newLabel, new GridBagConstraints(3, 0, 1, 1, 0, 0,
        GridBagConstraints.CENTER, GridBagConstraints.NONE,
        EMPTY_INSETS, 0, 0));
    add(new JScrollPane(newList), new GridBagConstraints(3, 1, 1, 5, .5,
        1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
        EMPTY_INSETS, 0, 0));
}

Later in main(), I would replace f.setsize() with f.pack() for the reasons discussed here.

public static void main(String args[]) {
    …
    f.add(dual, BorderLayout.CENTER);
    // f.setSize(400, 300);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
}

Also consider a nested layout, seen here.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045