Java 将新选项卡添加到JTabbedPane,然后刷新该JTabbedPane

Java 将新选项卡添加到JTabbedPane,然后刷新该JTabbedPane,java,refresh,jtabbedpane,Java,Refresh,Jtabbedpane,我在刷新JTabbedPane时遇到问题。 按下类JPaneladDataBaddShortcut中的addGroup按钮后,应用程序将创建一个新文件(工作正常) 选项卡的数量取决于这些文件的数量,所以如果我再添加一个文件,应用程序需要重新计算该数量(在readFiles()中设置的静态变量“intFileCount”),然后将最后一个选项卡添加到JTabbedPane 简而言之,readFiles()设置“intFileCount”(选项卡/文件的数量),readTabNames()设置str

我在刷新JTabbedPane时遇到问题。 按下类JPaneladDataBaddShortcut中的addGroup按钮后,应用程序将创建一个新文件(工作正常)

选项卡的数量取决于这些文件的数量,所以如果我再添加一个文件,应用程序需要重新计算该数量(在readFiles()中设置的静态变量“intFileCount”),然后将最后一个选项卡添加到JTabbedPane

简而言之,readFiles()设置“intFileCount”(选项卡/文件的数量),readTabNames()设置strTabName[](选项卡名称),然后tabbedPanne()返回添加了所有选项卡的JTabbedPane

我尝试将这3种方法添加到按钮操作侦听器和重新验证+重新绘制JTabbedPane中,但都不起作用。在此之前,我曾尝试使用removeALL(),但效果并不理想

可能是我在添加文件时设置“intFileCount”变量时说错了(jpaneladtabddshortcut class->addGroup action listener part和saveTabNames()方法)。这可能是我的错误,但经过很长时间的思考,我认为更有经验的人应该看看这个

当我重新运行应用程序时,新选项卡已正确添加

下面是代码(我尽可能地对所有内容进行注释):

公共类SkrotyAplikacjiTabbed2{
//主JFrame类+在显示JFrame()之前
类mainJFrame扩展了JFrame
{
public mainJFrame()抛出FileNotFoundException,IOException
{
//JFrame出现之前要做的事情
在显示jframe()之前;
//添加JTabbedPane
jTabbedPane=tabbedPane();
添加(jTabbedPane);
//JFrame属性
片名(“Skróty Aplikacji”);
设置大小(1024768);
可设置大小(假);
setLocationRelativeTo(空);
setDefaultCloseOperation(关闭时退出);
}
}
//JPanel仅用作背景
类JBackgroundPanel扩展了JPanel
{
专用缓冲图像img;
JBackgroundPanel()
{
尝试
{
img=ImageIO.read(新文件(“2.jpg”);
} 
捕获(IOE异常)
{
}
}
@凌驾
受保护组件(图形g)
{
超级组件(g);
g、 drawImage(img,0,0,getWidth(),getHeight(),this);
}
}
//Jpanel包含一对(按钮+jtextarea)->添加到ContainerPanel
类addShortcut扩展了JPanel
{
私有添加快捷方式(图标p、字符串s、最终字符串strin)
{
GridBagLayout gbLayout2=新的GridBagLayout();
GridBagConstraints d=新的GridBagConstraints();
super.setLayout(gbLayout2);
p=尺寸图标(p);
JButton btn1=新JButton(p);
btn1.设置首选尺寸(新尺寸(50,50));
JTextArea ShortcutDescription=新的JTextArea();
ShortcutDescription.setLineWrap(true);
ShortcutDescription.setWrapStyleWord(true);
ShortcutDescription.setText;
btn1.addActionListener(新ActionListener()
{
@凌驾
已执行的公共无效操作(操作事件e)
{
尝试
{
Runtime.getRuntime().exec(“cmd.exe/c start”+strin);
} 
捕获(IOEX异常)
{
Logger.getLogger(SkrotyAplikacjiTabbed2.class.getName()).log(Level.SEVERE,null,ex);
}
}
});
ShortcutDescription.set不透明(false);
此.set不透明(false);
setFont(新字体(“Verdana”,Font.BOLD,10));
ShortcutDescription.setForeground(颜色:白色);
//nazwaIkonki.getViewport().setOpaque(false);
ShortcutDescription.setEditable(false);
d、 gridy=0;
添加(btn1,d);
d、 gridy=1;
本.新增(简图说明,d);
} 
}
//JPanel用于添加新选项卡/文件
类jpaneladtabadshortcut扩展了JPanel
{
//多丹妮·科波南托
JTextField newTabName=newjtextfield(“Nazwa Nowej Grupy”);;
JTextField newShortcutDescription=新JTextField(“Nazwa Nowego Skrótu”);
JButton addGroup=新JButton(“Dodaj Grupę”);
JButton addShortcut=新JButton(“Dodaj Skrót”);
JPANELADTABADDSHORTCUT()
{
//乌斯塔维亚尼·维米亚罗
newTabName.setPreferredSize(新尺寸(260,20));
addGroup.setPreferredSize(新维度(130,20));
setPreferredSize(新维度(260,20));
addShortcut.setPreferredSize(新维度(130,20));
//乌斯塔维尼·齐翁基
newTabName.setFont(新字体(“Verdana”,字体粗体,10));
setFont(新字体(“verdana”,Font.BOLD,10));
//乌斯塔维尼·维多克兹诺西
此.set不透明(false);
//杜达贾西·诺瓦·格鲁普
//刷新扎克拉德
addGroup.addActionListener(新的ActionListener()
{
@凌驾
已执行的公共无效操作(操作事件e)
{
//多达纳·纳兹瓦·格鲁比
strTabName[intFileCount]=newTabName.getText();
//Tworzenie pliku dla danej grupy
文件f=新文件(Integer.toString(intFileCount)+“.txt”);
尝试
{
f、 createNewFile();
} 
捕获(IOEX异常)
{
Logger.getLogger(SkrotyAplikacjiTabbed2.class.getName()).log(Level.SEVERE,null,ex);
}
//扎皮斯·格鲁比·多普利库
尝试
{
saveTabNames();
} 
捕获(IOEX异常)
{
Logger.getLogger(SkrotyAplikacjiTabbed2.class.getName()).log(Level.SEVERE,null,ex);
}
//zmienna grup zwiekszona o+1
public class SkrotyAplikacjiTabbed2 {
// main JFrame Class + beforeShowingJFrame()
class mainJFrame extends JFrame 
    {
    public mainJFrame() throws FileNotFoundException, IOException
        {
        //things to do before JFrame shows up
        beforeShowingJFrame();

        //Add JTabbedPane
        jTabbedPane = tabbedPane();
        add(jTabbedPane);

        //JFrame Properties
        setTitle("Skróty Aplikacji");
        setSize(1024, 768);
        setResizable(false);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        }
    }
// JPanel used only as background
class JBackgroundPanel extends JPanel 
    {
    private BufferedImage img;
    JBackgroundPanel()
        {
        try
            {
            img = ImageIO.read(new File("2.jpg"));
            } 
        catch (IOException e) 
            {
            }
        }
    @Override
    protected void paintComponent(Graphics g) 
        {
        super.paintComponent(g);
        g.drawImage(img, 0, 0, getWidth(),getHeight(),this);
        }
    }
// Jpanel containing pair of (button+jtextarea) -> added to containterPanel
class addShortcut extends JPanel
    {
    private addShortcut(Icon p,String s,final String strin) 
        {
        GridBagLayout gbLayout2 = new GridBagLayout();
        GridBagConstraints d = new GridBagConstraints();
        super.setLayout(gbLayout2);

        p=resizeIcon(p);
        JButton btn1 = new JButton(p); 
        btn1.setPreferredSize(new Dimension (50,50));
        JTextArea ShortcutDescription = new JTextArea();
        ShortcutDescription.setLineWrap(true);
        ShortcutDescription.setWrapStyleWord(true);
        ShortcutDescription.setText(s);

        btn1.addActionListener(new ActionListener() 
            {
            @Override
            public void actionPerformed(ActionEvent e) 
                {
                try 
                    {
                    Runtime.getRuntime().exec("cmd.exe /c start "+ strin);
                    } 
                catch (IOException ex) 
                    {
                    Logger.getLogger(SkrotyAplikacjiTabbed2.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
        ShortcutDescription.setOpaque(false);
        this.setOpaque(false);
        ShortcutDescription.setFont(new Font("Verdana",Font.BOLD,10));
        ShortcutDescription.setForeground(Color.WHITE);
        //nazwaIkonki.getViewport().setOpaque(false); 
        ShortcutDescription.setEditable(false);
        d.gridy=0;
        this.add(btn1,d);
        d.gridy=1;
        this.add(ShortcutDescription,d);
        } 
    }
// JPanel used to add new Tabbs/Files
class jPanelAddTabAddShortcut extends JPanel
    {
    //Dodanie komponentow
    JTextField newTabName= new JTextField("Nazwa Nowej Grupy");;   
    JTextField newShortcutDescription = new JTextField("Nazwa Nowego Skrótu");
    JButton addGroup = new JButton("Dodaj Grupę"); 
    JButton addShortcut = new JButton("Dodaj Skrót"); 

        jPanelAddTabAddShortcut() 
        {
        //Ustawianie Wymiarow
        newTabName.setPreferredSize(new Dimension(260,20));
        addGroup.setPreferredSize(new Dimension (130,20));
        newShortcutDescription.setPreferredSize(new Dimension(260,20));
        addShortcut.setPreferredSize(new Dimension(130,20));
        //Ustawienie czcionki
        newTabName.setFont(new Font("Verdana",Font.BOLD,10));
        newShortcutDescription.setFont(new Font("verdana",Font.BOLD,10));
        //Ustawienie widocznosci
        this.setOpaque(false);

        //JButton dodajacy nowa grupe 
        //Refresh zakladek
        addGroup.addActionListener(new ActionListener() 
            {
            @Override
            public void actionPerformed(ActionEvent e) 
                {
                // dodana nazwa grupy
                strTabName[intFileCount] = newTabName.getText();
                //Tworzenie pliku dla danej grupy
                File f=new File(Integer.toString(intFileCount)+".txt");
                try 
                    {
                    f.createNewFile();
                    } 
                catch (IOException ex) 
                    {
                    Logger.getLogger(SkrotyAplikacjiTabbed2.class.getName()).log(Level.SEVERE, null, ex);
                    }
                //Zapis grupy do pliku
                try 
                    {
                    saveTabNames();
                    } 
                catch (IOException ex) 
                    {
                    Logger.getLogger(SkrotyAplikacjiTabbed2.class.getName()).log(Level.SEVERE, null, ex);
                    }
                //zmienna grup zwiekszona o +1
                intFileCount++;
                }
            });

        this.add(newTabName);
        this.add(addGroup);
        this.add(addShortcut);
        this.add(newShortcutDescription);
        } 
    }
    SkrotyAplikacjiTabbed2() throws FileNotFoundException, IOException
        {
        mainJFrame=new mainJFrame();
        mainJFrame.setVisible(true);
        }
    public static void main(String[] args) throws FileNotFoundException, IOException 
        {
        SkrotyAplikacjiTabbed2 skrotyAplikacjiTabbed2 = new SkrotyAplikacjiTabbed2();
        }
    // resize icon to 40,40
    Icon resizeIcon(Icon d)
        {
        Image img = iconToImage(d);
        Image newimg = img.getScaledInstance(40,40,java.awt.Image.SCALE_SMOOTH);
        d= new ImageIcon(newimg);
        return d;
        }
    // icon -> image
    Image iconToImage(Icon icon)
        {
        if (icon instanceof ImageIcon)
            {
            return ((ImageIcon)icon).getImage();
            }
        else
            {
            int w = icon.getIconWidth();
            int h = icon.getIconHeight();
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice gd = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gd.getDefaultConfiguration();
            BufferedImage image = gc.createCompatibleImage(w,h);
            Graphics2D g = image.createGraphics();
            icon.paintIcon(null, g, h, h);
            g.dispose();
            return image;
            }
        } 
    // returns JTabbedPane with all Tabbs added
    JTabbedPane tabbedPane()
        {
        JTabbedPane tempJTabbedPane = new JTabbedPane();
        int j;
        for(j=0;j<intFileCount;j++) 
            {
            tempJTabbedPane.addTab(strTabName[j],jBackgroundPanel[j]);
            }
        return tempJTabbedPane;
        }
    // things to do before JFrame shows up
    void beforeShowingJFrame() throws FileNotFoundException, IOException
        {
        readFiles();
        readTabNames();
        settingPanels();
        addingTabComponents();
        }
    // read Files (sets static intFileCount and intTabComponentCount)
    // gets necessary info about shortcut(link,description,icon etc)
    void readFiles() throws FileNotFoundException, IOException
        {
        for(intFileCount=0;intFileCount<1000;intFileCount++)
            {
            String a;
            a = Integer.toString(intFileCount);
            File f = new File(a+".txt");
            if(f.exists())
                {
                intTabComponentCount[intFileCount]=0;
                Scanner scanner = new Scanner(f);
                while (scanner.hasNextLine())
                    {
                    strLinksList[intFileCount][intTabComponentCount[intFileCount]]=scanner.nextLine();
                    strFileList[intFileCount][intTabComponentCount[intFileCount]]= new File(strLinksList[intFileCount][intTabComponentCount[intFileCount]]);
                    iconFileIcon[intFileCount][intTabComponentCount[intFileCount]]= fsv.getSystemIcon(strFileList[intFileCount][intTabComponentCount[intFileCount]]);
                    strShortcutDescription[intFileCount][intTabComponentCount[intFileCount]]=scanner.nextLine();
                    scanner.nextLine();
                    intTabComponentCount[intFileCount]++;     
                    }
                }
            else break;
            }
        }
    // read each tab name from a file
    void readTabNames() throws FileNotFoundException
        {
        Scanner scanner = new Scanner(fileGroupFile);
        for (int j=0; j<intFileCount;j++)
            {
            if (scanner.hasNextLine())
                {
                strTabName[j]=scanner.nextLine();   
                }    
            }
        }
    // adds jScrollPane[j] to jBackgroundPane[j]
    // then adds containerPanel[j] to jScrollPane[j]
    // sets panels properties
    void settingPanels()
        {
        int j;
        for(j=0;j<intFileCount;j++)
            {
            //inicjalizacja paneli
            jBackgroundPanel[j] = new JBackgroundPanel();
            containterPanel[j] = new JPanel();

            //wlasciwosci paneli
            containterPanel[j].setVisible(true);
            containterPanel[j].setLayout(new GridBagLayout());
            containterPanel[j].setOpaque(false);
            jBackgroundPanel[j].setLayout(new BorderLayout());
            jScrollPane[j] = new JScrollPane(containterPanel[j]);
            jScrollPane[j].setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
            jScrollPane[j].setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            jScrollPane[j].setPreferredSize(new Dimension(530,386));
            jScrollPane[j].setOpaque(false);
            jScrollPane[j].getViewport().setOpaque(false);
            jBackgroundPanel[j].add(jScrollPane[j],BorderLayout.WEST);           
            jBackgroundPanel[j].add(new jPanelAddTabAddShortcut(),BorderLayout.SOUTH);  
            }
        }    
    // saves edited Tab names to file
    public void saveTabNames() throws IOException
        {
        PrintWriter printWriter = new PrintWriter(fileGroupFile);
        for (int j=0; j<intFileCount+1;j++)
            {
            printWriter.println(strTabName[j]);
            printWriter.flush();
            }
        }
    // add pair of (jbutton+jtextarea) to chosen containterPanel[]
    // using method addShortcut
    void addingTabComponents()
    {
    int j,k;
    for (j=0;j<intFileCount;j++)    
        {
        v=0;
        q=0;
        for (k=0;k<intTabComponentCount[j];k++)
            {
            c.gridx=v;
            c.gridy=q;
            c.insets= new Insets(5,5,5,5);
            containterPanel[j].add(new addShortcut(iconFileIcon[j][k],strShortcutDescription[j][k],strLinksList[j][k]),c);
            if(v<4)
                {
                v++;
                }
            if (v==4)
                {
                v=0;
                q++;
                }
            }
        }
    }

    //readFiles() Variables
    static int intFileCount=0; // counts tabbs
    static int[] intTabComponentCount= new int[1000]; // counts components added to related tab

    //GridBagLayout Variables
    int v=0,q=0; // gridx and gridy
    GridBagConstraints c = new GridBagConstraints();

    //Tab Variables
    String[] strTabName = new String [1000];   // tab names 
    final File fileGroupFile = new File("grupy.txt"); // file containig tab names
    File fileNewShortcutFile;  // variable storing temporary file which will be set as a new tab

    //Shortcut Componnents Variables
    String[][] strShortcutDescription = new String [1000][1000]; // description below shortcut
    Icon[][] iconFileIcon = new Icon[1000][1000]; // shortcut icon
    String[][] strLinksList = new String[1000][1000]; // shortcut link
    File[][] strFileList = new File[1000][1000]; // File linked to related shortcut

    //Other Variables
    JBackgroundPanel[] jBackgroundPanel = new JBackgroundPanel[1000]; // background JPanel
    JScrollPane[] jScrollPane = new JScrollPane[1000]; // added to background Jpanel
    JPanel[] containterPanel = new JPanel[1000]; // added to JScrollPane; contains shortcuts + their descriptions
    FileSystemView fsv = FileSystemView.getFileSystemView(); // used to get file icon
    JTabbedPane jTabbedPane;  // JTabbedPane
    mainJFrame mainJFrame;  // main JFrame
}