2015-04-22 43 views
-1

好吧,容器加載所有JPanels,問題是在容器從clues()方法加載selectedItemIndex()之後,我無法更改selectedItemIndex()以顯示不同的線索列表,因爲容器從一開始就加載所有內容。選擇JCombobox選項時更改JLists。所有容器都是白色的

我該怎麼做才能從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) { 

} 

} 

對不起,大碼。

+0

做了'JList',或者它*「ListModel」是一個實例字段,並更新這些 – MadProgrammer

+0

*「對不起,對大代碼」。*代替道歉,發佈[MCVE](http://stackoverflow.com/help/mcve)(最小完整可驗證示例)或[SSCCE](http://www.sscce.org/)(簡短,獨立,正確的例子)。 –

回答

1

下面我創建了一個小例子程序供您作爲指導。

的三個要點是:

  1. 提供所需的組件類範圍。正如你在我的例子中看到的,myComboBoxmyList被聲明爲具有類作用域。爲了便於使用,我還在類範圍中使用了列表模型(myListModel)。

  2. 在組合框上實現監聽器。這意味着代碼將在相應的事件發生時運行。我碰巧使用ItemListener,但您也可以使用ActionListenerThis question也具有兩者的實現。

  3. 爲您的JLists使用ListModel,然後您可以更改模型中的項目,並且列表將處理這些更改。

欲瞭解更多信息,看看這些有用的鏈接:


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); 
      } 
     }); 
    } 
} 
相關問題