import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButton;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
//主类
public class Sample
{
public static void main(String[] args)
{
// 实例化框架类
SampleFrame frame = new SampleFrame();
// 设置默认关闭方式
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 显示框架
frame.setVisible(true);//推荐使用等同frame.show();
}
}
//框架类
class SampleFrame extends JFrame
{
private JMenuItem open;
public SampleFrame()
{
setTitle("J组件标签介绍");//设置框架标题
setSize(640, 480);//设置大小
// 菜单系统 放在JFrame里面
//菜单栏
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);//将菜单栏添加到框架上
//菜单
JMenu file = new JMenu("File");
file.setMnemonic('F');//设置菜单助记符 只能用此方法
//菜单项
open = new JMenuItem("Open...");
open.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
MyDialog d = new MyDialog(SampleFrame.this);
d.setVisible(true);
String ss = d.getS();
open.setText(ss);
}
});
ImageIcon icon = new ImageIcon("D:/编程图像/OTHER/FLOWER.GIF"); //添加图标
open.setIcon(icon);//设置菜单的图标
JMenuItem save = new JMenuItem("Save");
JMenuItem saveas = new JMenuItem("SaveAs");
saveas.setEnabled(false);//变灰
JMenuItem print = new JMenuItem("Print");
print.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,
InputEvent.CTRL_MASK));//设置快捷键
JMenuItem setup = new JMenuItem("Setup", 'u');//设置助记符
JMenuItem exit = new JMenuItem("Exit");
exit.setMnemonic('x');//设置助记符 在相同的菜单中不能有相同 在不同的可以
exit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
System.exit(0);
}
});
file.add(open);
file.add(save);
file.add(saveas);
file.addSeparator();//分隔符,添加在菜单上
file.add(print);
file.add(setup);
file.add(exit);
JMenu edit = new JMenu("Edit");
JMenu format = new JMenu("Format");
JMenu second = new JMenu("Second");//二级菜单,菜单添加到菜单中就可以形成菜单
//菜单项添加在菜单上(不管这个菜单项是几级菜单)
//原则上菜单可以嵌套多级,但是建议不要超过3级
JMenuItem one = new JMenuItem("One");
JMenuItem two = new JMenuItem("two");
format.add(second);
second.add(one);
second.add(two);
//带有单选、多选效果的菜单项
JRadioButtonMenuItem rbm1 = new JRadioButtonMenuItem("太阳");//单选
JRadioButtonMenuItem rbm2 = new JRadioButtonMenuItem("月亮");
JCheckBoxMenuItem cbm1 = new JCheckBoxMenuItem("QQ");//多选
JCheckBoxMenuItem cbm2 = new JCheckBoxMenuItem("MSN");
ButtonGroup group = new ButtonGroup();
group.add(rbm1);
group.add(rbm2);
second.add(rbm1);
second.add(rbm2);
second.add(cbm1);
second.add(cbm2);
format.add(rbm1);//后者生效
format.add(rbm2);
format.add(cbm1);
format.add(cbm2);
JMenu help = new JMenu("Help");
JMenuItem about = new JMenuItem("About");
about.setAccelerator(KeyStroke.getKeyStroke("F1"));//快捷键
help.add(about);
bar.add(file);
bar.add(edit);
bar.add(format);
bar.add(help);
Container con = getContentPane();//取得内容窗格
SamplePanel panel = new SamplePanel(SampleFrame.this);//实例化面板
con.add(panel);//将面板类添加到内容窗格
//右键菜单
pop = new JPopupMenu();
JMenuItem copy = new JMenuItem("Copy");
JMenuItem cut = new JMenuItem("Cut");
JMenuItem paste = new JMenuItem("Paste");
pop.add(copy);
pop.add(cut);
pop.addSeparator();
pop.add(paste);
addMouseListener(new MouseAdapter()
{
//鼠标弹出事件
public void mouseReleased(MouseEvent e)
{
//判断是否是弹出菜单触发器(过滤左键)
if(e.isPopupTrigger())
{
pop.show(e.getComponent(), e.getX(), e.getY());
}
}
});
}
private JPopupMenu pop;
}
//面板类
class SamplePanel extends JPanel
{
private JLabel label;//声明全局变量
public SamplePanel(final SampleFrame frame)//构造器,一个类中的方法和内部类是平级的
{
//标签
label = new JLabel("用户名");//设置标签名字
Font font = new Font("华文行楷", Font.BOLD + Font.ITALIC, 30);//BOLD=1
label.setFont(font);//设置字体
Color color = new Color(200, 12, 36);
//前景色和后景色
label.setForeground(color);//设置前景色
label.setOpaque(true);//设置透明,label默认不透明,设置背景色的前置条件
label.setBackground(Color.white);//设置背景色
/*
* Toolkit kit = Toolkit.getDefaultToolkit(); Image image =
* kit.getImage("D:/编程图像/OTHER/EARTH.GIF"); Icon icon = new
* ImageIcon(image);//图像变图标
*/
Icon icon = new ImageIcon("D:/编程图像/OTHER/EARTH.GIF");
//也可以写成ImageIcon = new ImageIcon(...)
label.setIcon(icon);//因为标签只能设置为图标
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.TOP);
label.setText("密码:");//重设置标签文本
label.setEnabled(true);//设置标签是否可用,默认可用true
label.setVisible(true);//设置是否可见
//除了bool值以外得到方法都使用is..否则就用get()
System.out.println(label.getText());
System.out.println(label.isVisible());
add(label);
//按钮
JButton button = new JButton("按钮");
Font font1 = new Font("宋体", Font.ITALIC, 32);
button.setFont(font1);
Color color1 = new Color(200, 12, 36);
button.setForeground(color1);
button.setOpaque(true);
button.setBackground(Color.white);
Icon icon1 = new ImageIcon("D:/编程图像/华人精品LOGO/华人作品静态类/0416.GIF");
button.setIcon(icon1);
button.setToolTipText("按钮提示");
button.addActionListener(new ActionListener()//动作监听
{
//new后面的这个并非接口而是实现该接口的匿名内部类
public void actionPerformed(ActionEvent e)
{
if (label.isVisible())
{
label.setVisible(false);
} else
{
label.setVisible(true);
}
JOptionPane.showMessageDialog(null, "******");
}
});
button.setHorizontalTextPosition(JButton.CENTER);
button.setVerticalTextPosition(JButton.TOP);
button.setText("点我:");
button.setEnabled(true);
button.setVisible(true);
System.out.println(button.getText());
System.out.println(button.isVisible());
add(button);
//文本框
field = new JTextField(10);
field.setText("要放假了!");
field.setEditable(true);//设置是否可编辑
field.setEnabled(true);//设置是否可用
System.out.println(field.getText());//取的文字的值
add(field);
JButton ok = new JButton("加五");
ok.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String s = field.getText();
if ("niit".equals(s))
{
JOptionPane.showMessageDialog(null, "恭喜!");
} else
{
int a = Integer.parseInt(s);
int result = a + 5;
JOptionPane.showMessageDialog(null, "" + result);
}
}
});
add(ok);
//文本域
area = new JTextArea(5, 10);
area.setLineWrap(true);//控制自动换行
//滚动窗格(带有滚动条的面板)
JScrollPane sp = new JScrollPane(area);
//设置单词风格换行
area.setWrapStyleWord(true);
add(sp);
//密码框
jfield = new JPasswordField(10);
jfield.setEchoChar('$');
add(jfield);
JButton checkPass = new JButton("检查密码");
checkPass.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
char[] ch = jfield.getPassword();
String s = new String(ch);
JOptionPane.showMessageDialog(null, s);
}
});
add(checkPass);
//复选框
cb1 = new JCheckBox("体育");
cb2 = new JCheckBox("旅游", true);//默认选中
cb3 = new JCheckBox("看书");
cb4 = new JCheckBox("音乐");
cb4.setSelected(true);//默认选中
cb4.isSelected();
add(cb1);
add(cb2);
add(cb3);
add(cb4);
cb1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (cb1.isSelected())
{
JOptionPane.showMessageDialog(null, "你选中了");
} else
{
JOptionPane.showMessageDialog(null, "你取消了选中");
}
}
});
JButton ch = new JButton("确定");
ch.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String s = "";
if (cb1.isSelected())
{
s = s + cb1.getText() + " ";
}
if (cb2.isSelected())
{
s = s + cb2.getText() + " ";
}
if (cb3.isSelected())
{
s = s + cb3.getText() + " ";
}
if (cb4.isSelected())
{
s = s + cb4.getText() + " ";
}
JOptionPane.showMessageDialog(null, s);
}
});
add(ch);
//单选按钮
JRadioButton r1 = new JRadioButton("春", true);//默认选中
JRadioButton r2 = new JRadioButton("夏");
JRadioButton r3 = new JRadioButton("秋");
JRadioButton r4 = new JRadioButton("冬");
r3.setSelected(true);//默认选中
ButtonGroup group = new ButtonGroup();//按钮组(为按钮添加逻辑约束)
group.add(r1);//r1到r4只能选一个
group.add(r2);
group.add(r3);
group.add(r4);
//添加一个面板,设置边框,进行(外观约束)
JPanel p = new JPanel();
Border border = BorderFactory.createTitledBorder("你最喜欢的季节");
p.setBorder(border);//为面板设置边框
p.add(r1);
p.add(r2);
p.add(r3);
p.add(r4);
RadioAction ra = new RadioAction();
r1.addActionListener(ra);
r2.addActionListener(ra);
r3.addActionListener(ra);
r4.addActionListener(ra);
add(p);
//组合框
String[] str =
{ "电视机", "电冰箱", "电话机", "电水壶", "电脑", "电火锅", "电热毯", "电磁炉", "洗衣机", "日光灯",
"电动车" };
//取得当前操作系统的所有字体
String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getAvailableFontFamilyNames();
combo = new JComboBox(str);
// combo.setSelectedIndex(2);//使用下标设置默认值
//使用对象来设置默认值
combo.setSelectedItem("电话机");
combo.setMaximumRowCount(5);//设置最大可见行数
combo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int idx = combo.getSelectedIndex();
Object obj = combo.getSelectedItem();
String s = obj.toString();
JOptionPane.showMessageDialog(null, "你选中了" + (idx + 1)
+ "个选项,内容是:" + s);
}
});
add(combo);
label1 = new JLabel("欢迎来到JAVA世界!!!");
String[] fonts1 = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getAvailableFontFamilyNames();
String[] style =
{ "常规", "加粗", "倾斜", "粗斜" };
cfont = new JComboBox(fonts1);
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();
label1.setFont(new Font(fontName, oldFont.getStyle(), oldFont
.getSize()));
}
});
cstyle.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String fontStyle = cstyle.getSelectedItem().toString();
Font oldFont = label1.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());
}
label1.setFont(f);
}
});
csize.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String size = csize.getSelectedItem().toString();
Font oldFont = label1.getFont();
int fontSize = Integer.parseInt(size);
label1.setFont(new Font(oldFont.getFontName(), oldFont
.getStyle(), fontSize));
}
});
add(label1);
add(cfont);
add(cstyle);
add(csize);
//列表框
v = new Vector();
v.addElement("电视机");
v.addElement("电冰箱");
v.addElement("电话机");
v.addElement("电水壶");
v.addElement("电脑");
v.addElement("电火锅");
v.addElement("电动车");
v.addElement("电热毯");
v.addElement("洗衣机");
v.addElement("日光灯");
list = new JList(v);
v.removeElement("电视机");//删除内容
v.addElement("NIIT");//添加内容
list.setVisibleRowCount(5);//设置可见行数
list.setSelectedIndex(1);//设置默认选中
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
list.setSelectedIndices(new int[]
{ 1, 3, 4 });//设置默认选中多个
list.addListSelectionListener(new ListSelectionListener()
{
//当状态改变时响应事件
public void valueChanged(ListSelectionEvent e)
{
//可以不设全局变量,li和list1是指向同一内存的不同名称的对象
JList li = (JList) e.getSource();//取得选中的对象列表,得到点击JList产生的事件
Object[] objs = li.getSelectedValues();
for (int i = 0; i < objs.length; i++)//遍历数组
{
if (e.getValueIsAdjusting())//触发刚才发生的事件,去除丢失状态的事件
{
Object obj = objs[i];
String s = obj.toString();
System.out.println(s);
}
}
}
});
//list = new JList(fonts);
JScrollPane sp1 = new JScrollPane(list);//加上滚动条
add(sp1);
JButton blist = new JButton("OK");
blist.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
v.addElement("NIIT");
//list.updateUI();//刷新列表框
SwingUtilities.updateComponentTreeUI(frame);//刷新整个界面
}
});
add(blist);
}
class RadioAction implements ActionListener
{
public void actionPerformed(ActionEvent e)//e为所有事件的封装
{
String s = "";
//取得触发事件的对象(四个单选按钮之一)
JRadioButton rb = (JRadioButton) e.getSource();
if ("春".equals(rb.getText()))
{
s = "春";
}
if ("夏".equals(rb.getText()))
{
s = "夏";
}
if ("秋".equals(rb.getText()))
{
s = "秋";
}
if ("冬".equals(rb.getText()))
{
s = "冬";
}
area.setText(area.getText() + s + "/r/n");
//自动追加的末尾,不会覆盖原来的内容
//area.append(s + "/r/n");
}
}
private JTextField field;
private JPasswordField jfield;
private JTextArea area;
private JCheckBox cb1, cb2, cb3, cb4;
private JComboBox combo;
private JLabel label1;
private JComboBox cfont, cstyle, csize;
private Vector v;
private JList list;
}
class MyDialog extends JDialog
{
private JTextField field1;
private String s;
public MyDialog(SampleFrame frame)
{
super(frame, true);
setTitle("对话框");
setSize(200, 160);
Container con = getContentPane();
JPanel panel = new JPanel();
field1 = new JTextField(10);
JButton button = new JButton("OK");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
s = field1.getText();
dispose();//销毁界面释放内存
//setVisible(false);//隐藏界面,不释放内存
}
});
con.add(panel);
panel.add(field1);
panel.add(button);
}
public String getS()
{
return s;
}
}