简体   繁体   English

根据数组创建对象

[英]Creating objects depending on an Array

I've got an Array holding the amount of directories located in an another directory. 我有一个数组,其中包含位于另一个目录中的目录数量。 However my problem is I have to create a JPanel for each folder. 但是我的问题是我必须为每个文件夹创建一个JPanel

For example: 例如:

File folder = new File("...");
File[] listOfFiles = folder.listFiles(); <- this contains the folders ({"folder1","folder2","folder3",...}).

Now I don't know how to fix this. 现在我不知道如何解决这个问题。

Some code I have written: 我写的一些代码:

SystemAPI sapi = new SystemAPI(); <- custom written API  
File folder = new File(sapi.getHomeDir+"\\Documents\\*programname*\\default");  
File[] listOfFiles = folder.listFiles();

    try{
        for (int i = 0; i < listOfFiles.length; i++) {
            if (listOfFiles[i].isFile()) {
                System.out.println(listOfFiles[i].getName());
            } else if (listOfFiles[i].isDirectory()) {
                System.out.println(listOfFiles[i].getName());
            }
        }   
    }catch(Exception a){
        JOptionPane.showMessageDialog(null, "Error Occurred", "Error Dialog", JOptionPane.ERROR_MESSAGE);
    }

You could do something like this (I made it using a layout provided by MigLayout but that can be changed) 你可以这样做(我使用MigLayout提供的布局,但可以更改)

import javax.swing.*;
import java.awt.*;
import net.miginfocom.swing.MigLayout;
import java.io.*;
import java.util.ArrayList;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.JTabbedPane;

public class SimpleGUI
{
    public JFrame myMainWindow = new JFrame("Multtiple directories");

    JPanel[] guiPanelS = new JPanel[1000];
    JScrollPane[] guiJSP = new JScrollPane[1000];
    public JTabbedPane tabbedPane = new JTabbedPane();
    int pI = 0;
    String mainDirectory = "C:/Users/Daniel/Dropbox/Programming/Code/Notepad++/Java/Stack Overflow";
    String mainDirectoryName = new File(mainDirectory).getName();
    int indentForMainPanel = 30;
    String parseIndent = Integer.toString(indentForMainPanel);
    String lastDirOpen = mainDirectory;
    String lastDirOpenBut = mainDirectory;
    ArrayList<File> directoriesList = new ArrayList<File>();

    public void runGUI()
    {
        myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        myMainWindow.setLayout(new GridLayout(1,1));

        listFilesHD(new File(mainDirectory),mainDirectoryName);

        final boolean showTabsHeader = false;
        tabbedPane.setUI(new javax.swing.plaf.basic.BasicTabbedPaneUI()
        {
            @Override
            protected int calculateTabAreaHeight(int tabPlacement, int horizRunCount, int maxTabHeight)
            {
                if(showTabsHeader)
                {
                    return super.calculateTabAreaHeight(tabPlacement, horizRunCount, maxTabHeight);
                }
                else
                {
                    return 0;
                }
            }
            protected void paintTabArea(Graphics g,int tabPlacement,int selectedIndex){}
        });

        myMainWindow.getContentPane().add(tabbedPane);
        tabbedPane.addChangeListener(new CustomChangeListener());

        myMainWindow.setVisible(true);
        myMainWindow.setBounds(10,10,500,500);
    }

    public void listFilesHD(File f,String dName)
    {
        MigLayout layout = new MigLayout("wrap", "[grow]");
        guiPanelS[pI] = new JPanel(layout);
        guiJSP[pI] = new JScrollPane(guiPanelS[pI]);
        JLabel currentDir = new JLabel("Current Directory: "+dName);
        guiPanelS[pI].add(currentDir,"align center");
        JLabel DirectoryName = new JLabel(dName);
        DirectoryName.setForeground(Color.BLUE);
        guiPanelS[pI].add(DirectoryName);
        File[] listOfFiles = f.listFiles();

        JLabel[] listsValues = new JLabel[listOfFiles.length];
        JButton[] tabSwitch = new JButton[listOfFiles.length];

        int i=0;
        int i2=0;
        for(File fileTemp:listOfFiles)
        {
            listsValues[i] = new JLabel(listOfFiles[i].getName());
            if(listOfFiles[i].isDirectory())
            {
                directoriesList.add(listOfFiles[i]);
                tabSwitch[i2] = new JButton(listOfFiles[i].getName());
                tabSwitch[i2].setOpaque(false); //These remove the button filling and border
                tabSwitch[i2].setContentAreaFilled(false);
                tabSwitch[i2].setBorder(null);
                tabSwitch[i2].setFocusable(false);
                tabSwitch[i2].setForeground(Color.RED);
                tabSwitch[i2].addActionListener(new openNewPaneActionListener());
                guiPanelS[pI].add(tabSwitch[i2],"gapLeft 30");
                i2++;
            }
            else if(listOfFiles[i].isFile())
            {
                guiPanelS[pI].add(listsValues[i],"gapLeft 30");
            }

            i++;
        }

        tabbedPane.addTab(f.getAbsolutePath(),guiJSP[pI]);
        guiJSP[pI].getVerticalScrollBar().setUnitIncrement(16);
        pI++;
    }

    public void listFilesSubD(File f,String dName,String dPath, String homeDirectory)
    {
        MigLayout layout = new MigLayout("wrap", "[grow]");
        guiPanelS[pI] = new JPanel(layout);
        guiJSP[pI] = new JScrollPane(guiPanelS[pI]);
        JLabel currentDir = new JLabel("Current Directory: "+dName);
        guiPanelS[pI].add(currentDir,"align center");
        JButton homeDirectoryName = new JButton(homeDirectory);
        homeDirectoryName.setForeground(Color.BLUE);
        homeDirectoryName.addActionListener(new backListener());
        homeDirectoryName.setOpaque(false); //These remove the button filling and border
        homeDirectoryName.setContentAreaFilled(false);
        homeDirectoryName.setBorder(null);
        homeDirectoryName.setFocusable(false);
        guiPanelS[pI].add(homeDirectoryName);

        if(!new File(lastDirOpenBut).getName().equals(mainDirectoryName))
        {
            JButton lastDirectoryName = new JButton(new File(lastDirOpenBut).getName());
            lastDirectoryName.setForeground(Color.GREEN);
            lastDirectoryName.addActionListener(new upOneListener());
            lastDirectoryName.setOpaque(false);
            lastDirectoryName.setContentAreaFilled(false);
            lastDirectoryName.setBorder(null);
            lastDirectoryName.setFocusable(false);
            guiPanelS[pI].add(lastDirectoryName,"gapLeft 30");

            File[] listOfFiles = f.listFiles();

            JLabel[] listsValues = new JLabel[listOfFiles.length];
            JButton[] tabSwitch = new JButton[listOfFiles.length];

            int i=0;
            int i2=0;
            for(File fileTemp:listOfFiles)
            {
                listsValues[i] = new JLabel(listOfFiles[i].getName());
                if(listOfFiles[i].isDirectory())
                {
                    directoriesList.add(listOfFiles[i]);
                    tabSwitch[i2] = new JButton(listOfFiles[i].getName());
                    tabSwitch[i2].setOpaque(false);
                    tabSwitch[i2].setContentAreaFilled(false);
                    tabSwitch[i2].setBorder(null);
                    tabSwitch[i2].setFocusable(false);
                    tabSwitch[i2].setForeground(Color.RED);
                    tabSwitch[i2].addActionListener(new openNewPaneActionListener());
                    guiPanelS[pI].add(tabSwitch[i2],"gapLeft 60");
                    i2++;
                }
                else if(listOfFiles[i].isFile())
                {
                    guiPanelS[pI].add(listsValues[i],"gapLeft 60");
                }
                i++;
            }
        }
        else
        {
            File[] listOfFiles = f.listFiles();

            JLabel[] listsValues = new JLabel[listOfFiles.length];
            JButton[] tabSwitch = new JButton[listOfFiles.length];

            int i=0;
            int i2=0;
            for(File fileTemp:listOfFiles)
            {
                listsValues[i] = new JLabel(listOfFiles[i].getName());
                if(listOfFiles[i].isDirectory())
                {
                    directoriesList.add(listOfFiles[i]);
                    tabSwitch[i2] = new JButton(listOfFiles[i].getName());
                    tabSwitch[i2].setOpaque(false); //These remove the button filling and border
                    tabSwitch[i2].setContentAreaFilled(false);
                    tabSwitch[i2].setBorder(null);
                    tabSwitch[i2].setFocusable(false);
                    tabSwitch[i2].setForeground(Color.RED);
                    tabSwitch[i2].addActionListener(new openNewPaneActionListener());
                    guiPanelS[pI].add(tabSwitch[i2],"gapLeft 30");
                    i2++;
                }
                else if(listOfFiles[i].isFile())
                {
                    guiPanelS[pI].add(listsValues[i],"gapLeft 30");
                }
                i++;
            }
        }

        if(tabbedPane.indexOfTab(dPath)==-1)
        {
            tabbedPane.addTab(dPath,guiJSP[pI]);
        }

        guiJSP[pI].getVerticalScrollBar().setUnitIncrement(16);
        pI++;
    }

    public static void main(String[] args)
    {
        SimpleGUI sG = new SimpleGUI();
        sG.runGUI();
    }

    class openNewPaneActionListener implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            lastDirOpenBut = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
            String butSrcTxt = "";
            Object source = e.getSource();
            if (source instanceof JButton) 
            {
                JButton btn = (JButton)source;
                butSrcTxt = btn.getText();
            }

            boolean tF = false;
            File fMain = new File("");
            for(File f:directoriesList)
            {
                if(f.getName().equals(butSrcTxt))
                {
                    fMain = f;
                    tF = true;
                }
            }

            if(tF)
            {
                if(tabbedPane.indexOfTab(fMain.getAbsolutePath())==-1)
                {
                    listFilesSubD(fMain, butSrcTxt, fMain.getAbsolutePath(),mainDirectoryName);
                }

                tabbedPane.setSelectedIndex(tabbedPane.indexOfTab(fMain.getAbsolutePath()));
            }

        }
    }

    class upOneListener implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            tabbedPane.setSelectedIndex(tabbedPane.indexOfTab(lastDirOpen));
        }
    }

    class CustomChangeListener implements ChangeListener
    {
        @Override
        public void stateChanged(ChangeEvent e)
        {
            lastDirOpen = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
            int endIndex = lastDirOpen.lastIndexOf(Character.toString((char) 92));
            if (endIndex != -1)
            {
                lastDirOpen = lastDirOpen.substring(0, endIndex);
            }
        }
    }

    class backListener implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            tabbedPane.setSelectedIndex(0);
        }
    } 
}

The code produces a simple GUI (as shown in the picture below). 代码生成一个简单的GUI(如下图所示)。 The picture shows the directory currently open. 图为当前打开的目录。 The blue button is the home directory which opens when clicked. 蓝色按钮是单击时打开的主目录。 The files in the open directory are black. 打开目录中的文件为黑色。 The sub directories are red buttons which when clicked open a new panel with the contents of that directory and finally the green button is the directory above the one currently open. 子目录是红色按钮,单击时打开一个包含该目录内容的新面板,最后绿色按钮是当前打开的目录上方的目录。 For example if you are in C:\\\\D\\B when the green button is clicked you would enter C:\\\\D . 例如,如果在单击绿色按钮时位于C:\\\\D\\B ,则输入C:\\\\D

All the panels are on a JScrollPane so you do not need to worry about the amount of files in the directory. 所有面板都在JScrollPane因此您无需担心目录中的文件数量。 You can now adapt this code to your own. 您现在可以将此代码调整为您自己的代码。 I would also suggest you get MigLayout if you don't have it already so you can see how this little program works. 如果你还没有它,我建议你得到MigLayout ,这样你就可以看到这个小程序是如何运作的。

编译代码的Pic

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM