I was given a font finder program, but I need to resize the applet... any suggestions on where and what code is needed to fit the applet to a specific size? If not, is there a setting in eclipse that will work?

public Dimension getPreferredSize() {
        return new Dimension(800,800);// this will not resize the applet
    }

    public void paintComponent(Graphics g) {
        int x = getWidth()/2 - metrics.stringWidth(text)/2;// this will not resize the applet
        int y = getHeight() - 80; // this will not resize the applet
    }
}

Thanks!

Dani AI

Generated

Good catch, — putting sizing in init() is the right move for an applet. Painting math inside paintComponent only controls where you draw inside the component; it does not change the component’s actual size. The real size comes from the host (HTML/appletviewer) or from the top-level/window that contains the component.

If you want a robust solution that works both as a standalone test and when embedded, prefer setting the preferred size on your Swing component and let the container honor it. For a standalone frame use setPreferredSize and pack() so the window matches the component:

panel.setPreferredSize(new Dimension(640,480));
frame.add(panel);
frame.pack();
frame.setVisible(true);

When running as an applet, the HTML attributes width and height determine the displayed size. If you change preferred size at runtime, call revalidate() (so layout managers update) and repaint().

Two extra points that often help troubleshoot:

  • Always do Swing UI creation on the Event Dispatch Thread — applet lifecycle methods may not run there. See the Swing concurrency guidance: Concurrency in Swing.
  • In paintComponent, start with super.paintComponent(g), get current getWidth()/getHeight() and fresh FontMetrics each paint, and avoid hard-coded offsets (use margins/insets instead). That keeps centering and layout correct after any resize.

If development convenience is a priority, test your UI as a JFrame (packable) during development and only rely on HTML width/height when deploying inside a page. For reference on how layout managers consult preferred size, see the Component API on preferred size: Component.setPreferredSize.

Just realized resizing goes under init().

setSize(500, 500);

It works now!

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.