java实例应用

更新时间:2024-05-07 01:47:01 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

实例1 产生自己的控件

import java.awt.*;

import java.awt.event.*; import javax.swing.*;

//颜色选择下拉框演示

public class IconComboBoxDemo extends JFrame{ JLabel iconLabel=null; //用来响应列表框选择的变化 JComboBox iconComboBox=null; //定制的选择下拉框

public IconComboBoxDemo(){

//定义Object二维数组,用于初始化下拉框,参数依次为图标,显示文本,提示文本 Object[][] obj={

{new ImageIcon(\旅游\提供旅游的最新信息\

{new ImageIcon(\音乐\提供最新的音乐资讯,古典的、流行的...\ {new ImageIcon(\聊天\与朋友聊天\ {new ImageIcon(\影视\影视娱乐\ {new ImageIcon(\家居\家居世界\ };

//初始化下拉框

iconComboBox = new JComboBox();

iconComboBox.setMaximumRowCount(3); //设置最大可视行数 iconComboBox.setRenderer(new IconRenderer()); //设置单元绘制器 for (int i=0;i

//初始化iconLabel信息 iconLabel = new JLabel();

//下拉框事件处理,用匿名类实现

iconComboBox.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent evt){ //处理事件

Object[] obj = (Object[])iconComboBox.getSelectedItem(); //得到选择的内容,此处为一维数组

iconLabel.setIcon((Icon)obj[0]); //设置iconLabel的图标 iconLabel.setText(obj[1].toString()); //设置iconLabel的文本 } });

//增加组件到主窗体上

this.getContentPane().setLayout(new BorderLayout()); //设置布局管理器

this.getContentPane().add(iconComboBox,BorderLayout.NORTH); //在上方增加下拉框 this.getContentPane().add(iconLabel,BorderLayout.CENTER); //在中间增加iconLabel,用于响应选择的变化

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序 this.setSize(350,260); //设置窗口尺寸 this.setVisible(true); //显示窗口 }

public static void main(String[] args){ new IconComboBoxDemo(); } }

import java.awt.*; import javax.swing.*;

import javax.swing.border.LineBorder;

//带图标下拉框的单元绘制器,从JLabel类扩展,实现ListCellRenderer接口

public class IconRenderer extends JLabel implements ListCellRenderer{

public Component getListCellRendererComponent(JList list, Object obj, int row, boolean sel, boolean hasFocus) {

Object[] cell = (Object[])obj; //得到行的参数 setIcon((Icon)cell[0]); //设置图标 setText(cell[1].toString()); //设置文本

setToolTipText(cell[2].toString()); //设置提示文本 setBorder(new LineBorder(Color.WHITE)); //设置边界 if (sel){

setForeground(Color.MAGENTA); //如果选中了,设置文本颜色为品红色 } else{

setForeground(list.getForeground()); //如果未选中,设置文本颜色为默认色 }

return this; } }

实例2 控件的排布示例

import java.awt.*; import javax.swing.*;

public class BorderLayoutDemo extends JFrame{

public static void main( String args[] ){ //构造函数 Container container = getContentPane(); //得到容器

container.setLayout( new BorderLayout() ); //设置布局管理器为Borderlayout container.add(new JButton(\ //增加按钮 container.add(new JButton(\ container.add(new JButton(\ container.add(new JButton(\ container.add(new JButton(\

setTitle(\演示\ //设置窗口标题 setSize(280,200); //设置主窗口尺寸 setVisible(true); //设置主窗口可视

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序 }

public static void main( String args[] ){ new BorderLayoutDemo(); } }

import java.awt.*; import javax.swing.*;

public class GridBagLayoutDemo extends JFrame {

public GridBagLayoutDemo() { //构造函数

Container contentPane = getContentPane(); //得到容器

contentPane.setLayout(new GridBagLayout()); //设置布局管理器 JLabel labelName=new JLabel(\姓名\ //姓名标签 JLabel labelSex=new JLabel(\性别\ //性别标签 JLabel labelAddress=new JLabel(\住址\ //住址标签

JTextField textFieldName = new JTextField(); //性名文本域

JTextField textFieldAddress = new JTextField(); //地址文本域 JComboBox comboBoxSex = new JComboBox(); //性别组合框 comboBoxSex.addItem(\男\ //增加选择项 comboBoxSex.addItem(\女\ JButton buttonConfirm=new JButton(\确定\ //确定按钮 JButton buttonCancel=new JButton(\退出\ //退出按钮 //增加各个组件 contentPane.add(labelName, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 ,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 0), 0, 0)); contentPane.add(textFieldName, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 0, 5), 0, 0)); contentPane.add(comboBoxSex, new GridBagConstraints(3, 0, 1, 1, 1.0, 0.0 ,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 0, 5), 0, 0)); contentPane.add(labelSex, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 ,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 0, 0), 0, 0)); contentPane.add(buttonConfirm, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0

,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 3, 0), 0, 0)); contentPane.add(buttonCancel, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0 ,GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 0, 3, 0), 0, 0)); contentPane.add(labelAddress, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 ,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 0), 0, 0)); contentPane.add(textFieldAddress, new GridBagConstraints(1, 1, 3, 1, 0.0, 0.0 ,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 0, 5), 0, 0)); setTitle(\演示\ //设置窗口标题 setSize(300,140); //设置窗口尺寸 setVisible(true); //设置窗口可见 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序 } public static void main(String args[]) { new GridBagLayoutDemo(); } }

实例3 控件的相互控制与消息传递

import java.awt.*;

import java.awt.event.*; import javax.swing.*;

//控件的相互控制与消息传递

public class ActionDemo extends JFrame{ JTextField jtfName; //名字输入域 JTextArea jtaChat; //显示聊天信息 JTextArea jtaInput; //输入消息 JButton jbSend; //发送消息按钮 JButton jbLink; //连接按牛 JButton jbUnlink; //断开按牛 public ActionDemo(){ super(\控件的相互控制\ //调用父类构造函数 Container container=this.getContentPane(); //得到容器 JPanel p=new JPanel(); //初始化一个面板 jtfName=new JTextField(10); //初始化名字输入域 Box box1=new Box(BoxLayout.X_AXIS); //初始化一个Box p.add(new JLabel(\昵称:\ //增加昵称标签 p.add(jtfName); //增加名字输入域 box1.add(jbLink); box1.add(jbUnlink);

container.add(p,BorderLayout.NORTH); //在容器上增加面板

jtaChat=new JTextArea(); //初始化信息显示文本框

container.add(new JScrollPane(jtaChat),BorderLayout.CENTER); //在容器上增加信息显示文本框 Box box=new Box(BoxLayout.X_AXIS); //初始化一个Box jtaInput=new JTextArea(3,20); //初始化消息输入域 jbSend=new JButton(); //初始化发送按钮 box.add(new JScrollPane(jtaInput)); //增加消息输入域 box.add(jbSend); container.add(box,BorderLayout.SOUTH); //在容器上增加box

Action sendMessage = new AbstractAction() { //发送消息Action public void actionPerformed(ActionEvent e){ replaceMessage(); //更新消息显示框 } }; jtaInput.getInputMap().put(KeyStroke.getKeyStroke(\ //键盘事件处理,按受回车事件 jtaInput.getActionMap().put(\ //回车时的处理(调用发送消息Action) jbSend.setAction(sendMessage); //设置命令为发送消息 jbSend.setText(\发送\ //设置按钮文本 this.setLocation(300,300); setSize(400,200); //设置窗口尺寸 setVisible(true); //设置窗口可视 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序 } private void replaceMessage(){ String message=jtfName.getText()+\ //得到消息文本 jtaChat.insert(message,jtaChat.getDocument().getLength()); //插入消息到显示域未端 jtaInput.setText(\ //清空输入消息域 }

public static void main(String[] args){ new ActionDemo(); } }

实例4 彩色列表框

import java.awt.*; import javax.swing.*;

import javax.swing.border.*;

//彩色列表框的Renderer,须实现接口ListCellRenderer

public class ColorRenderer extends JLabel implements ListCellRenderer { //实现接口中的getListCellRendererComponent方法

public Component getListCellRendererComponent(JList list, Object obj, int row, boolean sel, boolean hasFocus) { if (hasFocus || sel) { //设置选中时的边界

setBorder(new MatteBorder(2, 10, 2, 10, list.getSelectionBackground())); }

else { //设置未选中时的边界

setBorder(new MatteBorder(2, 10, 2, 10, list.getBackground())); }

Color c=(Color)obj; //得到该行的颜色值 setForeground(c); //设置颜色 setText(c.toString()); //设置文本 return this; } }

import java.awt.*; import javax.swing.*;

import javax.swing.event.*;

//彩色列表框示例

public class JListDemo extends JFrame{ Container container; //容器 JTextField selectedText; //文本域,反映选择的颜色值 JList list; //列表框 JPanel selectedColor; //Panel,以选择的颜色为背景绘制

public JListDemo(){ //构造函数

container=getContentPane(); //得到容器

container.setLayout(new BorderLayout()); //设置布局管理器,不是必须的,Container默认为BorderLayout

Color[]

colors={Color.orange,Color.pink,Color.red,Color.black,Color.blue,Color.cyan,Color.green,Color.lightGray}; //列表框内容 list=new JList(colors); JScrollPane scrollPane = new JScrollPane(list); //以list初始化滚动窗格 selectedText=new JTextField(20); selectedColor=new JPanel(); selectedColor.setPreferredSize(new Dimension(20,20)); //设置panel的首选尺寸 container.add(selectedText,BorderLayout.NORTH); //增加组件到容器上

container.add(scrollPane,BorderLayout.CENTER); container.add(selectedColor,BorderLayout.SOUTH);

list.setCellRenderer(new ColorRenderer()); //设置Renderer list.addListSelectionListener( //事件处理 new ListSelectionListener(){

public void valueChanged(ListSelectionEvent event){ //选择值有改变 Color c=(Color)list.getSelectedValue(); //得到选择的颜色

selectedText.setText(\选择颜色:\R=\G =\B=\ //设置文本域文本

selectedColor.setBackground(c); //设置panel的颜色 } });

setSize(300,200); //设置窗口尺寸 setVisible(true); //设置窗口可视

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序 }

public static void main(String[] args){ new JListDemo(); } }

实例5 圆形的按钮

import java.awt.*;

import javax.swing.*;

public class RoundButton extends JButton {

public RoundButton(String label) {

super(label); //调用父类构造函数

setContentAreaFilled(false); //不自行绘制按钮背景 }

//绘制圆和标签

protected void paintComponent(Graphics g) { if (getModel().isArmed()) { //鼠标点击时

g.setColor(Color.lightGray); //颜色为灰色 } else {

g.setColor(getBackground()); //置按钮颜色 }

g.fillOval(0, 0, getSize().width, getSize().height); //绘制圆 super.paintComponent(g); //调用父类函数,绘制其余部分 }

//绘制边框

protected void paintBorder(Graphics g) {

g.setColor(getForeground()); //设置边框颜色

g.drawOval(0, 0, getSize().width-1, getSize().height-1); //在边界上绘制一个椭圆 } }

import java.awt.*;

import java.awt.event.*; import javax.swing.*;

public class RoundButtonDemo extends JFrame{ private int clickCount=0; //记录安钮的点击次数 private JButton button1; private JButton button2; public RoundButtonDemo() { button1 = new RoundButton(\这是一个圆形按钮\ //初始化按钮一

Dimension dim=button1.getPreferredSize(); //得到按钮一的最佳尺寸

double maxsize=Math.max(dim.getHeight(),dim.getWidth()); //得到长宽中的最大值 dim.setSize(maxsize,maxsize); //更改长宽为长宽中的最大值 button1.setPreferredSize(dim); //设置最佳尺寸

button2 = new RoundButton(\点击了: \次\ //初始化按钮二 button1.setBackground(Color.blue); //设置按钮的背景颜色 button2.setBackground(Color.pink);

getContentPane().add(button1); //增加组件 getContentPane().add(button2);

getContentPane().setLayout(new FlowLayout()); //设置布局管理器

button2.addActionListener(new ActionListener(){ //铵钮二的事件处理 public void actionPerformed(ActionEvent e){ clickCount++; //增加一次点击数

button2.setText(\点击了: \次\ //重新设置按钮二的标签 } });

setSize(300, 200); //设置窗口尺寸 setVisible(true); //设置窗口可视

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序 }

public static void main(String[] args) { new RoundButtonDemo(); } }

实例6 密码验证框

import java.awt.*;

import java.awt.event.*; import javax.swing.*;

public class JPasswordFieldDemo extends JFrame { JTextField username; //用户名输入框 JPasswordField password; //密码输入框 JButton logonButton; //登录按钮 JButton cancelButton; //退出按钮

public JPasswordFieldDemo() { //构造函数

super(\演示\ //调用父类构造函数 Container container=getContentPane(); //得到容器

container.setLayout(new GridLayout(3, 2, 2, 2)); //设置布局管理器

username=new JTextField(16); //初始化文本输入框,宽度为16列

password=new JPasswordField(16); //初始化密码输入框,宽度为16列 logonButton=new JButton(\登录\ //初始化登录按钮 logonButton.addActionListener( //登录按钮事件处理 new ActionListener(){

public void actionPerformed(ActionEvent evt){

char[] pw=password.getPassword(); //得到密码

String message=\您的用户名:\您的密码:\String(pw); //消息字符串 JOptionPane.showMessageDialog(JPasswordFieldDemo.this, message); //显示消息

} }); cancelButton=new JButton(\退出\ //初始化退出按钮 cancelButton.addActionListener( //初始化按钮事件处理 new ActionListener(){ public void actionPerformed(ActionEvent evt){ System.exit(0); //退出程序 } }); container.add(new JLabel(\ 用户名:\ //增加组件 container.add(username); container.add(new JLabel(\ 密码:\ container.add(password); container.add(logonButton); container.add(cancelButton); setResizable(false); //不允许用户改变窗口大小 setSize(300,120); //设置窗口尺寸 setVisible(true); //设置窗口可视 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序 }

public static void main(String[] args) { new JPasswordFieldDemo(); } }

实例7 虚线与实线

import java.awt.*; import javax.swing.*;

public class LineDemo extends JFrame{ public LineDemo(){ super(\实线与虚线\调用父类构造函数 setSize(300,200); //设置窗口尺寸 setVisible(true); //设置窗口可视

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序 } public void paint(Graphics g){ //绘制组件方法 Graphics2D g2=(Graphics2D)g; //得到2D图形 Dimension dim = this.getSize(); //得到组件尺寸 g2.setColor(Color.white); //设置绘制颜色为白色 g2.fillRect(0, 0, dim.width, dim.height); //填充整个组件 g2.setColor(Color.black); //设置绘制颜色 g2.drawLine(40,160,280,160); //绘制实线 g2.drawLine(40,160,40,40); g2.drawString(\绘制字符串 g2.drawString(\ g2.drawString(\ float[] dash={5,5}; //短划线图案 BasicStroke bs = new BasicStroke(1,BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER, 10.0f,dash,0.0f); //实例化新画刷 g2.setStroke(bs); //设置新的画刷 g2.drawLine(40,160,100,120); //用新的画刷绘制虚线 g2.drawLine(100,120,160,120); g2.drawLine(160,120,280,40); } public static void main(String[] args){ new LineDemo(); } }

实例8 显示多种字体

import java.awt.*; import javax.swing.*;

//显示多种字体,用JLabel实现

public class FontDemo extends JFrame {

public FontDemo() {

super(\显示多种字体\ //调用父类构造函数

Font[] fonts={new Font(\

new Font(\ new Font(\宋体\ new Font(\黑体\

new Font(\ }; //字体数组

String[] text={\Demo\斜体,24号\宋体字示例\黑体\,粗体,斜体,18号\ //显示的文本

Container container=getContentPane(); //得到容器

Box boxLayout=Box.createVerticalBox(); //创建一个垂直排列的Box

boxLayout.setBorder(BorderFactory.createEmptyBorder(10,20,5,5)); //设置边界 container.add(boxLayout); //增加组件到容器上 for (int i=0;i<5;i++){

JLabel fontLabel=new JLabel(); //得到一个JLabel的实例 fontLabel.setFont(fonts[i]); //设置字体 fontLabel.setText(text[i]); //设置显示文本

boxLayout.add(fontLabel); //增加组件到Box上 }

setSize(380,180); //设置窗口尺寸 setVisible(true); //设置窗口可ub视

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序 }

public static void main(String args[]){ new FontDemo(); } }

实例9 多种风格的窗口

import java.awt.*;

import java.awt.event.*; import javax.swing.*;

//显示多种风格的窗口

public class LookAndFeelDemo extends JFrame {

public LookAndFeelDemo(){

super(\多种风格的窗口\ //调用父类构造函数

Container container=getContentPane(); //得到容器 JMenu menuTheme=new JMenu(\窗口风格\ //初始化菜单

JMenuItem itemNative=new JMenuItem(\系统平台风格\ //初始化菜单项 JMenuItem itemMotif=new JMenuItem(\风格\ JMenuItem itemMetal=new JMenuItem(\跨平台风格\ menuTheme.add(itemNative); //增加菜单项 menuTheme.add(itemMotif); menuTheme.add(itemMetal);

itemNative.addActionListener(new ActionListener(){ //菜单项事件处理 public void actionPerformed(ActionEvent event){ changeLookAndFeel(\ //调用方法,改变窗口风格 } });

itemMotif.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent event){ changeLookAndFeel(\ } });

itemMetal.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent event){ changeLookAndFeel(\ } });

JMenuBar menuBar=new JMenuBar(); //初始化菜单栏 menuBar.add(menuTheme); //增加菜单到菜单栏 setJMenuBar(menuBar); //设置菜单

JPanel panel=new JPanel(); //初始化一个JPanel

panel.setBorder(BorderFactory.createTitledBorder(\组件样式\ //设置边界

panel.add(new JTextField(\文本框:Look and feel测试 \ //增加组件到panel上 panel.add(new JCheckBox(\粗体\ panel.add(new JCheckBox(\斜体\ panel.add(new JCheckBox(\下划线\ panel.add(new JButton(\确定\ panel.add(new JButton(\退出\

container.add(panel); //增加panel到容器上

setSize(220,200); //设置窗口尺寸 setVisible(true); //设置窗口可见

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序 }

//改变窗口样式

public void changeLookAndFeel(String type){ try{ if (type.equals(\ //判断来自于哪个菜单项 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); //设置界面样式 } else if (type.equals(\ UIManager.setLookAndFeel(\ } else if (type.equals(\ UIManager.getCrossPlatformLookAndFeelClassName()); } javax.swing.SwingUtilities.updateComponentTreeUI(this); //更新界面 } catch(Exception ex){ //捕捉错误 ex.printStackTrace(); //输出错误 } }

public static void main(String[] args){ new LookAndFeelDemo(); } }

实例10右键弹出菜单

import java.awt.*;

import java.awt.event.*; import javax.swing.*;

//左键弹出菜单

public class JPopMenuDemo extends JFrame { JRadioButtonMenuItem items[]; //菜单项

Color[] colors={Color.blue,Color.pink,Color.yellow,Color.red,Color.orange}; //颜色数组 JPopupMenu popupMenu; //弹出菜单

public JPopMenuDemo() {

super( \右键弹出菜单\调用父类构造函数

ChangeColorAction action = new ChangeColorAction(); //菜单项事件处理 String[] str = {\菜单项名称 ButtonGroup colorGroup=new ButtonGroup(); //实例化按钮组 popupMenu=new JPopupMenu(); //实例化弹出菜单 items=new JRadioButtonMenuItem[5]; //初始化数组 for (int i=0;i

items[i]=new JRadioButtonMenuItem(str[i]); //实例化菜单项 popupMenu.add(items[i]); //增加菜单项到菜单上 colorGroup.add(items[i]); //增加菜单项到按钮组 items[i].addActionListener(action); //菜单项事件处理 }

addMouseListener(new MouseAdapter(){ //窗口的鼠标事件处理 public void mousePressed( MouseEvent event ) { //点击鼠标 triggerEvent(event); //调用triggerEvent方法处理事件 }

public void mouseReleased( MouseEvent event ) { //释放鼠标 triggerEvent(event); }

private void triggerEvent(MouseEvent event) { //处理事件

if (event.isPopupTrigger()) //如果是弹出菜单事件(根据平台不同可能不同)

popupMenu.show(event.getComponent(),event.getX(),event.getY()); //显示菜单

} }); getContentPane().setBackground(Color.white); //窗口的默认背景色为白色 setSize(230,160); //设置窗口大小 setVisible(true); //设置窗口为可视

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); //关闭窗口时退出程序 }

class ChangeColorAction implements ActionListener { //菜单项事件处理 public void actionPerformed(ActionEvent event) { for (int i=0;i

if (event.getSource()==items[i]) { //判断事件来自于哪个菜单项 getContentPane().setBackground(colors[i]); //设置窗口背景 repaint(); //重绘窗口 return; } } }

public static void main( String args[]) { new JPopMenuDemo(); } }

本文来源:https://www.bwwdw.com/article/ue5g.html

Top