java - HyperLinkListener 取消并保存文件

标签 java html swing file-io jtextpane

问题:

  • 当我将文本 Pane 的 contentType 保留为 text/html 时,键入的文本会向右移动,例如:如果键入“asd”,则“消息:”会出现在左侧,“asd”出现在文本 Pane 的右侧

  • 添加文件时,如何为此编写一个HyperLinkListener。我在代码中注释了“保存”和“取消”。如何获取我单击的内容的名称(取消或保存),以便我可以为这两个链接编写适当的代码?

代码:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import java.awt.FlowLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import javax.swing.event.HyperlinkListener;
import javax.swing.event.HyperlinkEvent;

public class SampleTextPane extends JFrame {

    private JPanel contentPane;
    private JTextField textField;
    private JTextPane textPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    SampleTextPane frame = new SampleTextPane();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public SampleTextPane() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.CENTER);
        panel.setLayout(new BorderLayout(0, 0));

        JPanel panel_1 = new JPanel();
        panel.add(panel_1, BorderLayout.CENTER);
        panel_1.setLayout(new BorderLayout(0, 0));

        textPane = new JTextPane();
        textPane.addHyperlinkListener(new HyperlinkListener() {
            public void hyperlinkUpdate(HyperlinkEvent arg0) {

                // Cancel
                // To cancel the progress

                // Save
                // To save the file
            }
        });
        textPane.setEditable(false);
        textPane.setContentType("text/html");
        panel_1.add(textPane);

        JPanel panel_2 = new JPanel();
        panel.add(panel_2, BorderLayout.SOUTH);
        panel_2.setLayout(new BorderLayout(0, 0));

        textField = new JTextField();
        textField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent key) {
                if(key.getKeyCode()==KeyEvent.VK_ENTER){
                    if(!textField.getText().trim().isEmpty()){
                        sendMessage(textField.getText());
                        textField.setText("");
                    }
                }
            }
        });
        panel_2.add(textField);
        textField.setColumns(10);

        JButton btnNewButton = new JButton("+");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser fileChoose = new JFileChooser();
                int returnVal = fileChoose.showOpenDialog(getParent());
                if(returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fileChoose.getSelectedFile();
                    String desc = file.getName().trim();
                    sendFileToUser(file, desc);
                }
            }
        });
        panel_2.add(btnNewButton, BorderLayout.EAST);
    }

    protected void sendFileToUser(File file, String desc) {
        StyledDocument doc = textPane.getStyledDocument();
        SimpleAttributeSet set = new SimpleAttributeSet();
        StyleConstants.setForeground(set, Color.BLACK);
        StyleConstants.setBold(set, true);
        StyleConstants.setAlignment(set, StyleConstants.ALIGN_LEFT);
        try {
            doc.insertString(doc.getLength(), " File : "+desc, set);
            HTMLEditorKit editorKit = (HTMLEditorKit)textPane.getEditorKit();
            HTMLDocument doc1 = (HTMLDocument)textPane.getDocument();
            try {
                editorKit.insertHTML(doc1, doc.getLength(), "<a href=\"\">Save</a>   <a href=\"\">Cancel</a>\n", 0, 0, null);
            } catch (BadLocationException | IOException e) {
                e.printStackTrace();
            }
        } catch (BadLocationException e) {
            e.printStackTrace();
        }

    }

    protected void sendMessage(String text) {
        StyledDocument doc = textPane.getStyledDocument();
        SimpleAttributeSet set = new SimpleAttributeSet();
        StyleConstants.setForeground(set, Color.BLACK);
        StyleConstants.setBold(set, true);
        StyleConstants.setAlignment(set, StyleConstants.ALIGN_LEFT);
        try {
            doc.insertString(doc.getLength(), " Message : ", set);
            doc.insertString(doc.getLength(), text+"\n", textPane.getStyle(StyleContext.DEFAULT_STYLE));
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
    }

}

最佳答案

How do I get the name of what I click (Cancel or Save),

您是否指定了超链接的 URL?

JEditorPane API 显示了如何从 HyperlinkEvent 访问 URL 的示例。

关于java - HyperLinkListener 取消并保存文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22918928/

相关文章:

java - 将 Java Swing 应用程序转换为 Eclipse 插件

java - 如何使用 java 从 URL 下载 .zip 文件

java - Java中的倒三角形

java - 为什么 en_GB 语言环境认为 1 月 1 日是一年中的第 52 周?

java - 滚动到一个元素 selenium java

php - 动态计算php mysql结果总和

Java - 如何使图像消失

html - Bootstrap 网格布局不起作用

javascript - FormData 缺少提交的值 - 获取它,也许没有 SubmitEvent.submitter?

java - JTextArea.print() 打印空白页