选择JCombobox中的选项时更改JLists。全部装在容器中

时间:2015-04-22 22:20:18

标签: java swing jcombobox jlist

好的,容器加载所有JPanels,问题是在容器从clues()方法加载selectedItemIndex()之后,我无法更改selectedItemIndex()以显示自容器以来的不同线索列表从一开始就加载所有内容。

我可以做什么,以便我可以从JCombobox中选择不同的项目索引,并让它们出现在包含JLists的JPanel中?

我需要做一些刷新吗?

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) {

}

}

对不起大码。

1 个答案:

答案 0 :(得分:1)

下面我已经创建了一个小示例程序供您用作指南。

三个要点是:

  1. 提供所需的组件类范围。正如您在我的示例中所看到的,myComboBoxmyList被声明为具有类范围。我也在类范围内有列表模型(myListModel),只是为了方便使用。

  2. 在你的组合框上实现一个监听器。这意味着代码将在相应事件发生时运行。我碰巧使用ItemListener,但您也可以使用ActionListenerThis question也实现了两者。

  3. ListModel使用JLists,然后您只需更改模型中的项目,列表就会处理这些更改。

  4. 有关更多信息,请查看以下有用链接:


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