如何在鼠标单击时将JPanel从其他类添加到另一个JPanel

时间:2013-07-28 03:09:18

标签: java swing jpanel

当我点击JLabel时,我一直试图将一个JPanel(这里称为'BulletinsJPanel')填充到一个被称为'Home.java'的类中,其中包含一个textfield(此处称为'readerSetTxtJTextField')。 ReaderPanel位于另一个名为“Reader.java”的类中,该类应该读取文本文件的内容并使用一行文本填充JTextField对象。

我正在使用netbeans,它没有向我显示任何代码错误亮点。

我非常感谢帮助显示文本字段'readerSetTxtJTextField'。非常感谢。

继承我的代码:

// The class Home

package Panels;
public class Home extends javax.swing.JPanel {
    // Here's a method in the class 'Home.java' which should populate 'BulletinsJPanel' with the contents
    private void MouseClickedList(java.awt.event.MouseEvent evt) {
        BulletinsJPanel.add(Reader.readerMouseClickedList());
        BulletinsJPanel.revalidate();
        BulletinsJPanel.repaint();
    }
}

// Now the class Reader below

package Database;
public class Reader {
    public static JTextField readerSetTxtJTextField;

    public static JTextField readerMouseClickedList() {                                  
        try {
            // Our code
            String fileURL = "/D:/TestFile.txt/";
            List<String[]> matches = new ArrayList<String[]>();
            String finalText;

            FileInputStream fileInputStream = new FileInputStream(fileURL);
            DataInputStream dataInputStream = new DataInputStream(fileInputStream);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dataInputStream));

            String stringLine;

            while((stringLine = bufferedReader.readLine()) != null) {
                String splittable = "[\\s]", splitLenth = "{955}";
                if(stringLine.startsWith("2013001")) {
                    String[] splits = stringLine.split(splittable + splitLenth );

                    matches.add(splits);
                }
            }
            dataInputStream.close();

            for(String[] items : matches) {
                int itemsLength = items.length;
                int i;
                for(i = 0; i <= itemsLength; i++) {
                    finalText = (items[i]);

                    readerSetTxtJTextField = new JTextField();
                    readerSetTxtJTextField.setText(finalText);
                }

            }

        } catch (Exception e) {
            // Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
        return readerSetTxtJTextField;
    }                                 

}

1 个答案:

答案 0 :(得分:2)

作为错误的快速解决方法,请更改:

for(i = 0; i <= itemsLength; i++)

for(i = 0; i < itemsLength; i++)