-1

Ok, the container loads all JPanels, the problem is after the container loads a selectedItemIndex() from the clues() method, I can't change the selectedItemIndex() to show a different list of clues since the container loads everything from the start.

What can I do so that I can select the different item indexes from the JCombobox and for them to appear in the JPanel that contains the JLists?

Do I need to do some sort of refresh?

package crucigramaprograi;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import static javax.swing.BorderFactory.createTitledBorder;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

public class Main extends JFrame implements MouseListener {

Container container;


public Main(){
    super("Crucigrama");
    container = getContentPane();
    container.setLayout(new BorderLayout(1, 1));
    container.add(login(),BorderLayout.NORTH);
    container.add(buttons(),BorderLayout.WEST);
    container.add(clues(),BorderLayout.SOUTH);
    container.add(createMatrix(crosswordPanel()),BorderLayout.CENTER);
    container.add(eastPanel(),BorderLayout.EAST);


}


public JPanel login(){

    JPanel loginPanel = new JPanel();
    loginPanel.setLayout(new FlowLayout(1, 15, 50));
    loginPanel.setVisible(true);

    JTextField inputUserName = new JTextField(15);
    inputUserName.setPreferredSize(new Dimension(25, 25));
    inputUserName.setToolTipText("Ingrese su nombre para poder jugar");
    loginPanel.add(inputUserName);

    JButton btnEnter = new JButton("Jugar!");
    btnEnter.setPreferredSize(new Dimension(80,25));
    loginPanel.add(btnEnter);

    return loginPanel;
}

public JPanel buttons(){

    JPanel buttonsPanel = new JPanel();
    buttonsPanel.setLayout(new FlowLayout(5, 45, 15));
    buttonsPanel.setPreferredSize(new Dimension(250, 200));
    buttonsPanel.setVisible(true);

    final String categories[] = {"Animales", "Capitales del Mundo", "El Clima"};
    JComboBox crosswordCategories = new JComboBox(categories);
    crosswordCategories.setPreferredSize(new Dimension(150,20));
    buttonsPanel.add(crosswordCategories);


    JButton newGame = new JButton("Nuevo Juego");
    newGame.setPreferredSize(new Dimension(130,27));
    newGame.setFont(new Font("Tahoma", Font.PLAIN, 11));
    buttonsPanel.add(newGame);

    JButton showChar = new JButton("Revelar letra");
    showChar.setPreferredSize(new Dimension(130,27));
    showChar.setFont(new Font("Tahoma", Font.PLAIN, 11));
    buttonsPanel.add(showChar);

    JButton showWord = new JButton("Revelar palabra");
    showWord.setPreferredSize(new Dimension(130,27));
    showWord.setFont(new Font("Tahoma", Font.PLAIN, 11));
    buttonsPanel.add(showWord);

    JButton verifyWord = new JButton("Verificar palabra");
    verifyWord.setPreferredSize(new Dimension(130,27));
    verifyWord.setFont(new Font("Tahoma", Font.PLAIN, 11));
    buttonsPanel.add(verifyWord);

    JButton revealAll = new JButton("Solución");
    revealAll.setPreferredSize(new Dimension(130,27));
    revealAll.setFont(new Font("Tahoma", Font.PLAIN, 11));
    buttonsPanel.add(revealAll);

    JLabel labelScore = new JLabel("Puntuación:");
    labelScore.setFont(new Font("Arial", Font.BOLD, 13));
    buttonsPanel.add(labelScore);

    return buttonsPanel;
}

public JPanel clues(){

    JPanel clues = new JPanel();
    clues.setLayout(new FlowLayout(3, 1, 1));
    clues.setPreferredSize(new Dimension(200, 185));
    clues.setVisible(true);

    JList horizontalList = new JList(new Object[]{"ghdfghdfgh","dfhsdghsfgh"});
    //horizontalList.setLayout(new FlowLayout());
    //horizontalList.setPreferredSize(new Dimension(635, 180));
    horizontalList.setBorder(createTitledBorder(null, "Pistas Horizontales",TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, Color.black));
    clues.add(horizontalList,BorderLayout.CENTER);


    JList verticalList = new JList(new Object[]{"bnmvbnmbnm","wertertert"});
    //verticalList.setLayout(new FlowLayout());
    //verticalList.setPreferredSize(new Dimension(635, 180));
    verticalList.setBorder(createTitledBorder(null, "Pistas Verticales",TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, Color.black));
    clues.add(verticalList,BorderLayout.CENTER);

    return clues;
}


public JPanel eastPanel(){

    JPanel fill = new JPanel();
    fill.setLayout(new FlowLayout(5, 25, 15));
    fill.setPreferredSize(new Dimension(50, 200));
    fill.setVisible(true);

    return fill;
}


public JPanel crosswordPanel(){

    JPanel crosswordPanel = new JPanel();
    crosswordPanel.setLayout(new GridLayout(10,10,0,0));
    crosswordPanel.setVisible(true);

    return crosswordPanel;
}

public JPanel createMatrix(JPanel crosswordPanel){

JPanel crosswordMatrix [][] = new JPanel [10][10]; 

    for (int i = 0; i < crosswordMatrix.length ; i++) {
        for (int j = 0; j < crosswordMatrix[0].length; j++) {

            crosswordMatrix[i][j] = new JPanel();
            crosswordMatrix[i][j].setBackground(Color.black);
            crosswordMatrix[i][j].setBorder(BorderFactory.createLineBorder(Color.black, 1));
            crosswordMatrix[i][j].addMouseListener(this);


            crosswordPanel.add(crosswordMatrix[i][j]);
        }
    }

return crosswordPanel;
}


public static void main(String[] args) {

    Main guiWindow = new Main();

    /*Sets window size according to the computer resolution. 
      Window size is not hardcoded.*/
    Toolkit screenSize = Toolkit.getDefaultToolkit();
    int width = screenSize.getScreenSize().width * 4/5;
    int height = screenSize.getScreenSize().height * 4/5;
    guiWindow.setSize(width, height);
    guiWindow.setLocationRelativeTo(null);

    //guiWindow.setResizable(false);
    guiWindow.setVisible(true);
    guiWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}


public static String[] getVerticalClues(int category) {

    String verticalClues[] = new String[6];
    switch (category) {

        case 1:

            verticalClues[0] = "1. Mamífero acuático muy inteligente y simpático";
            verticalClues[1] = "2. Muy grande con colmillos, orejas enormes y trompa";
            verticalClues[2] = "3. Felino pintado a rayas, muy feroz";
            verticalClues[3] = "4. Es el animal con el cuello más largo";
            verticalClues[4] = "5. Al trote o al galope era el medio de transporte de indios y vaqueros";
            verticalClues[5] = "6. Como lleva un caparazón muy pesado, siempre va muy despacio";

            break;

        case 2:

            verticalClues[0] = "1. Los cristianos se refugiaban en…";
            verticalClues[1] = "2. Religión que en un principio fue perseguida pero después paso a ser la religión oficial del imperio romano";
            verticalClues[2] = "3. Era la moneda Romana";
            verticalClues[3] = "4. Era la principal actividad económica Romana";
            verticalClues[4] = "5. Nombre de la lengua del Imperio Romano";
            verticalClues[5] = "6. Nombre del principal dios romano en la época pre cristiana";

            break;

        case 3:

            verticalClues[0] = "1. Océano que baña a Islandia";
            verticalClues[1] = "2. País por el que pasa el rio Elba";
            verticalClues[2] = "3. Capital del país situado a la derecha de Suecia";
            verticalClues[3] = "4. País cuya capital es Zagreb";
            verticalClues[4] = "5. Rio que divide a Rusia en 2 mitades";
            verticalClues[5] = "6. Capital del país que se encuentra entre Venezuela y Ecuador";

            break;
    }

    return verticalClues;
}

public static String[] getHorizontalClues(int category) {
    String horizontalClues[] = new String[6];

    switch (category) {

        case 1:

            horizontalClues[0] = "1. Tiene bigotes y siete vidas";
            horizontalClues[1] = "2. Oso grande, blanco y negro y es originario de Asia";
            horizontalClues[2] = "3. Tiene alas grandes, coloridas y sale de un capullo";
            horizontalClues[3] = "4. Dicen que es el mejor amigo del hombre";
            horizontalClues[4] = "5. El rey de la selva, con melena larga";
            horizontalClues[5] = "6. Vive en el agua y tiene una boca larga y llena de dientes";

            break;

        case 2:

            horizontalClues[0] = "1. Emperador que  concedió la libertad religiosa a los cristianos";
            horizontalClues[1] = "2. Nombre que recibe el conjunto de leyes romanas";
            horizontalClues[2] = "3. El español, francés, portugués, catalán, italiano y rumano se derivaron del…";
            horizontalClues[3] = "4. El culto domestico era dirigido por el…";
            horizontalClues[4] = "5. La arquitectura y escultura romana fue influenciada por la cultura…";
            horizontalClues[5] = "6. El descenso de la producción agrícola es una causa…";

            break;

        case 3:

            horizontalClues[0] = "1. Montes que están entre Francia, Suiza e Italia";
            horizontalClues[1] = "2. País cuya capital es Bagdad";
            horizontalClues[2] = "3. País que está a la par de Haití";
            horizontalClues[3] = "4. Tercer isla más grande del mundo";
            horizontalClues[4] = "5. Cabo en la península de Somalia";
            horizontalClues[5] = "6. Capital de Bolivia";

            break;
    }

    return horizontalClues;
}





//@Override
public void mouseClicked(MouseEvent e) {

}

@Override
public void mousePressed(MouseEvent e) {

}

@Override
public void mouseReleased(MouseEvent e) {

}

@Override
public void mouseEntered(MouseEvent e) {

}

@Override
public void mouseExited(MouseEvent e) {

}

}

Sorry for the large code.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
fredy21
  • 41
  • 1
  • 8
  • Make the `JList` or it's `ListModel` an instance field and update those – MadProgrammer Apr 22 '15 at 22:33
  • *"Sorry for the large code."* Instead of apologizing, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). – Andrew Thompson Apr 23 '15 at 01:41

1 Answers1

1

Below I've created a small example program for you to use as a guide.

The three main points are:

  1. Give the required components class scope. As you can see in my example, myComboBox and myList are declared to have class scope. I also have the list model (myListModel) at class scope just for ease of use.

  2. Implement a listener on your combobox. This means that the code will be run when the corresponding event occurs. I happened to use a ItemListener but you can also use an ActionListener. This question also has implementation of both.

  3. Use a ListModel for your JLists then you can just alter the items in the model and the list will handle those changes.

For more information look at these helpful links:


import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

/**
 * SelectionExample
 */
public class SelectionExample extends JFrame
{

    // ------  Point 1 --------- //
    private DefaultListModel<String> myListModel;
    private JComboBox<String> myComboBox;
    private JList<String> myList;

    public SelectionExample()
    {
        super("An Example");
        initComponents();
    }

    private void initComponents()
    {
        JPanel jp = new JPanel(new BorderLayout(5,5));
        jp.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        myComboBox = new JComboBox<String>(new String[]{"Numbers", "Letters", "Punctuation"});

        // ------ Point 2 --------- //
        myComboBox.addItemListener(new ItemListener()
        {
            @Override
            public void itemStateChanged(ItemEvent e)
            {
                if(e.getStateChange() == ItemEvent.SELECTED)
                {
                    String[] jListItems = getItemsForSelection(myComboBox.getSelectedIndex());
                    // ------  Point 3 --------- //
                    myListModel.removeAllElements();
                    for(String s : jListItems)
                        myListModel.addElement(s);
                }
            }
        });

        jp.add(myComboBox, BorderLayout.NORTH);

        myListModel = new DefaultListModel<String>();
        myList = new JList<String>(myListModel);

        JScrollPane jsp = new JScrollPane();
        jsp.add(myList);
        jsp.setViewportView(myList);

        jp.add(jsp, BorderLayout.CENTER);

        add(jp);
        pack();
    }

    private String[] getItemsForSelection(int selection)
    {
        switch(selection)
        {
            case 0:
                return new String[]{"1","2","3","4","5"};
            case 1:
                return new String[]{"A","B","C","D","E"};
            case 2:
                return new String[]{"!","@","#","$","%"};
            default:
                return null;
        }
    }


    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                SelectionExample se = new SelectionExample();
                se.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                se.setVisible(true);
            }
        });
    }
}
Community
  • 1
  • 1
Java Devil
  • 10,629
  • 7
  • 33
  • 48