swing - 如何在 JSF 页面中执行 Java Swing 代码

标签 swing jsf

大家好,我是 JSF 新手,

我已经创建了一个 java 文件,当用户按下 XHTML 页面上的按钮时我需要运行该文件,我该如何执行此操作?对于像我这样的初学者来说,还有什么好的 JSF 教程吗?谢谢:)

JAVA代码是一段简单的代码,允许用户选择一个txt文件然后打印它。

目的是创建一个网络应用程序以允许打印文档

这是我希望运行的 JAVA 代码:

import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.print.*;
import java.text.*;
import java.io.*;
import javax.swing.*;
import java.util.List;
import java.util.ArrayList;

public class PrintText implements Printable {

    private String text; // Constructor argument for AttributedString.

    // Below the code will allow the user to select a file and then print out the contents of the file
    public static void main(String[] args) throws IOException {
        new PrintText();
    }

    public PrintText() {
        EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }

                    //selects the file
                    JFileChooser chooser = new JFileChooser();
                    chooser.showOpenDialog(null);
                    File file = chooser.getSelectedFile();
                    String filename = file.getName();
                    //System.out.println("You have selected: " + filename);  testing to see if file seleected was right
                    String path = file.getAbsolutePath();

                    //Reads contents of file into terminal 
                    //FileReader fr = new FileReader("filename");
                    // FileReader fr = new FileReader("D:/Documents/" + "filename")); 

                    BufferedReader br = null;
                    try {
                        br = new BufferedReader(new FileReader(path));
                        StringBuilder stringBuilder = new StringBuilder();
                        String line;
                        while ((line = br.readLine()) != null) {
                            //System.out.println(line); //This is now not needed, was used to test to see if the contents was recieved corrently
                            stringBuilder.append(line).append("\n");
                        }
                        text = stringBuilder.toString();;

                        printer();
                    } catch (IOException exp) {
                        exp.printStackTrace();
                    } finally {
                        try {
                            br.close();
                        } catch (Exception e) { e.printStackTrace(); }
                    }
                    //fr.close(); 
                }
            });
    }
    //Testing 
    //private static final String mText = 
    //    "This is a test to see if this text will be printed "; //This works perfectly fine
    //AttributedString mStyledText = new AttributedString(mText);
    /**
     * Print a single page containing some sample text.
     */
    public void printer() {

        /* Get the representation of the current printer and 
         * the current print job.
         */
        PrinterJob printerJob = PrinterJob.getPrinterJob();
        /* Build a book containing pairs of page painters (Printables)
         * and PageFormats. 
         */
        Book book = new Book();
        book.append(this, new PageFormat());
        /* Set the object to be printed (the Book) into the PrinterJob.
         * Doing this before bringing up the print dialog allows the
         * print dialog to correctly display the page range to be printed
         * and to dissallow any print settings not appropriate for the
         * pages to be printed.
         */
        printerJob.setPageable(book);
        /* Show the print dialog to the user. If the user cancels the print dialog then false
         * is returned. If true is returned we go ahead and print.
         */
        boolean doPrint = printerJob.printDialog();
        if (doPrint) {
            try {
                printerJob.print();
            } catch (PrinterException exception) {
                System.err.println("Printing error: " + exception);
            }
        }
    }

    /**
     * Print a page of text.
     */
    public int print(Graphics g, PageFormat format, int pageIndex) {

        AttributedString mStyledText = new AttributedString(text);

        Graphics2D g2d = (Graphics2D) g;
        g2d.translate(format.getImageableX(), format.getImageableY());
        g2d.setPaint(Color.black);// Sets text colour
        Point2D.Float pen = new Point2D.Float();
        AttributedCharacterIterator charIterator = mStyledText.getIterator();
        LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator, g2d.getFontRenderContext());
        float wrappingWidth = (float) format.getImageableWidth();
        while (measurer.getPosition() < charIterator.getEndIndex()) {
            TextLayout layout = measurer.nextLayout(wrappingWidth);
            pen.y += layout.getAscent();
            float dx = layout.isLeftToRight() ? 0 : (wrappingWidth - layout.getAdvance());
            layout.draw(g2d, pen.x + dx, pen.y);
            pen.y += layout.getDescent() + layout.getLeading();
        }
        return Printable.PAGE_EXISTS;
    }
}

最佳答案

对于实现选择要上传的文件然后使用 JSF 显示它的具体功能要求,您的方向是错误的。

您正在尝试使用 Swing/AWT 选择文件。虽然这对于基于桌面的应用程序来说可能确实是正确的方法,但对于基于 Web 的应用程序来说这完全是错误的方法。在基于 Web 的应用程序中,Java/JSF 代码在 Web 服务器中运行并生成一堆 HTML/CSS/JS 代码,这些代码通过网络发送到 Web 浏览器,而 Web 浏览器最终又运行所有获得的 HTML/CSS/JS 代码。因此请注意,Java/JSF 运行在运行 Web 服务器的物理机中。因此,Swing/AWT 也会在运行 Web 服务器的物理机中运行,因此绝对不会在运行 Web 浏览器的物理机中运行。基本上,当 Swing/AWT 显示某些 UI 时,它将显示在附加到 Web 服务器的监视器中,而不是附加到 Web 浏览器的监视器中。

您需要使用 HTML/CSS/JS 而不是 Java 来实现您的功能需求。您需要以这样的方式编写 JSF 代码,使其生成适合所需任务的特定 HTML/CSS/JS 代码。

在您的具体情况下,您想要上传文件并显示其内容。在 HTML 世界中,文件选择器由 <input type="file"> 表示。元素。在标准 JSF 中,您可以使用 <h:inputFile>组件生成该 HTML。这是一个启动示例:

<h:form enctype="multipart/form-data">
    <h:inputFile value="#{bean.file}" />
    <h:commandButton value="Submit" action="#{bean.process}" />
    <h:messages />
</h:form>
<pre>#{bean.content}</pre>

用这个bean

private Part file; // +getter+setter
private String content; // +getter

public void process() throws IOException {
    content = IOUtils.toString(file.getInputstream(), "UTF-8");
}

(注意:IOUtils 是 Apache Commons IO 的一部分,因此上述代码按原样工作)

另请参阅:

关于swing - 如何在 JSF 页面中执行 Java Swing 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55773100/

相关文章:

java - 如何将用户在一种方法中获得的值用于同一类中的其他方法

JSF EL - 用默认值替换 null

jsf - 无缘无故调用@PostConstruct方法

java - 错误的值被发送到转换器 JSF

java - 尝试在Java中播放声音: NullPointerException

java - 如何访问同一应用程序的不同线程中的所有JFrame

java - 处理长时间运行的 EDT 任务(f.i. TreeModel 搜索)

java - 在 JList 中选择行时,字符串未正确写入 JTextField/Area

spring - faces-config.xml 中的 EL 解析器

javascript - Primefaces 以编程方式触发的事件触发两次