用java swing组件编写一个用JList实现对一句话改变字体大小,如字号从10到32。
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
/**
* @author Hardneedl
*/
final class ChangeFontDemo extends JFrame {
interface Brush {
void doPaint(Graphics g);
}
final static private class FontBrush implements Brush {
private float size;
private final String sampleString = "sample string";
synchronized private void setSize(float size) {this.size = size;}
public void doPaint(Graphics g) {
Graphics gg = g.create();
gg.setColor(Color.BLUE);
gg.setFont(gg.getFont().deriveFont(size));
gg.drawString(sampleString, 40, 40);
gg.dispose();
}
}
final private static FontBrush brush = new FontBrush();
private static final Dimension minSize = new Dimension(300, 200);
private static final Dimension maxSize = new Dimension(1024, 768);
private static final Dimension preferredSize = new Dimension(300, 400);
final static private JComponent canvas = new JComponent() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
brush.doPaint(g);
}
};
public Dimension getMaximumSize() {return maxSize;}
public Dimension getMinimumSize() {return minSize;}
public Dimension getPreferredSize() {return preferredSize;}
public String getTitle() {return "Font Demo";}
private JList sizeList;
ChangeFontDemo() throws HeadlessException {
init();
doLay();
attachListeners();
}
private void init() {
Float[] size = new Float[10];
for (int i = 0, k = 20, j = size.length; i < j; i++,k+=5) size[i] = new Float(k);
sizeList = new JList(size) {
private final Dimension minSize = new Dimension(100, 60);
public Dimension getMinimumSize() {return minSize;}
public Dimension getPreferredSize() {return minSize;}
};
sizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
private void doLay() {
Container container = getContentPane();
container.add(new JScrollPane(sizeList), BorderLayout.NORTH);
container.add(canvas, BorderLayout.CENTER);
pack();
}
private void attachListeners() {
sizeList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
brush.setSize((Float) sizeList.getSelectedValue());
if (canvas.isVisible())canvas.repaint();
}
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {new ChangeFontDemo().setVisible(true);}
});
}
}