I'm looking to incorporate a hover effect on a hyperlink within JEditorPane utilizing Swing in Java. How can I achieve this

After successfully implementing the hyperlink in jEditorPane through this link, I now aim to incorporate a hover effect to the hyperlink.

I attempted to apply CSS using the following code:

MyHTMLEditorKit kit = new MyHTMLEditorKit();
setEditorKitForContentType("text/html", kit);        
addHyperlinkListener(createHyperlinkListener());
StyleSheet css= kit.getStyleSheet();
css.addRule("a { color: red;}");

Despite my efforts, the CSS rules like a:hover{color:red;} did not yield the desired results. I also experimented with attributes like

onmouseover="this.style.color='red'"
, but to no avail.

How can I effectively implement the onhover effect for hyperlinks in jEditorPane?

Answer №1

My approach to this code seems a bit convoluted. I'm looking for a cleaner solution from others.

import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.text.html.*;

public class HoverEffectSolution {
  private static final String SO = "http://stackoverflow.com/";
  private final String s = "<a href='%s' color='%s'>%s</a><br>";
  private final String s1 = String.format(s + "aaaaaaaaaaaaaa<br>", SO, "blue", SO);
  private final String s2 = String.format(s + "cccc", SO, "#0000FF", "bbbbbbbbbbb");
  private final JEditorPane editor = new JEditorPane(
    "text/html", "<html>" + s1 + s2);
  private JComponent createUI() {
    editor.setEditable(false);
    //@see: BasicEditorPaneUI#propertyChange(PropertyChangeEvent evt) {
    //      if ("foreground".equals(name)) {
    editor.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
    editor.addHyperlinkListener(new HyperlinkListener() {
      @Override public void hyperlinkUpdate(HyperlinkEvent e) {
        if (e.getEventType() == HyperlinkEvent.EventType.ENTERED) {
          setElementColor(e.getSourceElement(), "red");
        } else if (e.getEventType() == HyperlinkEvent.EventType.EXITED) {
          setElementColor(e.getSourceElement(), "blue");
        } else if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
          Toolkit.getDefaultToolkit().beep();
        }
        //I don't understand why this is necessary...
        //??? call BasicTextUI#modelChanged() ???
        editor.setForeground(Color.WHITE);
        editor.setForeground(Color.BLACK);
      }
    });
    return new JScrollPane(editor);
  }
  private void setElementColor(Element element, String color) {
    AttributeSet attrs = element.getAttributes();
    Object o = attrs.getAttribute(HTML.Tag.A);
    if (o instanceof MutableAttributeSet) {
      MutableAttributeSet a = (MutableAttributeSet) o;
      a.addAttribute(HTML.Attribute.COLOR, color);
    }
  }
  public static void main(String... args) {
    EventQueue.invokeLater(new Runnable() {
      @Override public void run() {
        displayGUI();
      }
    });
  }
  public static void displayGUI() {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    f.getContentPane().add(new HoverEffectSolution().createUI());
    f.setSize(320, 240);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}

Answer №2

Check out this code snippet:

HTMLEditorKit editor = new HTMLEditorKit();
StyleSheet styleSheet = editor.getStyleSheet();
styleSheet.addRule("a:hover{color:blue;}");
Document document = editor.createDefaultDocument();
String htmlContent = "<a href='google.com'>Visit Google!</a>";
// set up your JEditorPane
jEditorPane.setDocument(document);
jEditorPane.setText(htmlContent);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing PHP to Assign Attributes to Form Elements

Currently, I am utilizing a Content Management System (CMS) along with a form builder extension. This particular extension grants me the ability to execute PHP scripts upon page load. Furthermore, I have the option to include custom 'Additional Attri ...

The page refreshes when the anchor element is clicked

Currently, I am working on enhancing a web application that is built on the foundation of traditional aspx (asp.net) web forms with elements of Angular 6 incorporated into it. My current assignment involves resolving a bug that triggers a page refresh whe ...

CSS Grid ensures uniformity in the spacing between columns

Is there a way to ensure the spacing between items is consistent? I attempted to use grid-column-gap, but the gap varies because the number of items on each row differs. The first and third rows have a larger gap compared to the second row, which has the ...

Bidirectional binding of attributes in an Angular directive

I have developed a custom Angular Directive known as evoEventMirror. Its main purpose is to attach a jQuery event to an inserted element and apply a specified CSS style to the "root" element. Refer to the example below: <div id="#mydiv" evo-event-mirro ...

Deactivate the selection option in Syncfusion NumericTextbox

I have integrated an Angular NumericTextbox component from Syncfusion into my application. A problem we encountered is that when the input is clicked, it automatically gets selected. Is there a way to disable this behavior? Problem: https://gyazo.com/a72b ...

The styling of the first column in this row will be different from the rest

Despite having the same styling and no typing errors, I am still facing an issue with the first column not being styled correctly. It appears as nothing but text inside a column square. HTML: <div class="container-fluid"> <!--Nav Bar--> ...

Changing knockoutJS foreach binding dynamically

I have a list of arrays known as table#1, table#2, ... table#10 and I want to be able to click on a table number and display the list items of that table in a panel. Here is a snippet of the code: The HTML part works fine. The only issue lies in this li ...

Is it not possible to use a hyperlink and the general sibling combinator simultaneously?

Hi everyone, I'm completely new to CSS so please bear with me as I try to explain my issue. I'm attempting to create an image hyperlink using the .link class. I want the images for both .link and .picture to "change" when I hover over the hyperl ...

What is the best way to display a default image when a specific image file cannot be located?

Is there a way to request images for user profile photos from an Amazon S3 bucket, and if the image file is not found for a user, automatically redirect to an alternate default image file for the profile photo? If so, how can I implement this using Amazo ...

Ways to transfer a value from a Thymeleaf template to an Ajax request

I am currently working on a table that iterates through a list of logs. My goal is to implement an ajax call so that when a specific row is clicked, it retrieves the id of the log clicked and fetches that log's specific details, then inserts the infor ...

Customizing Material UI: Adjusting the visibility of slider thumb upon user interaction and value changes in the slider

In my application, I have implemented a Material UI Slider and I am looking to keep the thumb invisible until the user interacts with it. Once the user changes the slider value, I want the thumb to remain visible at that specific value. By using the CSS pr ...

Transform collapsible color upon materialize click

Is there a way to change the color of the collapsible header only when clicked? I'm struggling with adding the color inside the class element while calling the "connect" function. Can this be achieved? <div class="collapsible-header" onclick="conn ...

How come the background image gets replaced by an extensive amount of text?

When using a text-field with a background-image style, the following CSS is applied: .leftPaneContent INPUT { background-color: #FFFFFF; background-image: url("../images/icon-search-large.png"); background-position: 4px 3px; background-rep ...

Popup text alert remains persistent in SeleniumPlus test on Internet Explorer

Currently, I am using a method called VerifyAndDismissAlert() in an automated test. try{ WebDriver WD = WebDriver(); Alert alert = WD.switchTo().alert(); alert.accept(); String alertText = alert.getText(); Pause(1); ...

How can I extract the value of an integer variable from the TextEdit response in MainActivity to utilize it in another class?

I am working on developing an app that involves extracting numerical specifications entered by users in the main activity via a TextEdit input. The goal is to convert this input into an integer and utilize the specific value of the integer in a separate cl ...

I am eager to demonstrate the utilization of AngularJS in displaying hierarchical table rows

I am facing an issue with the code I wrote to display a tree-structured table. It's not working as expected and I need some assistance. The goal is to show only rows in a tree structure, not the entire table inside a table row. <script type="text/ ...

What causes threads to be awakened by Object.notifyAll but fail to acquire the lock they need?

We can understand the functioning of a monitor by observing how it works. Check out this image to get a visual representation: monitor When Object.notifyAll() is called, threads in the wait set are awakened. Out of these threads, only one of them acqu ...

Discover the best ways to repurpose an HTML page with varying jQuery/PHP code

After recently venturing into web development, I decided to create a guestbook that requires login information. Users with valid accounts have the ability to log in/out, create new entries, and edit their own content. They also have the option to change th ...

Problem with redirecting when using HTTPS

I recently implemented an SSL Certificate and made changes to the web.config file. Here is the updated code: <system.webServer> <rewrite> <rules> <rule name="removed by me" stopProcessing="true"> ...

transforming the elements within a div into a visual representation

I'm in the process of developing a web-based image editor. My main div will have multiple nested div elements within it. My goal is to save the entire main div as an image in a designated folder when the user clicks on a save button. I initially atte ...