我有一个名为fontlist的类,我想使用JTextPane制作下划线字体,但我发现很难做到这一点。粗体或斜体都可以正常工作,但是当我添加下划线代码时,它会给我一些错误。
我的代码是:
import java.awt.*;
import java.awt.font.TextAttribute;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.text.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.plaf.basic.BasicTextPaneUI;
class fontlist extends JFrame implements ItemListener,ActionListener
{
JComboBox jcb,fontSize;
Container content;
JTextPane jta;
JScrollPane jsp;
JToggleButton bold,italic,underline;
Font font;
private static final int[] fontsize = {8,9,10,11,12,14,16,18,20,22,24,26,28,36,48,72};
fontlist()
{
content=getContentPane();
setLayout(null);
setBackground(Color.WHITE);
jcb=new JComboBox();
content.add(jcb);
jcb.setBounds(100,100,100,20);
fontSize=new JComboBox();
content.add(fontSize);
fontSize.setBounds(200,100,40,20);
bold=new JToggleButton("B");
content.add(bold);
bold.setBounds(240,100,45,22);
italic=new JToggleButton("I");
content.add(italic);
italic.setBounds(285,100,45,22);
underline=new JToggleButton("U");
content.add(underline);
underline.setBounds(330,100,45,22);
jta=new JTextPane();
jsp=new JScrollPane(jta);
content.add(jsp);
jsp.setBounds(100,120,500,200);
jcb.addItemListener(this);
fontSize.addItemListener(this);
bold.addActionListener(this);
italic.addActionListener(this);
underline.addActionListener(this);
String fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
for ( int i = 0; i < fonts.length; i++ )
{
jcb.addItem(fonts[i]);
}
for ( int j = 0; j <16; j++ )
{
fontSize.addItem(fontsize[j]);
}
}
public void itemStateChanged(ItemEvent ie)
{
try
{
if (ie.getStateChange() == ItemEvent.SELECTED)
{
int size = new Integer(fontSize.getSelectedItem()+"");
font = new Font(jcb.getSelectedItem().toString(),Font.PLAIN,size);
jta.setFont(font);
}
}
catch(NumberFormatException e){}
}
public void actionPerformed(ActionEvent ae)
{
int size = new Integer(fontSize.getSelectedItem()+"");
if (bold.isSelected() && italic.isSelected() && underline.isSelected() )
{
font = new Font(jcb.getSelectedItem().toString(),Font.BOLD+Font.ITALIC,size);
jta.setFont(font);
}
else if(bold.isSelected() && italic.isSelected())
{
font = new Font(jcb.getSelectedItem().toString(),Font.BOLD+Font.ITALIC,size);
jta.setFont(font);
}
else if(bold.isSelected())
{
font = new Font(jcb.getSelectedItem().toString(),Font.BOLD,size);
jta.setFont(font);
}
else if(italic.isSelected())
{
font = new Font(jcb.getSelectedItem().toString(),Font.ITALIC,size);
jta.setFont(font);
}
else if(underline.isSelected())
{
font = new Font(jcb.getSelectedItem().toString(),Font.UNDERLINE,size);
jta.setFont(font);
}
else
{
font = new Font(jcb.getSelectedItem().toString(),Font.PLAIN,size);
jta.setFont(font);
}
}
public static void main(String args[])
{
fontlist fl=new fontlist();
fl.setSize(700,500);
fl.setVisible(true);
}
}