Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7958157
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T04:22:40+00:00 2026-06-04T04:22:40+00:00

Normally, I would just create the JLabel using a string as the first parameter

  • 0

Normally, I would just create the JLabel using a string as the first parameter and JLabel.CENTER as the second parameter; adding the label to the panel using BorderLayout.CENTER would then cause the text in the label to be aligned in the center of the panel.

However, I’m using the ‘RichJLabel’ class in order to get a drop shadow on my text. To do this, it overrides Component.paintComponent in such a way that the alignment information is lost, and the label’s text is drawn in the top left of the panel no matter what I do.

From what I understand, the workaround for this is to encase the label inside of another panel; that way, I can align the panel itself inside the parent panel, but I’m uncertain of how exactly to do this.

My complete goal is to:

  • Figure out what font size a given string needs in order to fill up its parent JPanel
  • Add a drop shadow to that text
  • Center the text within its JPanel

Here’s what I’ve got so far:

import java.awt.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;

public class RichJLabel extends JLabel {

    private int tracking;

    public RichJLabel(String text, int tracking) {
        super(text, JLabel.CENTER);
        this.tracking = tracking;
    }

    private int left_x, left_y, right_x, right_y;
    private Color left_color, right_color;

    public void setLeftShadow(int x, int y, Color color) {
        left_x = x;
        left_y = y;
        left_color = color;
    }

    public void setRightShadow(int x, int y, Color color) {
        right_x = x;
        right_y = y;
        right_color = color;
    }

    public Dimension getPreferredSize() {
         String text = getText();
         FontMetrics fm = this.getFontMetrics(getFont());

         int w = fm.stringWidth(text);
         w += (text.length()-1)*tracking;
         w += left_x + right_x;
         int h = fm.getHeight();
         h += left_y + right_y;

         return new Dimension(w,h); 
}

public void paintComponent(Graphics g) {

        ((Graphics2D)g).setRenderingHint(
            RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        char[] chars = getText().toCharArray();

        FontMetrics fm = this.getFontMetrics(getFont());

        int h = fm.getAscent();
        int x = 0;

        for(int i=0; i<chars.length; i++) {
            char ch = chars[i];
            int w = fm.charWidth(ch) + tracking;

            g.setColor(left_color);
            g.drawString(""+chars[i],x-left_x,h-left_y);

            g.setColor(right_color);
            g.drawString(""+chars[i],x+right_x,h+right_y);

            g.setColor(getForeground());
            g.drawString(""+chars[i],x,h);

            x+=w;
    }

        ((Graphics2D)g).setRenderingHint(
            RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT);

    } // end paintComponent()

public static void main(String[] args) {

  JPanel panel1 = new JPanel( new BorderLayout() );
  panel1.setBackground( Color.BLUE );
  panel1.setBorder( BorderFactory.createBevelBorder( BevelBorder.LOWERED ));

  JPanel interiorPanel = new JPanel( new BorderLayout() );
  panel1.add(interiorPanel, BorderLayout.CENTER);
  RichJLabel label = new RichJLabel("100", 0);
  label.setHorizontalAlignment(JLabel.CENTER);
  label.setVerticalAlignment(JLabel.CENTER);
  label.setVisible( true );
  label.setForeground( Color.YELLOW );

  interiorPanel.add(label, BorderLayout.CENTER);
  label.setFont(new Font("Arial", Font.BOLD, 140));
  label.setFont(label.getFont().deriveFont(140f));


  //resize code
  Font labelFont = label.getFont();
  String labelText = label.getText();
  int stringWidth = label.getFontMetrics(labelFont).stringWidth(labelText);
  int componentWidth = interiorPanel.getWidth();

  // Find out how much the font can grow in width.
  double widthRatio = (double)componentWidth / (double)stringWidth;
  int newFontSize = (int)(labelFont.getSize() * widthRatio);
  int componentHeight = interiorPanel.getHeight();

  // Pick a new font size so it will not be larger than the height of label.
  int fontSizeToUse = Math.min(newFontSize, componentHeight);
  // Set the label's font size to the newly determined size.
  label.setFont(new Font(labelFont.getName(), Font.BOLD, fontSizeToUse));
  label.setLeftShadow(-3,-3,Color.BLACK);     

  // drop shadow w/ highlight
  label.setRightShadow(2,3,Color.black);
  label.setForeground(Color.gray);

  JFrame frame = new JFrame("Label SSCCEE");
  frame.getContentPane().add(panel1);
  frame.pack();
  frame.setVisible(true);
 }
}

What it does right now is this:

gray box inside blue panel

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T04:22:41+00:00Added an answer on June 4, 2026 at 4:22 am

    The code was checking for the size of the container too soon. Before it is displayed, it has a width/height of 0.

    Text with shadow

    Altered code

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.BevelBorder;
    
    public class RichJLabel extends JLabel {
    
        private int tracking;
    
        public RichJLabel(String text, int tracking) {
            super(text, JLabel.CENTER);
            this.tracking = tracking;
        }
    
        private int left_x, left_y, right_x, right_y;
        private Color left_color, right_color;
    
        public void setLeftShadow(int x, int y, Color color) {
            left_x = x;
            left_y = y;
            left_color = color;
        }
    
        public void setRightShadow(int x, int y, Color color) {
            right_x = x;
            right_y = y;
            right_color = color;
        }
    
        public Dimension getPreferredSize() {
             String text = getText();
             FontMetrics fm = this.getFontMetrics(getFont());
    
             int w = fm.stringWidth(text);
             w += (text.length()-1)*tracking;
             w += left_x + right_x;
             int h = fm.getHeight();
             h += left_y + right_y;
    
             return new Dimension(w,h);
    }
    
    public void paintComponent(Graphics g) {
    
            ((Graphics2D)g).setRenderingHint(
                RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            char[] chars = getText().toCharArray();
    
            FontMetrics fm = this.getFontMetrics(getFont());
    
            int h = fm.getAscent();
            int x = 0;
    
            for(int i=0; i<chars.length; i++) {
                char ch = chars[i];
                int w = fm.charWidth(ch) + tracking;
    
                g.setColor(left_color);
                g.drawString(""+chars[i],x-left_x,h-left_y);
    
                g.setColor(right_color);
                g.drawString(""+chars[i],x+right_x,h+right_y);
    
                g.setColor(getForeground());
                g.drawString(""+chars[i],x,h);
    
                x+=w;
        }
    
            ((Graphics2D)g).setRenderingHint(
                RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT);
    
        } // end paintComponent()
    
    public static void main(String[] args) {
    
      JPanel panel1 = new JPanel( new BorderLayout() );
      panel1.setBackground( Color.BLUE );
      panel1.setBorder( BorderFactory.createBevelBorder( BevelBorder.LOWERED ));
    
      JPanel interiorPanel = new JPanel( new BorderLayout() );
      panel1.add(interiorPanel, BorderLayout.CENTER);
      RichJLabel label = new RichJLabel("100", 0);
      label.setLeftShadow(-3,-3,Color.BLACK);
    
      // drop shadow w/ highlight
      label.setRightShadow(2,3,Color.black);
    
      label.setHorizontalAlignment(JLabel.CENTER);
      label.setVerticalAlignment(JLabel.CENTER);
      label.setVisible( true );
      label.setForeground( Color.YELLOW );
    
      interiorPanel.add(label, BorderLayout.CENTER);
      label.setFont(new Font("Arial", Font.BOLD, 140));
      label.setFont(label.getFont().deriveFont(140f));
    
      //resize code
      Font labelFont = label.getFont();
    
      JFrame frame = new JFrame("Label SSCCEE");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.setContentPane(panel1);
      frame.pack();
      frame.setVisible(true);
    
      int componentWidth = interiorPanel.getWidth();
      String labelText = label.getText();
      int stringWidth = label.getFontMetrics(labelFont).stringWidth(labelText);
      // Find out how much the font can grow in width.
      double widthRatio = (double)componentWidth / (double)stringWidth;
      int newFontSize = (int)(labelFont.getSize() * widthRatio);
      int componentHeight = interiorPanel.getHeight();
    
      // Pick a new font size so it will not be larger than the height of label.
      int fontSizeToUse = Math.min(newFontSize, componentHeight);
      System.out.println("fontSizeToUse: " + fontSizeToUse);
      if (fontSizeToUse<1) {
          System.err.println("Font size less than 1!");
          System.exit(1);
      }
    
      // Set the label's font size to the newly determined size.
      label.setFont(new Font(labelFont.getName(), Font.BOLD, fontSizeToUse));
      label.setForeground(Color.gray);
     }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would normally just create a static class like StandardFooColors and create a static
Normally I would just do this. $str = preg_replace('#(\d+)#', ' $1 ', $str); If
Normally I would just use URL GET parameters but CodeIgniter doesn't seem to like
If I have a table of a hundred users normally I would just set
So I m just trying to test my modules, normally i would go and
Normally I would go: bgwExportGrid.RunWorkerCompleted += ReportManager.RunWorkerCompleted; The ReportManager class is a static class
Normally it would be in such a structure: ../application/modules/somemodule/views/scripts/index/index.phtml How I move it to:
Normally I would have one junit test that shows up in my integration server
Normally I would do select top (1) * from table where id active =
This kind of code would normally work in PHP, but since the scope is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.