Insert String to JTextPane as hyperlink
Hi,
I have a JTabbedPane with 2 tabs, on each tab is one panel.
On first pannel I add JTextPane and I would like to insert in this JTextPane some hyperlinks.
I found some examples in forum, but doesn't work for me.
Could somebody help me ?
Thank's.
Here is my code :
JTextPane textPane = new JTextPane();
textPane.setPreferredSize(new Dimension(500,300));
HTMLEditorKit m_kit = new HTMLEditorKit();
textPane.setEditorKit(m_kit);
StyledDocument m_doc = textPane.getStyledDocument();
textPane.setEditable(false); // only then hyperlinks will work
panel1.add( textPane,BorderLayout.CENTER); //add textPane to panel of
//JTabbedPane
String s = new String("http://google.com");
SimpleAttributeSet attr2 = new SimpleAttributeSet();
attr2.addAttribute(StyleConstants.NameAttribute, HTML.Tag.A);
attr2.addAttribute(HTML.Attribute.HREF, s);
try{
m_doc.insertString(m_doc.getLength(), s, attr2);
}catch(Exception excp){};
The String s is displayed like text not like hyperlink..
Hi , You can take a look at this code , this code inserts a string into a StyledDocument in a JTextPane as a hyperlink and on clicking fires the URL on the browser.
/* Demonstrating creation of a hyperlink inside a StyledDocument in a JTextPane */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.Border;
import javax.swing.text.*;
public class Hyperlink extends JFrame {
private Container container = getContentPane();
private int toolXPosition;
private int toolYPosition;
private JPanel headingPanel = new JPanel();
private JPanel closingPanel = new JPanel();
private final static String LINK_ATTRIBUTE = "linkact";
private JTextPane textPane;
private StyledDocument doc;
Hyperlink() {
try {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
setSize(300, 200);
Rectangle containerDimension = getBounds();
toolXPosition = (screenDimension.width - containerDimension.width) / 10;
toolYPosition = (screenDimension.height - containerDimension.height) / 15;
setTitle("HYPERLINK TESTER");
setLocation(toolXPosition, toolYPosition);
container.add(BorderLayout.NORTH, headingPanel);
container.add(BorderLayout.SOUTH, closingPanel);
JScrollPane scrollableTextPane;
textPane = new JTextPane();
//for detecting clicks
textPane.addMouseListener(new TextClickListener());
//for detecting motion
textPane.addMouseMotionListener(new TextMotionListener());
textPane.setEditable(false);
scrollableTextPane = new JScrollPane(textPane);
container.add(BorderLayout.CENTER, scrollableTextPane);
container.setVisible(true);
textPane.setText("");
doc = textPane.getStyledDocument();
Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
String url = "http://www.google.com";
//create the style for the hyperlink
Style regularBlue = doc.addStyle("regularBlue", def);
StyleConstants.setForeground(regularBlue, Color.BLUE);
StyleConstants.setUnderline(regularBlue,true);
regularBlue.addAttribute(LINK_ATTRIBUTE,new URLLinkAction(url));
Style bold = doc.addStyle("bold", def);
StyleConstants.setBold(bold, true);
StyleConstants.setForeground(bold, Color.GRAY);
doc.insertString(doc.getLength(), "\nStarting HyperLink Creation in a document\n\n", bold);
doc.insertString(doc.getLength(), "\n",bold);
doc.insertString(doc.getLength(),url,regularBlue);
doc.insertString(doc.getLength(), "\n\n\n", bold);
textPane.setCaretPosition(0);
catch (Exception e) {
public static void main(String[] args) {
Hyperlink hp = new Hyperlink();
hp.setVisible(true);
private class TextClickListener extends MouseAdapter {
public void mouseClicked( MouseEvent e ) {
try{
Element elem = doc.getCharacterElement(textPane.viewToModel(e.getPoint()));
AttributeSet as = elem.getAttributes();
URLLinkAction fla = (URLLinkAction)as.getAttribute(LINK_ATTRIBUTE);
if(fla != null)
fla.execute();
catch(Exception x) {
x.printStackTrace();
private class TextMotionListener extends MouseInputAdapter {
public void mouseMoved(MouseEvent e) {
Element elem = doc.getCharacterElement( textPane.viewToModel(e.getPoint()));
AttributeSet as = elem.getAttributes();
if(StyleConstants.isUnderline(as))
textPane.setCursor(new Cursor(Cursor.HAND_CURSOR));
else
textPane.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
private class URLLinkAction extends AbstractAction{
private String url;
URLLinkAction(String bac)
url=bac;
protected void execute() {
try {
String osName = System.getProperty("os.name").toLowerCase();
Runtime rt = Runtime.getRuntime();
if (osName.indexOf( "win" ) >= 0) {
rt.exec( "rundll32 url.dll,FileProtocolHandler " + url);
else if (osName.indexOf("mac") >= 0) {
rt.exec( "open " + url);
else if (osName.indexOf("ix") >=0 || osName.indexOf("ux") >=0 || osName.indexOf("sun") >=0) {
String[] browsers = {"epiphany", "firefox", "mozilla", "konqueror",
"netscape","opera","links","lynx"};
// Build a command string which looks like "browser1 "url" || browser2 "url" ||..."
StringBuffer cmd = new StringBuffer();
for (int i = 0 ; i < browsers.length ; i++)
cmd.append((i == 0 ? "" : " || " ) + browsers[i] +" \"" + url + "\" ");
rt.exec(new String[] { "sh", "-c", cmd.toString() });
catch (Exception ex)
ex.printStackTrace();
public void actionPerformed(ActionEvent e){
execute();
}Here , what I have done is associated a mouseListener and a mouseMotionListener with the JTextPane and I have created the hyperlink look with a Style of blue color and underline and have added the LINK_ATTRIBUTE to that Style which takes care of listening to mouse clicks and mouse motion.
The browser can be started in windows using the default FileProtocolHandler using rundll32 and in Unix/Sun we have to take a wild guess at which browser could be installed , the first browser encountered is started , in Mac open command takes care of starting the browser.
Hope this is useful.
Similar Messages
-
Some problems about insert String into JTextPane
here is the colde:
HTMLEditorKit kit = new HTMLEditorKit();
HTMLDocument doc =(HTMLDocument)kit.createDefaultDocument();
String str="hello world";
SimpleAttributeSet attr =new MutableAttributeSet();
StyleConstants.setFontFamily(attr, "Times New Roman");
StyleConstants.setFontSize(attr, 12);
StyleConstants.setBold(attr, true);
StyleConstants.setBackground(attr, UIManager.getColor("control"));
doc.insertString(1,str,attr);
JTextPanel panel =new JTextPanel();
panel.setEditorKit(kit);
panel.setDocument(doc);
text "hello word" of document can be show correctly,i save it as a .html file then open it a strange problem occured,i can't see the word "hello world" in panel,i can't find the word "hello word" in html source code except some tags of html,who can tell me what's wrong?thanks in advanced!hello user457523
I have found the reason to that error.It's because there's a trigger and ext_src_file_nm is populated by the trigger from another column ext_src_file_loc when inserting and I didn't give any value to ext_src_file_loc so ext_src_file_nm is null.
I have disabled that trigger and now I get new errors.When I traced to a line of Jave code I got missing source file warning,and the source file is also oracle.sql.CharacterSet.java.I can not trace into the source file and then I skipped that code and then I got new errors.I want to know how to trace into the jave code and find what's the matter.
Thank you very much. -
Hi,
I am trying to insert HTML into JTextPane.
I am using the following code for the same.
JTextPane jedit = new JTextPane();
jedit.setContentType("text/html");
HTMLDocument doc = (HTMLDocument)jedit.getDocument();
String text = "<a href=\"???\">hyperlink</a>asd<a href=\"???\">hyperlink123</a>";
HTMLEditorKit editorKit = (HTMLEditorKit)jedit.getEditorKit();
editorKit.insertHTML(doc, doc.getLength(), text, 0, 0, null);
doc.insertString(doc.getLength(),"Hi testing",null);
text = "<a href=\"???\">hyperlink123</a>";The problem is that the HTML gets inserted into new line. I do not want the new line.
I know there is an API like insertBeforeEnd(...) but do not know how to use that.
Any help for the above problem will be of great use.
Thanks.look I have got the answer ... I guess this would be the root cause of the problem of new line.
when ever you want the text to be inserted
-at new line provide the last argument of HTMLDocument.insertHTML as null
- at same line provide the last argument as the HTML tag you are inserting into the JtextPane's document.thats it !!!
ENJOY :-) -
Can we pass dynamic cell associated value [of scorecard] as query string parameter in custom hyperlink property of KPI of scorecard in PPS SP2013 , so that we can pass those values to another page
How to get those cell associated values and set these dynamic value as query string parameter in custom hyperlink property of KPI of scorecard in performance point services in sharepoint 2013I could somehow link to the table name, but that can be changed... Any ideas?
Not sure if this will help or not but maybe a little from several areas might point you in the right direction.
If you are concerned about users changing the table name then you can define a name to reference the table and then if the user changes the table name then the Refers to automatically changes to the new table reference but your defined name remains the same.
However, if users want to break a system even when you think you have it bullet proof the users come along with armour piercing bullets.
Example:
Insert a table (say Table1)
Go to Define a name and insert a name of choice (eg. ForMyTab1)
Then click the icon at the right of the Refers to field and select the entire table including the column headers and it will automatically insert something like the following in the Refers to field.
=Table1[#All]
Now if a user changes the table name then Table1 will also automatically change.
Example code to to reference the table in VBA.
Sub Test()
Dim wsSht1 As Worksheet
Dim lstObj1 As ListObject
Set wsSht1 = Worksheets("Sheet1")
Set lstObj1 = wsSht1.ListObjects(Range("ForMyTab1").ListObject.Name)
MsgBox lstObj1.Name
End Sub
Regards, OssieMac -
A Simple Question... inserting image into JTextPane...
Well my problem is very simple (but not for me). Before I explain it, please take a look at a simple class...
public class Window extends JTextPane {
Window() {
super();
}// Window
public void appendText(String s,Color col) throws BadLocationException {
StyledDocument sd = getStyledDocument();
SimpleAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setForeground(attr,col);
sd.insertString(sd.getLength(),s,attr);
* THE POINT - what should I write here, please consult description followed by the class.
} //appendText
} //classThe appendText method simply appends the text in text pane with desired color. Now I want to know what should I write at point THE POINT so that at end of appended string an icon (suppose end.gif) is added and is displayed in text pane. Simple?
Stay happy,
fadeeDear Fadee,
here is a small programe for inserting images into JTextPane;
find this comment and start
/*All Code In this Button Action*/if you need any thing feel free to tell me,
i'm with you brother, i'll do my best :O)
-Best regards
mnmmm
* Fadee.java
* Created on June 7, 2002, 1:13 AM
import java.awt.*;
import java.awt.event.*;
import java.awt.color.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
* @author Brother Mohammad, Cairo, Egypt.
* @version
public class Fadee extends javax.swing.JFrame {
JTextPane tp;
JButton b;
StyledDocument sd;
SimpleAttributeSet attr;
public Fadee() throws BadLocationException {
b = new JButton("Press");
tp = new JTextPane();
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
/*All Code In this Button Action*/
try {
sd = tp.getStyledDocument();
attr = new SimpleAttributeSet();
/*get default style*/
Style def = StyleContext.getDefaultStyleContext().
getStyle(StyleContext.DEFAULT_STYLE);
/*add style for text default style*/
Style regular = tp.addStyle("regular", def);
StyleConstants.setFontFamily(def, "SansSerif");
StyleConstants.setAlignment(def, StyleConstants.ALIGN_CENTER);
StyleConstants.setForeground(def, Color.RED);
/*add style for icon create as many as icons you have
and don't forget to resize the photo at small size
to fit with font size*/
Style s = tp.addStyle("icon", regular);
StyleConstants.setAlignment(s, StyleConstants.ALIGN_JUSTIFIED);
StyleConstants.setIcon(s, new ImageIcon("d:\\My Photo.GIF"));
/*here is what user will see*/
sd.insertString(sd.getLength(), "Allah Akbar ", tp.getStyle("regular"));
sd.insertString(sd.getLength(), " ", tp.getStyle("icon"));
} catch (BadLocationException x) {
x.printStackTrace();
getContentPane().setLayout(new BorderLayout());
getContentPane().add(b, BorderLayout.NORTH);
getContentPane().add(tp, BorderLayout.CENTER);
setSize(500, 500);
setVisible(true);
public static void main(String args[]) {
try {
Fadee f = new Fadee();
} catch (BadLocationException x) {
x.printStackTrace();
} -
Inserting strings in a database
Hello all!
I am trying to insert string values in a database with this metode.
public void insertData(){
try{
String url = "jdbc:odbc":"+database;
Connection connection = DriverManager.getConnection(url, user, password);
Statement status = connection.createStatement();
status.executeUpdate("INSERT INTO radiograhy (Title, Red, Green, Blue,"
+ "Hue,Saturation,Value,Color,Path,IdRadiography,Description) VALUES "
+"("+Title+","+Red+","+ Green+","+ Blue +","
+ Hue+","+Saturation+","+Value+","+Color+","+Path+","
+IdRadiography+","+Description+")");
}catch(SQLException e){
e.printStackTrace();
System.out.println(e);
but the metode throws me an exception :
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement.This has actually nothing to do with JDBC, but with basic SQL knowledge.
Print the complete query using System.out.println and try to find out what's wrong with it. Play with it, execute it right on the DB, etcetera. If you don't understand it, then don't bother to read some SQL tutorials how to write clean SQL.
Once you understand SQL, I would also recommend you to use PreparedStatement instead. -
Inserting strings over 2000 in length
Hi,
I'm trying to populate a database table which contains a long and
I've been running into two Oracle errors:
ORA-01462: cannot insert string literals longer than 2000
characters
and
ORA-01489: result of string concatenation is too long
Can someone point me to documentation or a solution of how you
can get a 29k string into the database? I have code regarding how
to use LOBs, but I'm unfamiliar with any stored procedures which
will allow you to append to a long column with new content. I
need to use long for the project I am working on.
Thanks in advance for your help!
Jill
nullHi Ralf,
If you read the documentation on
http://java.sun.com/products/jdbc/index.html you will
find a statement saying that the JdbcOdbcDriver is
only for test and experimental use.Yes, but my and other's experiences with the JDBC-ODBC bridge itself are very well.
Since it is only a bridge over the specific vendor's ODBC driver, you are limited to the capabilities of that.
But the bridge is not to blame for this.
For MS products you may reach efforts by updating to an actual MDAC version.
Nethertheless, with MS ODBC there are some problems.
Search the driver database (a link is on the above web
page) for another (commercial) driver. I recommend the
type 4 driver from i-net.Ok.
Have you tried out that error David reported with the i-net driver?
I use JDBC-ODBC with MS SQLServer 2000, actual MDAC, and I get that error with PreparedStatement.
But it's all ok with a normal statement.
So if you could test them both with the i-net driver, we would see if it's again the MS ODBC driver.
Regards,
Ralf SchumacherI think, I'm not the first you asks this:
you are not the quick one we saw in Suzuka on Sunday, are you? -
Inserting String data to BLOB column
Hi All
I want to insert String data into BLOB column using DBAdapter - through database procedure.
anybody can help?
Regards
Albin IssacI have used utl_raw.cast_to_raw('this is only a test')).But for bigger string I get the error as "string literal too long" do we have any similar function for longer string.
Thanks,
-R -
Problem in Inserting string in mysql databse
Hi all,
I am trying to insert string in mysql using java query.As I have taken field varchar,that should be in single quotes,whereas string is having double quotes...so as I am trying to insert data that gives null value all the time.
I did like:
String name=jTextFieldname.getText();
String sql="insert into record_master values (name,orderno,email,dob,address,mobile)";Any pointers are appreciable.
Regards,
PalakOh I got the sollution...Tat was something like:
String sql = "INSERT INTO record_master (name, orderno,email,dob,address,mobile,imeino) " +
"VALUES('" + name + "', '" + orderno + "','" + email + "','" + dob +"','" + address +"','" + mobile + "','" + imei + "')";
Regards,
Palak -
hi
when i insert string text in hebrew i see ????????? how to fix it ?
i work on:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
Oracle Developer ver. 2.1.1.64
thanksi try this, but still same problem :(
my Settings:
NLS_LANGUAGE AMERICAN
NLS_TERRITORY AMERICA
NLS_CURRENCY $
NLS_ISO_CURRENCY AMERICA
NLS_NUMERIC_CHARACTERS .,
NLS_CHARACTERSET IW8MSWIN1255
NLS_CALENDAR GREGORIAN
NLS_DATE_FORMAT DD-MON-RR
NLS_DATE_LANGUAGE AMERICAN
NLS_SORT BINARY
NLS_TIME_FORMAT HH.MI.SSXFF AM
NLS_TIMESTAMP_FORMAT DD-MON-RR HH.MI.SSXFF AM
NLS_TIME_TZ_FORMAT HH.MI.SSXFF AM TZR
NLS_TIMESTAMP_TZ_FORMAT DD-MON-RR HH.MI.SSXFF AM TZR
NLS_DUAL_CURRENCY $
NLS_COMP BINARY
NLS_LENGTH_SEMANTICS BYTE
NLS_NCHAR_CONV_EXCP FALSE
NLS_NCHAR_CHARACTERSET AL16UTF16
NLS_RDBMS_VERSION 11.2.0.1.0 -
How to get string from jtextpane along with its attributes
sir,
How to get string from jtextpane along with its attributes
i,e font,size,style,color etc.
please help me out.
my mail id is [email protected]JTextPane extends JTextComponent
JTextComponent.getDocument()
a Document is a set of Element, see Document.getRootElements(). Each Element has attributes, stored within an AttributSet object see Element.getAttributes()
a Document can also be rendered as a String, see Document.getText( offest, length ), use it with 0 and Document.getLength() as parameters. -
Inserting Component in JTextPane
hai
I have a problem while inserting components in JTextPane
i first inserted text using insertString() function and then a JLabel using
insertComponent() function but the Label is appearing before the text.
This is the case with any of the component that is being added
The components are being added before the text
can someone tell me a solution by which the components appear in the order they
were added
Thanking you in anticipationu r inserting the component at the 0 caret position, so as ur need set the caret position where u want to insert the component like..
textPane.setText("Hello");
textPane.setCaretPosition(5);
textPane.insertComponent(new JLabel("World")); -
How to insert string containing '&' into a table
INSERT INTO TBL_CHANGES_ORGANISATIES(CHANGE_MANAGEMENT_ID, SUBMITTER) VALUES ('HM0000002147848|TK0000003121328','CS CSU S\&B Change Management')if you're in sqlplus:
put set define offprior to running your insert.
if you're in Toad, either:
put set define offbefore your insert statement, and run both in as a script
OR
right mouseclick on the editor and untick the "Prompt for substitution variables", and you need never worry about the & again! -
Inserting components to JTextPane
Hi,
I need to insert components to JTextPane. I know JTextPane provides a method insertComponent() for this purpose.
But this does not work when you set the content type to "text/html".
For example if I do the following:
JTextPane textPane = new JTextPane();
textPane.setContentType("text/html");and then try to insert a component it does not work.
My question is, can I insert a JLabel/JButton to JTextPane once I set the content type to "text/html"?My question is, can I insert a JLabel/JButton to JTextPane once I set
the content type to "text/html"? You don't really know what you did, do you?
No, you can not add other widgets into a JTextPane since it's not a container. That is completely irrelevant from the fact that you can specify a MIME type for what's written inside the text pane. -
Hi,
I?m building a little IRC client. I?m using a swing JtextPane but my problem is that I can?t insert hyperlinks into it.
The JtextPane is based on a DefaultStyledDocument, I have created a Style called Hyperlink.
Style style4 = myStylePane.addStyle("Hyperlink", defstyle);
StyleConstants.setUnderline(style4,true);
doc.insertString(doc.getLength(),"Http://www.Java.Sun.com",style4);
The problem is that I can?t find a proper method how I can make the text a click-able hyperlink.
I have tried already the following:
Style style4 = myStylePane.addStyle("Hyperlink-Jlabel", defstyle);
StyleConstants.setComponent(style4, new Jurl("http://www.Java.sun.com"))
doc.insertString(doc.getLength(),"Ignore text",style4);
The class Jurl extends of Jlabel, plus I have implemented the event mouseclicked that opens the url in a blank browser window.
But the problem here is that Jlabel breaks out of the visible rectangle of my JtextPane (right side break). So it is possible that I see for example http://www.Java.su here ends my JtextPane. The JtextPane does no take a new line to display the JLabel.
Thanks in advance and,
Have a nice day.
Pieter PareitHere, you should be able to adapt this;-import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.applet.*;
public class linkIt extends Applet {
Panel back = new Panel();
public linkIt(){
super();
setLayout(new BorderLayout());
add("Center",back);
back.setLayout(null);
Olink link1 = new Olink(this,"Go to google and search ","http://www.google.com");
back.add(link1);
link1.setBounds(10,10,100,25);
Olink link2 = new Olink(this,"Answer for programmers ","http://forum.java.sun.com");
back.add(link2);
link2.setBounds(10,40,100,25);
public void init(){
setVisible(true);
public class Olink extends Label implements MouseListener {
Applet applet;
Color fcolor = Color.blue;
Color lcolor = Color.magenta;
String text;
String wadd;
public Olink(Applet ap, String s, String s1){
super(s);
this.applet = ap;
this.text = s;
this.wadd = s1;
addMouseListener(this);
setForeground(fcolor);
public void paint(Graphics g){
super.paint(g);
if (getForeground() == lcolor){
Dimension d = getSize();
g.fillRect(1,d.height-5,d.width,1);
public void update(Graphics g){paint(g);}
public void mouseClicked(MouseEvent e){
try{
URL url = new URL(wadd);
applet.getAppletContext().showDocument(url,"_self");
catch(MalformedURLException er){ }
public void mouseEntered(MouseEvent e){
setForeground(lcolor);
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
repaint();
public void mouseExited(MouseEvent e){
setForeground(fcolor);
setCursor(Cursor.getDefaultCursor());
repaint();
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public static void main (String[] args){
new linkIt();
}
Maybe you are looking for
-
MR11 - GR/IR Clearing account
Hi There is a Service Purchase order with 2 services in it, amounting to USD 848.00 with a document creation date in 2003. (Note: In the invoice item tab of PO, the Invoice receipt and GR-based IV are both flagged.) The user did a service entry sheet
-
Lost Adobe trials during restore, help please
Two days ago I downloaded PS and Dreamweaver trials. I had to do a restore and when I looked; all new Adobe programs were gone. What should I do to get back to the trials I have already downloaded?
-
Where does a PL/SQL block run? PGA or SGA?
Hi all, 11g I'm not familiar with the oracle memory structure, if I have a simple pl/sql block as below DECLARE v1 number; BEGIN v1:=100; DBMS_OUTPUT.PUT_LINE(v1); END;in my mind, even though it's a small block, when i execute it, it would also
-
How can we change Topic Names Generated after linking a document
Hi: I linked a document and generated a topic in RoboHelp for HTML. The topics are generated with some names and i am not able to rename them after they are generated. I tried doing this as per help Define the topic name pattern for generated to
-
Hi I bought a e4200 router about 3 weeks ago and after a power outage it decided it didnt like being connected to the internet anymore. So i got on the phone with cisco they determined the router was no good, mind you my laptop would connect wired. S