Problem to change a font size.

L

lov2code

Hi,

I tried to change font size by changing an existing font object, it
did not work. Anybody can help with this? Thanks.

=========================================================
import java.awt.*;
import java.awt.event.*;
import javax.swing.JApplet;
import javax.swing.*;
import java.util.Random;

public class test extends JApplet implements ActionListener{
private MyFont cacheFont;
private Random rand;

public void init()
{
Container container = getContentPane();
container.setLayout( new BorderLayout() );

JButton button1;
button1 = new JButton( "Random Font");
button1.addActionListener(this);
container.add(button1, BorderLayout.SOUTH );

cacheFont = new MyFont();
rand = new Random();
}

public void actionPerformed( ActionEvent event )
{
cacheFont.setSize(rand.nextInt(30) + 20);
Graphics g = getGraphics();
update(g);
g.setFont( cacheFont );
//print out changed size, but still draw size 12.
g.drawString( "Font size = " + cacheFont.getSize(), 15,15 );
}

private class MyFont extends Font
{
public MyFont()
{
super("Serif", Font.BOLD, 12);
}

public void setSize(int size)
{
this.size = size;
}
}

}
 
F

Fahd Shariff

To tell you the truth, i dont know why your method isn't working. I
can, however, propose some solutions:

1. Create a new Font every time:
g.setFont(new Font("Serif", Font.BOLD, rand.nextInt(30) + 20)) ;

2. Use the deriveFont() method:
g.setFont(cacheFont.deriveFont(new Integer(rand.nextInt(30) +
20).floatValue())) ;
 
F

Fahd Shariff

To tell you the truth, i dont know why your method isn't working. I
can, however, propose some solutions:

1. Create a new Font every time:
g.setFont(new Font("Serif", Font.BOLD, rand.nextInt(30) + 20)) ;

2. Use the deriveFont() method:
g.setFont(cacheFont.deriveFont(new Integer(rand.nextInt(30) +
20).floatValue())) ;
 
L

lov2code

To tell you the truth, i dont know why your method isn't working. I
can, however, propose some solutions:

1. Create a new Font every time:
g.setFont(new Font("Serif", Font.BOLD, rand.nextInt(30) + 20)) ;

2. Use the deriveFont() method:
g.setFont(cacheFont.deriveFont(new Integer(rand.nextInt(30) +
20).floatValue())) ;
Thank you, but I would like not to create an new object.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top