Java 如何将我自己的代码插入Netbeans Gui Builder?

Java 如何将我自己的代码插入Netbeans Gui Builder?,java,swing,user-interface,netbeans,jeditorpane,Java,Swing,User Interface,Netbeans,Jeditorpane,我在网上找到了代码:我根据自己的需要编辑了代码,请看: import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.io.IOException; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; imp

我在网上找到了代码:我根据自己的需要编辑了代码,请看:

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.io.IOException;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

public class Emotes extends JEditorPane {

    public Emotes() {
        super();
        this.setEditorKit(new StyledEditorKit());
        this.initListener();
    }

    private void replace (String text, StyledDocument doc, ImageIcon icon, int start, String what) throws BadLocationException
    {
        int i = text.indexOf(what);
        while(i >= 0) 
        {
            final SimpleAttributeSet attrs = new SimpleAttributeSet(doc.getCharacterElement(start+i).getAttributes());
            if (StyleConstants.getIcon(attrs) == null)
            {
                StyleConstants.setIcon(attrs, icon);
                doc.remove(start+i, what.length());
                doc.insertString(start+i,what, attrs);
            }
            i = text.indexOf(what, i+what.length());
        }
    }

    private void initListener() {
        getDocument().addDocumentListener(new DocumentListener(){
            @Override
            public void insertUpdate(DocumentEvent event) {
                final DocumentEvent e=event;
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        if (e.getDocument() instanceof StyledDocument) {
                            try {
                                StyledDocument doc=(StyledDocument)e.getDocument();
                                int start= Utilities.getRowStart(Emotes.this,Math.max(0,e.getOffset()-1));
                                int end=Utilities.getWordStart(Emotes.this,e.getOffset()+e.getLength());
                                String text=doc.getText(start, end-start);


                                replace(text, doc, createEmoticon("wink.png"), start, ";)");
                                replace(text, doc, createEmoticon("wink.png"), start, "<wink>");
                                replace(text, doc, createEmoticon("sad.png"), start, ":(");
                                replace(text, doc, createEmoticon("sad.png"), start, "<sad>");
                                replace(text, doc, createEmoticon("smile.png"), start, ":)");
                                replace(text, doc, createEmoticon("smile.png"), start, "<smile>");

                            } catch (BadLocationException e1) {
                                e1.printStackTrace();
                            }
                        }
                    }
                });
            }
            @Override
            public void removeUpdate(DocumentEvent e) {
            }
            @Override
            public void changedUpdate(DocumentEvent e) {
            }
        });
    }

    static ImageIcon createEmoticon(String icon)
    {
        BufferedImage img = null;
        try
        {
            img = ImageIO.read(new File(icon));
            Graphics g = img.getGraphics();
            ((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        }catch (IOException ex)
        {
        }
        return new ImageIcon(img);
    }
}
导入java.awt.Graphics;
导入java.awt.Graphics2D;
导入java.awt.RenderingHints;
导入java.io.IOException;
导入javax.swing.*;
导入javax.swing.event.DocumentEvent;
导入javax.swing.event.DocumentListener;
导入javax.swing.text.*;
导入java.awt.image.buffereImage;
导入java.io.File;
导入javax.imageio.imageio;
公共类Emotes扩展了TorPane{
公众情绪(){
超级();
this.setEditorKit(新StyledEditorKit());
this.initListener();
}
私有void replace(字符串文本、样式文档文档、图像图标、int start、字符串what)引发BadLocationException
{
int i=text.indexOf(what);
而(i>=0)
{
final SimpleAttributeSet attrs=新的SimpleAttributeSet(doc.getCharacterElement(start+i).getAttributes());
if(StyleConstants.getIcon(attrs)==null)
{
设置图标(属性,图标);
doc.remove(start+i,what.length());
doc.insertString(start+i,what,attrs);
}
i=text.indexOf(what,i+what.length());
}
}
私有void initListener(){
getDocument().addDocumentListener(新DocumentListener()){
@凌驾
公共作废插入更新(DocumentEvent事件){
最终文件事件e=事件;
SwingUtilities.invokeLater(新的Runnable(){
@凌驾
公开募捐{
if(例如getDocument()instanceof StyledDocument){
试一试{
StyledDocument文档=(StyledDocument)e.getDocument();
int start=Utilities.getRowStart(Emotes.this,Math.max(0,e.getOffset()-1));
int end=Utilities.getWordStart(Emotes.this,e.getOffset()+e.getLength());
String text=doc.getText(start,end-start);
替换(文本、文档、createEmoticon(“wink.png”)、开始“;)”;
替换(文本、文档、createEmoticon(“wink.png”)、开始“”;
替换(文本、文档、createEmoticon(“sad.png”)、开始“:(”;
替换(文本、文档、createEmoticon(“sad.png”)、开始“”;
替换(文本、文档、createEmoticon(“smile.png”)、开始“:”;
替换(文本、文档、createEmoticon(“smile.png”)、开始“”;
}捕获(BadLocationException e1){
e1.printStackTrace();
}
}
}
});
}
@凌驾
公共作废移除更新(文档事件e){
}
@凌驾
公共作废更改日期(记录事件e){
}
});
}
静态图像图标createEmoticon(字符串图标)
{
BuffereImage img=null;
尝试
{
img=ImageIO.read(新文件(图标));
Graphics g=img.getGraphics();
((Graphics2D)g).setRenderingHint(renderingHits.KEY_ANTIALIASING,renderingHits.VALUE_ANTIALIAS_ON);
}捕获(IOEX异常)
{
}
返回新的图像图标(img);
}
}
这很有效。但我在Netbeans中创建了一个新的GUI(JDialog窗口),上面有JEditorPane,我想在JDialog窗口中使用此功能:

但它根本不想工作。当我输入“:”时,它在图像中不会改变

请尝试运行该代码:

public class NewJDialog extends javax.swing.JDialog {

    /** Creates new form NewJDialog */
    public NewJDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jEditorPane1 = new Emotes();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jScrollPane1.setViewportView(jEditorPane1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(51, 51, 51)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(20, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                NewJDialog dialog = new NewJDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JEditorPane jEditorPane1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration
}
公共类NewJDialog扩展了javax.swing.JDialog{
/**创建新表单NewJDialog*/
public NewJDialog(java.awt.Frame父级,布尔模式){
超级(父级、模态);
初始化组件();
}
/**此方法从构造函数中调用,以
*初始化表单。
*警告:请勿修改此代码。此方法的内容为
*始终由表单编辑器重新生成。
*/
@抑制警告(“未选中”)
// 
私有组件(){
jScrollPane1=newjavax.swing.JScrollPane();
jEditorPane1=新表情();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE\u ON\u CLOSE);
jScrollPane1.setViewportView(jEditorPane1);
javax.swing.GroupLayout=newjavax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(布局);
layout.setHorizontalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0,400,短。最大值)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1,javax.swing.GroupLayout.DEFAULT\u SIZE,376,Short.MAX\u值)
.addContainerGap()))
);
layout.setVerticalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0,300,短。最大值)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(51,51,51)
.addComponent(jScrollPane1,javax.swing.GroupLayout.PREFERRED\u SIZE,229,javax.swing.GroupLayout.PREFERRED\u SIZE)
.addContainerGap(20,简称最大值)))
);
包装();
}// 
/**
*@param指定命令行参数
*/
公共静态void main(字符串参数[]){
/*设置Nimbus的外观和感觉*/
//
/*如果Nimbus(在JavaSE6中引入)不可用,请使用de
        img = ImageIO.read(Emotes.class.getResourceAsStream(icon));