Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 选择JCombobox中的选项时更改JLists。全部放在一个容器里_Java_Swing_Jcombobox_Jlist - Fatal编程技术网

Java 选择JCombobox中的选项时更改JLists。全部放在一个容器里

Java 选择JCombobox中的选项时更改JLists。全部放在一个容器里,java,swing,jcombobox,jlist,Java,Swing,Jcombobox,Jlist,好的,容器加载所有JPanel,问题是在容器从clues()方法加载selectedItemIndex()后,我无法更改selectedItemIndex()以显示不同的线索列表,因为容器从一开始就加载所有内容 我该怎么做才能从JCombobox中选择不同的项索引,并使它们出现在包含JLists的JPanel中 我需要刷新一下吗 package crucigramaprograi; import java.awt.BorderLayout; import java.awt.Color; impo

好的,容器加载所有JPanel,问题是在容器从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) {

}

}
gramaprograi;
导入java.awt.BorderLayout;
导入java.awt.Color;
导入java.awt.Container;
导入java.awt.Dimension;
导入java.awt.FlowLayout;
导入java.awt.Font;
导入java.awt.GridLayout;
导入java.awt.Toolkit;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.awt.event.MouseEvent;
导入java.awt.event.MouseListener;
导入javax.swing.BorderFactory;
导入静态javax.swing.BorderFactory.createTitledBorder;
导入javax.swing.JButton;
导入javax.swing.JComboBox;
导入javax.swing.JFrame;
导入javax.swing.JLabel;
导入javax.swing.JList;
导入javax.swing.JPanel;
导入javax.swing.JTextField;
导入javax.swing.border.TitledBorder;
公共类Main扩展JFrame实现MouseListener{
集装箱;
公用干管(){
超级(“十字架”);
container=getContentPane();
container.setLayout(新的BorderLayout(1,1));
container.add(login(),BorderLayout.NORTH);
container.add(buttons(),BorderLayout.WEST);
container.add(线索(),BorderLayout.SOUTH);
container.add(createMatrix(crosswordPanel()),BorderLayout.CENTER);
container.add(eastPanel(),BorderLayout.EAST);
}
公共JPanel登录(){
JPanel loginPanel=新的JPanel();
loginPanel.setLayout(新的FlowLayout(1,15,50));
loginPanel.setVisible(true);
JTextField inputUserName=新的JTextField(15);
inputUserName.setPreferredSize(新维度(25,25));
inputUserName.setToolTipText(“Ingree su nombre para poder jugar”);
loginPanel.add(输入用户名);
JButton btenter=新的JButton(“Jugar!”);
b输入设置首选尺寸(新尺寸(80,25));
loginPanel.add(bEnter);
返回登录面板;
}
公共JPanel按钮(){
JPanel buttonPanel=新的JPanel();
按钮面板设置布局(新的流程布局(5,45,15));
按钮面板设置首选尺寸(新尺寸(250200));
按钮面板设置可见(真);
最终字符串类别[]={“动物”、“蒙多首府”、“El Clima”};
JComboBox crosswordCategories=新的JComboBox(类别);
crosswordCategories.setPreferredSize(新维度(150,20));
添加(纵横字谜类别);
JButton newGame=新JButton(“新朱伊戈”);
setPreferredSize(新维度(130,27));
setFont(新字体(“Tahoma”,Font.PLAIN,11));
按钮面板添加(新游戏);
JButton showChar=新JButton(“Reverar letra”);
setPreferredSize(新维度(130,27));
setFont(新字体(“Tahoma”,Font.PLAIN,11));
按钮面板添加(showChar);
JButton showWord=新JButton(“狂欢宫”);
设置首选尺寸(新尺寸(130,27));
setFont(新字体(“Tahoma”,Font.PLAIN,11));
按钮面板添加(showWord);
JButton verifyWord=新JButton(“Verificar palabra”);
验证Word.setPreferredSize(新维度(130,27));
verifyWord.setFont(新字体(“Tahoma”,Font.PLAIN,11));
按钮面板添加(验证字);
JButton revealAll=新JButton(“Solución”);
显示所有设置首选尺寸(新尺寸(130,27));
setFont(新字体(“Tahoma”,Font.PLAIN,11));
按钮面板添加(显示全部);
JLabel labelScore=新JLabel(“Puntuación:”);
labelScore.setFont(新字体(“Arial”,Font.BOLD,13));
按钮面板添加(标签核心);
返回按钮面板;
}
公共JPanel线索(){
JPanel线索=新的JPanel();
线索。设置布局(新的流程布局(3,1,1));
线索:setPreferredSize(新维度(200185));
线索。设置可见(真);
JList horizontalList=新JList(新对象[]{“ghdfghdfgh”,“dfhsdghsfgh”});
//setLayout(新的FlowLayout());
//水平列表。setPreferredSize(新维度(635180));
设置顺序(CreateTitleBorder(null,“Pistas Horizontales”,titleBorder.DEFAULT_对齐,titleBorder.DEFAULT_位置,null,Color.black));
添加(水平列表、边界布局、中心);
JList-verticalList=new-JList(新对象[]{“bnmvbnmbnm”,“werterter”});
//setLayout(新的FlowLayout());
//垂直规划师。设置首选尺寸(新尺寸(635180));
verticalList.setBorder(CreateTitleBorder(null,“Pistas Verticales”,TitleBorder.DEFAULT_对齐,TitleBorder.DEFAULT_位置,null,Color.black));
添加(垂直列表、边界布局、中心);
返回线索;
}
公共JPanel东面板(){
JPanel fill=新的JPanel();
fill.setLayout(新的FlowLayout(5,25,15));
填充。设置首选尺寸(新尺寸(50200));
fill.setVisible(true);
回填土;
}
公共JPanel crosswordPanel(){
JPanel crosswordPanel=新的JPanel();
crosswordPanel.setLayout(新的GridLayout(10,10,0,0));
crosswordPanel.setVisible(true);
返回纵横字谜面板;
}
公共JPanel createMatrix(JPanel crosswordPanel){
JPanel crosswordMatrix[][]=新JPanel[10][10];
对于(int i=0;iimport 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);
            }
        });
    }
}