java - 将 JPanel 保存为 png 文件

标签 java

我正在尝试实现一个工资单生成器。我已经让 GUI 在单独的 JPanel 上生成工资单。当我单击“另存为 PNG”按钮时,它当前将 Jpanel 保存为项目文件夹内的 png 文件。但我希望它在保存时能够指定文件路径和文件名。这是我到目前为止所做的事情。

public static BufferedImage getScreenShot(Component component) {
    BufferedImage image = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_RGB);
    component.paint(image.getGraphics());
    return image;
}

public void saveScreenShot(Component component, String fname) throws Exception {

    BufferedImage img = getScreenShot(component);
    ImageIO.write(img, "png", new File(fname));
}
private void SaveAsPNGButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                

    try {
        saveScreenShot(PaySlip, "My panel Image.png");
    } catch (Exception e) {

    }
}

我希望它类似于下面的代码。我用它来将 Jtable 中的搜索结果保存到文本文件中。

 private void Export2TextActionPerformed(java.awt.event.ActionEvent evt) {                                            

    try {
        JFileChooser fc = new JFileChooser();
        int option = fc.showSaveDialog(SearchEmployeeGUI.this);
        if (option == JFileChooser.APPROVE_OPTION) {
            try {
                String filename = fc.getSelectedFile().getName();
                String path = fc.getSelectedFile().getParentFile().getPath();

                int len = filename.length();
                String ext = "";
                String file = "";

                if (len > 4) {
                    ext = filename.substring(len - 4, len);
                }

                if (ext.equals(".txt")) {
                    file = path + "\\" + filename;
                } else {
                    file = path + "\\" + filename + ".txt";
                }
                FileWriter fw = new FileWriter(file);
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write("Employee ID       First Name      Last Name       Gender      Contact No      Email       Date of Join        Designation     Basic Salary");
                bw.newLine();
                bw.write("--------------------------------------------------------------------------------------------------------------------------------------------");
                bw.newLine();

                for (int i = 0; i < EmployeeTable.getRowCount(); i++) {
                    for (int j = 0; j < EmployeeTable.getColumnCount(); j++) {
                        bw.write(EmployeeTable.getModel().getValueAt(i, j) + "    ");
                    }
                    bw.newLine();

                }
                bw.close();
                fw.close();
                int answer = JOptionPane.showConfirmDialog(null, "Would you like to open the exported file?", "Successfully exported!", option);
                if (answer == JOptionPane.YES_OPTION) {
                    try {
                        Desktop dt = Desktop.getDesktop();
                        dt.open(new File(file));

                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(null, e);
                    }
                }

            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e);
            }
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}  

在这里我可以指定路径和文件名。我想要同样的“另存为png”按钮。但我不知道该怎么做。有人可以帮忙吗?提前致谢。

最佳答案

您可以使用JFileChooser

                String suggesteddir = ".";
            String EXTENSION = ".png";
            JFileChooser fileChooser = new JFileChooser(suggesteddir);
            JFrame choose = new JFrame();
            choose.setTitle("Save To ...");
             int status = fileChooser.showSaveDialog(choose);
            if (status == JFileChooser.APPROVE_OPTION) 
            {

                try 
                {
                    File selectedFile = fileChooser.getSelectedFile();
                    String newfile = selectedFile.getCanonicalPath();
                    if (!newfile.endsWith(EXTENSION)) {
                        newfile=newfile + EXTENSION;
                    }

                    ImageIO.write(img, "png", new File(newfile)); //write img to file

                } catch (IOException ex) {
                    ex.printStackTrace();

                }
            }

关于java - 将 JPanel 保存为 png 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30832866/

相关文章:

java - 在 java 中使用列表的运算符优先级

java - Lambda 表达式和嵌套数组

java - 继承会将类变成对象吗?

java - removeEventListener() 不是 Firebase Firestore 的一部分吗?

java - 在实体集合中查找所有 id 集合的最有效方法

java - 如何在 JDBC url 中访问 `classpath:` 的父级?

java - 在 Android 中加密和解密文件的任何优化方式

java - 如何从资源文件夹以外的外部路径加载 logback.xml 文件

java - 编辑器设计: Update Swing Components After Change

java - 有没有办法用其他数组初始化二维数组?