Guide on adjusting image dimensions in JTextPane using HTML and CSS in the Java Swing environment

I am looking to add an image (such as a formula created from LaTeX) into JTextPane, using HTML+CSS for text formatting and manually setting its size. I attempted the following approach:

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JTextPane;


public class App extends JFrame {

    private void run() {
        setSize(new Dimension(320, 240));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTextPane pane = new JTextPane();
        pane.setContentType("text/html");
        String imageUrl = getClass()
                            .getClassLoader()
                            .getResource("resources/img.jpg");
        pane.setText(
            "<html>"+
                "<head> <style>"+
                        // CSS works perfectly for text,
                        ".text { color: red; font-family: \"Times New Roman\"; }"+
                        // but not for images
                        ".pic { width: 250px; }"+
                "</style> </head>"+
                "<body>"+
                    "<p class=\"text\"> Aaaa. </p>"+
                    "<img class=\"pic\" src=\""+imageUrl+"\" />"+
                "</body>"+
            "</html>"
        );
        
        getContentPane().add(pane);
        setVisible(true);
    };

    public App() {
        super("Test HTML+CSS");
    }

    public static void main(String[] args) {
        App app = new App();
        app.run();
    }
}

It appears that the JTextPane effectively applies text styles with CSS, but does not seem to respond to CSS rules for images. Is there a way to resolve this issue or am I simply wasting time?

Answer №1

According to the advice from Lena White in the feedback, it is recommended to place the width attribute within the <img> tag. Therefore, the revised HTML code should appear as follows:

<html>
  <body>
    <p style="color: blue;"> Hello! </p>
    <img width="200" src="/path/to/picture" />
  </body>
</html>

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

Creating a personalized serializer for Java 8 LocalDateTime

Having a class named Child1, I initially utilized Joda Date Time to convert it into JSON using Lift Json. However, I now intend to switch to Java 8 LocalDateTime. Unfortunately, I am facing challenges in creating a custom serializer for this transition. He ...

The text and buttons exceed the size limits of the popup box

Currently, I am tasked with updating an old website that includes a popup box containing an iFrame and nested tables. The content within these tables consists of text and two input boxes at the bottom. Everything within the box looks fine on screen resolu ...

An issue occurred when retrieving the input value during a (change) event within a nested *ngFor loop in Angular

Within my table, I have implemented a nested loop using the *ngFor directive: <tbody> <tr *ngFor="let dept of salesTarget; let i = index"> <td>{{dept.dept}}</td> <td *ngFor="let month of monthList; ...

"Toggling a switch alters the appearance following the submission of a form

Recently, I incorporated a switch toggle into my form to help filter products. I followed this guide. However, after submitting the form, the page reloads using ajax and the switch toggles back to its initial style before being toggled again. What could be ...

Executing numerous xhttp.send requests within a single webpage

Hey there, I'm facing an issue with xhttp.send(); as it keeps giving me the error message net::ERR_EMPTY_RESPONSE Here is a snippet of my code. Whenever a user clicks too quickly, they get kicked off the page. Is there a way to prevent this? docum ...

How to style the first column of the first row in a table using CSS without affecting nested tables

Having some challenges with CSS selectors, I'm hoping to find some assistance here. Presented with HTML code that resembles the following: <table class=myTable> <tr> <td>this is the td of interest</td> </tr> ...

Utilizing SASS to retrieve the H, S, L values from a color

Is there a way to extract the H, S, L values from a hex color in SASS and assign them to separate CSS variables? $colors: ( "primary": $primary, "secondary": $secondary) !default; :root { @each $color, $value in $colors { -- ...

Steps to display the Sidebar on top of the main information page

One unique feature of my website is the FiltersSideBar located on the left side of the page. It contains various filters to refine search results. To optimize user experience, I implemented a function that hides the sidebar at specific browser window size ...

Tips for starting Safari using SafariLauncher on an actual iPhone

After following the tutorial on , I managed to create a project. However, I am now facing difficulties in finding a tutorial for running Appium with a web page. I have made edits to customize it according to my needs, for example, launching google.com whic ...

employing personalized CSS styles

When I implement the following code: <div class="metanav"> ... </div> Every element inside that div will inherit the styling of .metanav. But if I duplicate .metanav in the CSS and rename it to A; then update the div's class to: <d ...

Generating divs dynamically with inline styling and utilizing ngFor, while incorporating a conditional check with ngIf in Angular

Currently, I have an Angular component where I am dynamically generating div elements using the ngFor directive. However, I also need to validate a condition before creating each div, and I'm facing challenges when trying to use both ngFor and ngIf in ...

Navigating Through the DOM with Selenium using XPath Axes

Currently, I am developing Selenium tests for a dynamic web page. Within this section of code, I am extracting data from an Excel sheet and verifying if a specific element exists on the webpage. I have annotated the critical part of the code with comments ...

css table cells with overflow

I need help with a table where I have text in one of the td cells that goes beyond the right border and wraps to the next line. What I want is for the overflowing text to be hidden when it reaches the border, showing only the last 3 visible characters repl ...

JsPlumb: Incorrect endpoint drawn if the source `div` is a child of a `div` with `position:absolute`

My current setup involves two blue div elements connected by jsPlumb. You can view the setup here: https://jsfiddle.net/b6phv6dk/1/ The source div is nested within a third black div that is positioned 100px from the top using position: absolute;. It appe ...

What is the best way to reveal a hidden div using JavaScript after a form submission?

jQuery is not a language I am very familiar with, but I am attempting to display a simple animated gif when a form is submitted. When users click 'submit' to upload an image, I want the gif to show to indicate that the image is being uploaded. Th ...

Chrome's CSS columns cannot contain iframes without causing them to escape their

I'm currently attempting to incorporate Iframes within a 3-column grid. HTML <div id="blogPosts"> <div class="blogPost"> <iframe width="100%" src="https://www.youtube.com/embed/YqeW9_5kURI" frameborder="0" allowfullscre ...

Issues have arisen with the main background image in IE7 on ProLoser's AnythingSlider

Check out my website: Everything is working perfectly with AnythingSlider in all browsers except for IE7 - not really a surprise. The background image of the entire page seems to be offset differently depending on the browser size. After some investigatio ...

Using CSS to overlay a background image on top of a background gradient

Struggling to get both a background gradient and a background image (transparent PNG) to display in my div. No matter what, only the color gradient shows up while the image remains hidden. If I use a solid color instead of a gradient, the image displays ju ...

Looking for assistance with transferring a data attribute to a form redirection

I'm seeking assistance with a coding dilemma I've encountered. To provide some background, I have a list of items on my website, each featuring a 'Book Now' button that redirects users to different pages. Recently, I incorporated a mod ...

Oops! Looks like there's a hiccup with merging classes in the debug version of the app

After following the instructions to integrate appodeal into my application, I encountered the following error: Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'. com.android.build.api.transform.TransformException: j ...