I need to change the font size after I click. How can I do that - Thanks!

here is the code

import java.applet.*;
import java.awt.*;
import java .awt.event.*;
import javax.swing.*;
import java.util.*;
public class JChangeFont extends JApplet implements ActionListener
  {
   
    JLabel question = new JLabel("Who's number one?");
   JButton click = new JButton("Click");
   JLabel questionText = new JLabel(" ");
   Container con = getContentPane();
	 
	 public void init()
	 	   {

	     con.add(question);
	    con.add(click);
	    con.setLayout(new FlowLayout());
	    click.addActionListener(this);
	   }
		  
   public void actionPerformed(ActionEvent e)
 	   {
	
			 	questionText.setText("Who's number one?");
				con.add(questionText);
				validate();
		}
 }

Dani AI

Generated

showed the right starting point, but adding a new JLabel inside the click handler is unnecessary and can lead to layout headaches. Change the existing label's Font instead, and let Swing repaint the component. Using Font.deriveFont keeps the same family/style while changing size.

Example (change the label's size by 6 points on each click):

click.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        Font f = question.getFont();
        question.setFont(f.deriveFont(f.getSize2D() + 6f)); // increase size
        question.revalidate();
        question.repaint();
    }
});

Notes and troubleshooting:

  • deriveFont(float) preserves the current font family and style; setFont(new Font(...)) replaces them.
  • Prefer revalidate() + repaint() for Swing layouts instead of the older AWT validate(); that ensures the UI updates correctly.
  • Avoid repeatedly adding the same component in an event handler. If a label must appear later, add it once (hidden or empty) during initialization, then call setText() and setFont() when needed.
  • All Swing updates should run on the Event Dispatch Thread. See Oracle's Swing concurrency guidance for details: Swing concurrency guide.
  • For Font API specifics, refer to the Javadoc: Font class javadoc.

Regarding the "marked solved" note from : the above gives an explicit, minimal fix that matches the original intent without adding extra components.

Why is this marked as solved? If you solved, why didn't you post solution?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.