import java.awt.Container;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
//主类
public class ComboBox
{
public static void main(String[] args)
{
// 实例化框架类
GUIFrame frame = new GUIFrame();
// 设置默认关闭方式
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 显示框架
frame.setVisible(true);//推荐使用等同frame.show();
}
}
//框架类
class GUIFrame extends JFrame
{
public GUIFrame()
{
setTitle("J组件介绍");//设置框架标题
setSize(640, 480);//设置大小
Container con = getContentPane();//取得内容窗格
GUIPanel panel = new GUIPanel();//实例化面板
con.add(panel);//将面板类添加到内容窗格
}
}
//面板类
class GUIPanel extends JPanel
{
private JLabel label;//声明全局变量
private JComboBox cfont, cstyle, csize;//声明全局变量
public GUIPanel()
{
label = new JLabel("欢迎来到JAVA世界!!!");//标签
//组合框
String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getAvailableFontFamilyNames();//取得当前操作系统的所有字体
String[] style =
{ "常规", "加粗", "倾斜", "粗斜" };
cfont = new JComboBox(fonts);
cstyle = new JComboBox(style);
csize = new JComboBox(new String[]
{ "12", "16", "18", "22", "26", "32", "48" });
cfont.addActionListener(new ActionListener()//动作监听
{
public void actionPerformed(ActionEvent e)
{
String fontName = cfont.getSelectedItem().toString();
Font oldFont = label.getFont();
label.setFont(new Font(fontName, oldFont.getStyle(), oldFont
.getSize()));
}
});
cstyle.addActionListener(new ActionListener()//动作监听
{
public void actionPerformed(ActionEvent e)
{
String fontStyle = cstyle.getSelectedItem().toString();
Font oldFont = label.getFont();
Font f = null;
if ("常规".equals(fontStyle))
{
f = new Font(oldFont.getFontName(), Font.PLAIN, oldFont
.getSize());
}
if ("加粗".equals(fontStyle))
{
f = new Font(oldFont.getFontName(), Font.BOLD, oldFont
.getSize());
}
if ("倾斜".equals(fontStyle))
{
f = new Font(oldFont.getFontName(), Font.ITALIC, oldFont
.getSize());
}
if ("粗斜".equals(fontStyle))
{
f = new Font(oldFont.getFontName(),
Font.BOLD + Font.ITALIC, oldFont.getSize());
}
label.setFont(f);
}
});
csize.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String size = csize.getSelectedItem().toString();
Font oldFont = label.getFont();
int fontSize = Integer.parseInt(size);
label.setFont(new Font(oldFont.getFontName(), oldFont
.getStyle(), fontSize));
}
});
add(label);
add(cfont);
add(cstyle);
add(csize);
}
}