2017-07-08 53 views
0

我正在创建一个GUI,允许用户输入佛罗里达州的湖泊信息,然后才能显示湖泊信息。我希望显示信息位于JOptionPane.showMessageDialog中,该对话框可以滚动所有湖名的ArrayList。我能够将湖泊添加到ArrayList中,但它们不会显示在我的JOptionPane中,并且它是空白的。我知道它正在读取ArrayList中的某些内容,因为它正在打开该窗口。下面是代码片段中的代码,因为整个事情都是疯狂的。在具有滚动功能的JTextArea中显示数组

public static ArrayList<Lakes> lake = new ArrayList<Lakes>(); 
private JTextArea textAreaDisplay; 
private JScrollPane spDisplay; 

// this is called in my initComponent method to create both 
    textAreaDisplay = new JTextArea(); 

    for (Object obj : lake) 
    { 
     textAreaDisplay.append(obj.toString() + " "); 
    } 

    spDisplay = new JScrollPane(textAreaDisplay); 

    textAreaDisplay.setLineWrap(true); 
    textAreaDisplay.setWrapStyleWord(true); 
    spDisplay.setPreferredSize(new Dimension(500, 500)); 

    // this is called in my createEvents method. After creating lakes in the database 
    // it will display the else statement but it is empty 

    btnDisplayLake.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      try 
      { 
       if (lake.size() == 0) 
       { 
        JOptionPane.showMessageDialog(null, "No Lakes in database!"); 
       } 
       else 
        JOptionPane.showMessageDialog(null, spDisplay, "Display Lakes", JOptionPane.YES_NO_OPTION); 
      } 
      catch (Exception e1) 
      { 

      } 

     } 
    }); 

谢谢你提供的任何帮助。我已经在这方面花了几天脑筋。能够完成其他的事情,但回到这个问题。

+1

1)为了更好地提供帮助,请发布[MCVE]或[简短自包含正确示例](http://www.sscce.org/)。 2)不要忽视例外!他们告诉我们到底出了什么问题。除非实现日志记录,否则至少要调用'Throwable.printStackTrace()' –

回答

1

一些明显的问题:

textAreaDisplay = new JTextArea(); 

一个JTextArea应该像代码创建:

textAreaDisplay = new JTextArea(5, 20); 

通过指定行/列文本区域就能计算出自己的最佳尺寸。当文本区域的首选大小大于滚动窗格的大小时,应显示滚动条。

spDisplay.setPreferredSize(new Dimension(500, 500)); 

请勿使用setPreferredSize()。滚动区域将根据文本区域的首选大小计算其首选大小。

textAreaDisplay.append(obj.toString() + " "); 

我想你希望每个湖展现在另一条线路,所以我会追加"\n"而不是空间。

0

我在设置textAreaDisplay之前已经将任何内容输入到ArrayList中,并且在输入任何内容后它不会再次运行。我将for循环移到了actionPerformed事件中,现在运行良好。

btnDisplayLake.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      try 
      { 
       for (Object obj : lake) 
       { 
        textAreaDisplay.append(obj.toString() + "\n"); 
       } 
       if (lake.size() == 0) 
       { 
        JOptionPane.showMessageDialog(null, "No Lakes in database!"); 
       } 
       else 
        JOptionPane.showMessageDialog(null, spDisplay, "Display Lakes", JOptionPane.YES_NO_OPTION); 
      } 
      catch (Exception e1) 
      {