2012-09-29 3 views
2

После долгих трудностей я получил работоспособность в щелчке. К сожалению, когда я меняю формат своего JTextPane на "text/html" и добавляю текст в JTextPane, моя кнопка исчезает. Я почти закончил с этой суровой любовницей. Может ли кто-нибудь помочь?Невозможно иметь компоненты в jtextpane, если установлено значение «text/html».

код следует ...

import java.awt.*; 
import javax.swing.*; 
import java.awt.Color; 
import javax.swing.JTextPane; 
import javax.swing.JButton; 
import java.applet.*; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 

public class jlabeltest extends Applet { 

    public void init() { 

     jlabeltest textPaneExample = new jlabeltest(); 
     textPaneExample.setSize(550, 300); 
     textPaneExample.setVisible(true); 
    } 


    public jlabeltest() { 

     JTextPane textPane = new JTextPane(); 
     textPane.setContentType("text/html"); 
     InlineB button = new InlineB("Button");  
     textPane.setText("<p color='#FF0000'>Cool!</p>"); 
     button.setAlignmentY(0.85f); 

     button.addMouseListener(new MouseAdapter() { 

     public void mouseReleased(MouseEvent e) { 

     if (e.isPopupTrigger()) { 

      JOptionPane.showMessageDialog(null,"Hello!"); 
      // Right Click 
     } 

     if (SwingUtilities.isLeftMouseButton(e)) { 

      JOptionPane.showMessageDialog(null,"Click!"); 
      // Left Click 
     } 
    } 
    }); 
     textPane.insertComponent(button); 
     this.add(textPane); 
    } 
} 
+0

Должен ли я просто хранить его в собственном режиме, а не использовать HTML или у меня есть выбор? – Confident

+0

пожалуйста, чтобы проверить сообщение [camickr] (http://stackoverflow.com/users/131872/camickr) и [StanislavL] (http://stackoverflow.com/users/301607/stanislavl) о 'JTextPane' /' JEditorPane ' – mKorbel

+0

http://java-sl.com/custom_tag_html_kit.html, который показывает, как добавить пользовательский тег для кнопки – StanislavL

ответ

3

Там, кажется, какая-то проблема с этим типом содержимого при добавлении компонентов (см this пост), но вы можете попробовать что-то вроде следующего:

JTextPane textPane = new JTextPane(); 
    JButton button = new JButton("Button");  
    button.setAlignmentY(0.85f); 

    HTMLEditorKit kit = new HTMLEditorKit(); 
    HTMLDocument doc = new HTMLDocument(); 
    textPane.setEditorKit(kit); 
    textPane.setDocument(doc); 

    try { 
     kit.insertHTML(doc, doc.getLength(), "<p color='#FF0000'>Cool!", 0, 0, HTML.Tag.P); 
     kit.insertHTML(doc, doc.getLength(), "<p></p>", 0, 0, null); 
    } catch (BadLocationException ex) { 
    } catch (IOException ex) { 
    } 
+0

спасибо большое! Я думаю, что это будет сделано. – Confident

2

Проблема заключается в том, что вы добавляете текст в JEditorPane, а затем добавляете компонент, который он встроил в HTML-код JEditorPane:

Вот пример:

import java.awt.Color; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 
import javax.swing.*; 

public class Test { 

    public static void main(String[] args) throws Exception { 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       new Test().createAndShowUI(); 
      } 
     }); 
    } 

    private void createAndShowUI() { 
     JFrame frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     initComponents(frame); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    private void initComponents(JFrame frame) { 
     final JTextPane editorPane = new JTextPane(); 
     editorPane.setSelectedTextColor(Color.red); 

     //set content as html 
     editorPane.setContentType("text/html"); 
     editorPane.setText("<p color='#FF0000'>Cool!</p>"); 

     //added <u></u> to underlone button 
     final InlineB label = new InlineB("<html><u>JLabel</u></html>"); 

     label.setAlignmentY(0.85f); 

     label.addMouseListener(new MouseAdapter() { 

      @Override 
      public void mouseReleased(MouseEvent e) { 
       //added check for MouseEvent.BUTTON1 which is left click 
       if (e.isPopupTrigger() || e.getButton() == MouseEvent.BUTTON1) { 
        JOptionPane.showMessageDialog(null, "Hello!"); 
        String s = editorPane.getText(); 
        System.out.println(s); 
       } 
      } 
     }); 

     editorPane.insertComponent(label); 
     frame.getContentPane().add(editorPane); 
    } 
} 

class InlineB extends JButton { 

    public InlineB(String caption) { 
     super(caption); 
     setBorder(null);//set border to nothing 
    } 
} 

Когда мы нажимаем на кнопку это выполняется:

//added check for MouseEvent.BUTTON1 which is left click 
       if (e.isPopupTrigger() || e.getButton() == MouseEvent.BUTTON1) { 
        JOptionPane.showMessageDialog(null, "Hello!"); 
        String s = editorPane.getText(); 
        System.out.println(s); 
       } 

результаты Println (ов):

<html> 
    <head> 

    </head> 
    <body> 
    <p color="#FF0000"> 
     Cool! 
     <p $ename="component"> 

    </p> 
    </body> 
</html> 

Как вы можете см. компонент, встроенный в HTML, дальнейшие вызовы setText() стирают это.

Единственным жизнеспособным решением (помимо Rempelos +1 к нему) слишком:

Повторно добавьте компонент в JEditorPane после вызова setText() так:

 @Override 
     public void mouseReleased(MouseEvent e) { 
      //added check for MouseEvent.BUTTON1 which is left click 
      if (e.isPopupTrigger() || e.getButton() == MouseEvent.BUTTON1) { 

       JOptionPane.showMessageDialog(null, "Hello!"); 
       String s = editorPane.getText(); 
       System.out.println(s); 

       editorPane.setText("<html><u>Hello</u></html>"); 
       //re add after call to setText 
       editorPane.insertComponent(label); 
      } 
     } 

Хотя лучший способ может состоять в том, чтобы расширить класс JEditorPane и сделать метод setText() автоматически добавить его компонент/кнопку