目录
1.Panel/applet默认使用flowlayout.2
Frame/dialog/Scorllpane默认borderlayout.2
2.布局管理器..2
3.常用组件..6
4.事件..8
5.AWT菜单..14
1.顶层容器:jframe/japplet/jwindow..21
2.边框..26
3.Swing组件的键盘驱动..27
4.Action的jtoolbar的使用..28
6.进度条..56
8.Jtree.69
9.Jtable andJtablemodel77
10.使用jtextpane和jformattedtextfiled创建格式文本..88
AWT
1.Panel/applet默认使用flowlayout
Frame/dialog/Scorllpane默认borderlayout
2.布局管理器
Flowlayout:f.setLayout(new FlowLayout(FlowLayout.LEFT,20,5));//设置垂直间距和水平间距
Borderlayout:有东西南北中五个区域,可以设置水平和垂直距离,不是置则会覆盖
f.setLayout(new BorderLayout(30,5));//设置垂直间距和水平间距
f.add(newButton("东"),BorderLayout.EAST);
f.add(newButton("西"),BorderLayout.WEST);
f.add(newButton("南"),BorderLayout.SOUTH);
f.add(newButton("北"),BorderLayout.NORTH);
f.add(newButton("中"),BorderLayout.CENTER);
gridlayout:将容器划分成网格gridlayout(rows,cols,hgap,vgap)
gridbaglayout:与gridbagconstraints连用(不好控制的东西一般不太喜欢)
gbc.gridx/gridy设置所在网格位置的横向和纵向索引
gbc.gridwidth/height设置可以跨越多少个网格的大小
gbc.fill如何占据空白区域,有none,herizontal,vertical,both
gbc.ipadx/ipady设置内部填充的大小
gbc.insets设置外部填充的大小
gbc.anchor组件在显示区域的定位方式,九个方位
gbc.widthx/weighty占据多余的垂直或者水平空间
gbc.gridwidth=GridBagConstraints.REMAINDER;//所在行的最后一个组件
packagecom.zylg.www;
importjava.awt.Button;
importjava.awt.Frame;
importjava.awt.GridBagConstraints;
importjava.awt.GridBagLayout;
importjava.awt.event.WindowEvent;
importjava.awt.event.WindowListener;
publicclass find
{
public static void main(String[] args)
{
Frame f=new Frame();
GridBagLayout gb=newGridBagLayout();
GridBagConstraints gbc=newGridBagConstraints();
f.setLayout(gb);
f.setLocation(200, 200);
f.setSize(400, 400);
f.addWindowListener(newWindowListener()
{
@Override
public void windowClosed(WindowEvente)
{
// TODOAuto-generated method stub
}
@Override
public voidwindowOpened(WindowEvent e)
{
// TODOAuto-generated method stub
}
@Override
public voidwindowClosing(WindowEvent e)
{
System.exit(0);
}
@Override
public voidwindowIconified(WindowEvent e)
{
// TODOAuto-generated method stub
}
@Override
public voidwindowDeiconified(WindowEvent e)
{
// TODOAuto-generated method stub
}
@Override
public voidwindowActivated(WindowEvent e)
{
// TODOAuto-generated method stub
}
@Override
public voidwindowDeactivated(WindowEvent e)
{
// TODOAuto-generated method stub
}
});
f.setTitle("专业路过");
Button[] bt=new Button[10];
for(int i=0;i<10;i++){bt[i]=newButton("按钮"+i);}
gbc.fill=GridBagConstraints.NONE;//
gbc.weightx=1;
gbc.weighty=1;
gb.setConstraints(bt[0],gbc);f.add(bt[0]);
gb.setConstraints(bt[1], gbc);f.add(bt[1]);
gb.setConstraints(bt[2],gbc);f.add(bt[2]);
gbc.gridwidth=GridBagConstraints.REMAINDER;//所在行的最后一个组件
gb.setConstraints(bt[3],gbc);f.add(bt[3]);
gbc.weightx=1;
gbc.weighty=1;
gbc.gridx=0;
gb.setConstraints(bt[4], gbc);f.add(bt[4]);
gbc.gridwidth=0;
gb.setConstraints(bt[5],gbc);f.add(bt[5]);
gbc.gridwidth=GridBagConstraints.REMAINDER;
gb.setConstraints(bt[6],gbc);f.add(bt[6]);
gbc.gridwidth=1;
gbc.gridheight=2;
gbc.weighty=1;
gb.setConstraints(bt[7],gbc);f.add(bt[7]);
gbc.gridheight=1;
gbc.weighty=1;
gbc.gridwidth=GridBagConstraints.REMAINDER;
gb.setConstraints(bt[8],gbc);f.add(bt[8]);
gb.setConstraints(bt[9],gbc);f.add(bt[9]);
f.setVisible(true);
}
}
cardlayout(hgap,vgap)
first(Containertarget)显现容器第一张 last() previous() next() show(target,name)
packagecom.zylg.www;
importjava.awt.BorderLayout;
importjava.awt.Button;
importjava.awt.CardLayout;
importjava.awt.Frame;
importjava.awt.Panel;
importjava.awt.TextArea;
importjava.awt.event.ActionListener;
importjava.awt.event.WindowEvent;
importjava.awt.event.WindowListener;
publicclass find
{
public static void main(String[] args)
{
Frame f=new Frame();
f.setLayout(newBorderLayout(0,0));
CardLayout c=new CardLayout();
Panel p1=new Panel(),p2=newPanel();
p1.setLayout(c);
Button[] bt=new Button[5];
f.setLocation(200, 200);
f.setSize(400, 400);
f.setTitle("专业路过");
for(int i=0;i<5;i++)
{
Panel p=new Panel();
p.add(new TextArea("专业路过"+i,30,90));
p1.add("专业路过"+i,p);
}
ActionListener listener=e->
{
switch(e.getActionCommand())
{
case "上一张":c.previous(p1);break;
case "下一张":c.next(p1);break;
case "第一张":c.first(p1);break;
case "最后一张":c.last(p1);break;
case "第三张":c.show(p1, "专业路过3");break;
}
};
bt[0]=new Button("上一张");bt[0].addActionListener(listener);p2.add(bt[0]);
bt[1]=new Button("下一张");bt[1].addActionListener(listener);p2.add(bt[1]);
bt[2]=new Button("最后一张");bt[2].addActionListener(listener);p2.add(bt[2]);
bt[3]=new Button("第一张");bt[3].addActionListener(listener);p2.add(bt[3]);
bt[4]=new Button("第三张");bt[4].addActionListener(listener);p2.add(bt[4]);
f.add(p1);
f.add(p2, BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
}
}
Null绝对定位
Boxlayout比gridbaglayout简单一点的东西,水平或者垂直的排列,加上间距
f.setLayout(newBoxLayout(f, BoxLayout.Y_AXIS));
Box horizontal=Box.createHorizontalBox();
Box vertical=Box.createVerticalBox();
horizontal.add(Box.createHorizontalGlue());
horizontal.add(new Button("水平按钮1"));
horizontal.add(Box.createHorizontalGlue());
horizontal.add(new Button("水平按钮2"));
horizontal.add(Box.createHorizontalGlue());
horizontal.add(new Button("水平按钮3"));
horizontal.add(Box.createHorizontalGlue());
vertical.add(Box.createVerticalStrut(50));
vertical.add(new Button("垂直按钮1"));
vertical.add(Box.createVerticalStrut(50));
vertical.add(new Button("垂直按钮2"));
f.add(horizontal);
f.add(vertical, BorderLayout.SOUTH);
3.常用组件
基本组件button(按钮)、canvas(画布)、checkbox(复选框组件)、checkboxgtoup(将多个checkbox合成在一起)、choice(下拉式选择框组件)、frame(窗口)、label(标签)、list(列表框组件)、panel(容器)、scrollbar(滚动条组件)、textarea(文本域)、textfile(单行文本)
对话框dialog
Button ok=new Button("确认");
CheckboxGroup cbg=new CheckboxGroup();
Checkbox male=new Checkbox("男",cbg,true);
Checkbox famale=new Checkbox("女",cbg,false);
Checkbox married=new Checkbox("是否已婚?",false);
Choice colorchooser=new Choice();
List colorlist=new List(6,true);
TextArea ta=new TextArea(5,20);
TextField name=new TextField(40);
colorlist.add("红");
colorlist.add("绿");
colorlist.add("蓝");
colorchooser.add("红");
colorchooser.add("绿");
colorchooser.add("蓝");
Panel p1=new Panel(),p2=new Panel();
p1.add(name);p1.add(ok);f.add(p1,BorderLayout.SOUTH);
p2.add(colorchooser);p2.add(male);p2.add(famale);p2.add(married);
Box topleft=Box.createVerticalBox();
topleft.add(ta);topleft.add(p2);
Box top=Box.createHorizontalBox();
top.add(topleft);top.add(colorlist);
f.add(top);
对话框
Dialog d1=new Dialog(f,"模式对话框",true);
Dialog d2=new Dialog(f,"非模式对话框",false);
Button bt1=new Button("打开模式对话框");bt1.addActionListener(e->d1.setVisible(true));
Button bt2=new Button("打开非模式对话框");bt2.addActionListener(e->d2.setVisible(true));
4.事件
Componentevent组件事件
Containerevent容器事件
Focusevent焦点事件
Windowevent窗体事件
Keyevent键盘事件
Mouseevent键盘事件
Paintevent组件绘制事件
Actionevent动作事件
Adjustmentevent调节事件
Itemevent选项事件
Textevent文本框事件
package com.zylg.www;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.Box;
public class find
{
public static void main(String[] args)
{
Frame f=new Frame();
f.setLocation(200, 200);
f.setSize(400, 400);
f.setTitle("专业路过");
Panel p1=new Panel();
TextArea shuru=new TextArea(3,40);
Button ok=new Button("确定");
p1.add(shuru);p1.add(ok);
f.add(p1, BorderLayout.SOUTH);
Box top=Box.createHorizontalBox();
TextAreata1=new TextArea(20,25),ta2=new TextArea(20,25);
top.add(ta1);top.createHorizontalGlue();top.add(ta2);
top.createVerticalGlue();
f.add(top);
//事件的重新定义
ActionListener action=new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
ta2.append("按钮、文本框,菜单项被单击\n");
}
};
AdjustmentListener adjust=new AdjustmentListener()
{
@Override
public voidadjustmentValueChanged(AdjustmentEvent e)
{
ta2.append("滑块位置发生改变\n");
}
};
ContainerListener cont=new ContainerListener()
{
@Override
public void componentRemoved(ContainerEvent e)
{
ta2.append("从容器中移除了组件\n");
}
@Override
public void componentAdded(ContainerEvent e)
{
ta2.append("从容器中添加了组件\n");
}
};
FocusListener focus=new FocusListener()
{
@Override
public void focusLost(FocusEvent e)
{
ta2.append("获得了焦点\n");
}
@Override
public void focusGained(FocusEvent e)
{
ta2.append("失去了焦点\n");
}
};
ComponentListener comp=new ComponentListener()
{
@Override
public void componentShown(ComponentEvent e)
{
ta2.append("组件被显示\n");
}
@Override
public void componentResized(ComponentEvent e)
{
ta2.append("组件大小发生变化\n");
}
@Override
public void componentMoved(ComponentEvent e)
{
ta2.append("组件被移动\n");
}
@Override
public void componentHidden(ComponentEvent e)
{
ta2.append("组件被隐藏\n");
}
};
KeyListener key=new KeyListener()
{
@Override
public void keyTyped(KeyEvent e)
{
// ta2.append("单击某个键\n");
}
@Override
public void keyReleased(KeyEvent e)
{
// ta1.append("释放按键");
}
@Override
public void keyPressed(KeyEvent e)
{
ta1.append(e.getKeyText(e.getKeyCode()));
}
};
MouseListener mous1=new MouseListener()
{
@Override
public void mouseReleased(MouseEvent e)
{
ta2.append("松开了鼠标键\n");
}
@Override
public void mousePressed(MouseEvent e)
{
ta2.append("按下鼠标键\n");
}
@Override
public void mouseExited(MouseEvent e)
{
ta2.append("鼠标键离开\n");
}
@Override
public void mouseEntered(MouseEvent e)
{
ta2.append("鼠标键进入\n");
}
@Override
public void mouseClicked(MouseEvent e)
{
ta2.append("鼠标单击\n");
}
};
MouseMotionListener mous2=new MouseMotionListener()
{
@Override
public void mouseMoved(MouseEvent e)
{
ta2.append("在组件上移动鼠标\n");
}
@Override
public void mouseDragged(MouseEvent e)
{
ta2.append("在组件上移动鼠标,且鼠标被按下\n");
}
};
TextListener tex=new TextListener()
{
@Override
public void textValueChanged(TextEvent e)
{
ta2.append("文本空值发生改变\n");
}
};
ItemListener item=new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent e)
{
ta2.append("选项被选中\n");
}
};
WindowListener win=new WindowListener()
{
@Override
public void windowOpened(WindowEvent e)
{
ta2.append("窗体被打开\n");
}
@Override
public void windowIconified(WindowEvent e)
{
ta2.append("窗体最小化\n");
}
@Override
public void windowDeiconified(WindowEvent e)
{
ta2.append("窗体被恢复\n");
}
@Override
public void windowDeactivated(WindowEvent e)
{
ta2.append("窗体失去激活\n");
}
@Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
@Override
public void windowClosed(WindowEvent e)
{
ta2.append("窗体已经关闭\n");
}
@Override
public void windowActivated(WindowEvent e)
{
ta2.append("窗体被激活\n");
}
};
f.addWindowListener(win);
shuru.addKeyListener(key);
ok.addMouseListener(mous1);
f.setVisible(true);
}
}
事件的适配器 可以继承过来重写listener
5.AWT菜单
Menubar菜单条装menu,menu装menuitem和checkboxmenuitem,menuitem和checkmenuitem装menu和menushortcut
publicstatic void main(String[] args)
{
Frame f=new Frame();
f.setLocation(200, 200);
f.setSize(400, 400);
f.setTitle("专业路过");
f.addWindowListener(new WindowAdapter()
{
public voidwindowClosing(WindowEvent e)
{
System.exit(0);
}
});
TextArea ta=new TextArea(6,40);
MenuBar mb=new MenuBar();
Menu file=new Menu("文件");
MenuItem newitem=newMenuItem("新建");
MenuItem saveitem=newMenuItem("保存");
MenuItem exititem=newMenuItem("退出", new MenuShortcut(KeyEvent.VK_X));
Menu edit=new Menu("编辑");
CheckboxMenuItem autowrap=new CheckboxMenuItem("自动换行");
MenuItem copyitem=newMenuItem("复制");
MenuItem pasteitem=newMenuItem("粘贴");
Menu format=new Menu("格式");
MenuItem commentitem=newMenuItem("注释",new MenuShortcut(KeyEvent.VK_SHIFT,true));
MenuItem cancelitem=newMenuItem("取消注释");
ActionListener listener=e->{
Stringstr=e.getActionCommand();
ta.append("单击"+str+"菜单");
if(str.equals("退出"))
{
System.exit(0);
}
};
commentitem.addActionListener(listener);
exititem.addActionListener(listener);
file.add(newitem);file.add(saveitem);file.add(exititem);//为文件菜单添加菜单项
edit.add(autowrap); edit.addSeparator();edit.add(copyitem);edit.add(pasteitem); //为编辑菜单添加菜单项
format.add(commentitem);format.add(cancelitem);//format添加菜单项
edit.add(newMenuItem("-"));edit.add(format);//将format添加到edit形成二级菜单
mb.add(file);mb.add(edit);
//右键菜单
PopupMenu pop=new PopupMenu();
pop.add(copyitem);
Panel p=new Panel();
p.add(pop);
p.addMouseListener(newMouseAdapter()
{
public voidmouseReleased(MouseEvent e)
{
if(e.isPopupTrigger())
{
pop.show(p,e.getX(), e.getY());
}
}
});
f.add(ta);
f.add(p);
f.setMenuBar(mb);
f.setVisible(true);
}
6.Awt绘图
三个方法paint()、update()、repaint()
staticString name="";
public static void main(String[] args)
{
Frame f=new Frame();
f.setLocation(200, 200);
f.setSize(400, 400);
f.setTitle("专业路过");
f.addWindowListener(newWindowAdapter()
{
public voidwindowClosing(WindowEvent e)
{
System.exit(0);
}
});
class mycanvas extends Canvas
{
@Override
public void paint(Graphicsg)
{
Random rand=newRandom();
if(name.equals("oval"))
{
g.setColor(newColor(220, 100, 80));
g.drawOval(rand.nextInt(120),rand.nextInt(120), 50, 50);
}
if(name.equals("rect"))
{
g.setColor(newColor(220, 100, 80));
g.drawRect(rand.nextInt(200),rand.nextInt(200), 40, 60);
}
}
}
Button bt1=new Button("绘制矩形");
Button bt2=new Button("绘制圆形");
mycanvas draw=new mycanvas();
bt1.addActionListener(e->{name="rect";draw.repaint();});
bt2.addActionListener(e->{name="oval";draw.repaint();});
f.add(draw);
Panel p=new Panel();
p.add(bt1);p.add(bt2);
f.add(p, BorderLayout.SOUTH);
f.setVisible(true);
}
7.位图处理
BufferedImageimage=new BufferedImage(AREA_WIDTH, AREA_HEIUGHT, BufferedImage.TYPE_3BYTE_BGR);
Graphicsg=image.getGraphics();
g.drawLine(preX,preY, e.getX(), e.getY());
用imageio输入输出位图
(1) 格式
String[] readformat=ImageIO.getReaderFormatNames();//可以读的所有的文件格式
for(String str:readformat){System.out.print(str+"\t");}
System.out.println("\n");
String[] writeformat=ImageIO.getWriterFormatNames();//可以写的所有的文件格式
for(String str:writeformat){System.out.print(str+"\t");}
System.out.println("\n");
String[] name1=ImageIO.getReaderFileSuffixes();//可以读的所有的文件后缀
for(String str:name1){System.out.print(str+"\t");}
System.out.println("\n");
String[] name2=ImageIO.getWriterFileSuffixes();//可以写的所有的文件后缀
for(String str:name2){System.out.print(str+"\t");}
(2) readand write
BufferedImage image=newBufferedImage(600,400,BufferedImage.TYPE_INT_BGR);
Graphics g=image.getGraphics();
Image src=ImageIO.read(new File("背景.jpg"));
g.drawImage(src, 0, 0, 600,400,null);
ImageIO.write(image, "jpeg", new File("hello"+".jpg"));
8.剪切板
//require system clipboard
Clipboard clipboard=Toolkit.getDefaultToolkit().getSystemClipboard();
//Clipboard clipboard=new Clipboard("cb");
StringSelection contents=new StringSelection(copyarea.getText());
clipboard.setContents(contents,null);//copy to clipboard
String contents=(String)clipboard.getData(DataFlavor.stringFlavor);
pastearea.setText(contents);//paste
jdk只是为transferable提供了一个实现的接口StringSelection,但是提供了一个imageFlavor常量,用于图片的操作
Image img;
public static List
staticclass imageselection implementsTransferable
{
private Image image;
publicimageselection(Image img)
{
image=img;
}
public DataFlavor[]getTransferDataFlavors()
{
return newDataFlavor[]{DataFlavor.imageFlavor};
}
public booleanisDataFlavorSupported(DataFlavor flavor)
{
returnflavor.equals(DataFlavor.imageFlavor);
}
public ObjectgetTransferData(DataFlavor flavor)throws UnsupportedFlavorException,IOException
{
if(flavor.equals(DataFlavor.imageFlavor)){returnimage;}
else
{try
{
throw newException();
} catch (Exceptione)
{
// TODOAuto-generated catch block
e.printStackTrace();
}}
return flavor;
}
}
class mycanvas extends JPanel
{
public void paint(Graphics g)
{
g.drawImage(img, 0, 0,null);
for(Imagei:imglist)
{
g.drawImage(i, 0, 0,600,400,null);
}
}
}
pastebutton.addActionListener(e->
{
if(clipboard.isDataFlavorAvailable(DataFlavor.imageFlavor))
{
try
{
imglist.add((Image)clipboard.getData(DataFlavor.imageFlavor));
arae.repaint();
}
catch (Exceptione1)
{
pastearea.setText("剪切板内容为空");
}
}
});
copybutton.addActionListener(e->
{
StringSelection contents=new StringSelection(copyarea.getText());
try
{
img=ImageIO.read(new File("背景.jpg"));
} catch (IOExceptione1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
imageselection imageselected=newimageselection(img);
clipboard.setContents(imageselected,null);
});
9,拖放
Awt的类,droptarget创建拖放目标,构造器droptarget(Component c,int ops,droptargetlistener dtl)
ops:DnDConstants.ACTION_COPY/COPY_OR_MOVE/LINK/MOVE/NONE
dtl:dragenter/drahexit/dragover/drop/dropactionchange
public void drop(DropTargetDropEvent dtde)
{
dtde.acceptDrop(DnDConstants.ACTION_COPY);//接受复制操作
//获取拖放的内容
Transferable trans=dtde.getTransferable();
DataFlavor[] flavors=trans.getTransferDataFlavors();
//遍历拖放内容的全部格式
for(inti=0;i<flavors.length;i++)
{
DataFlavor df=flavors[i];
if(df.equals(DataFlavor.javaFileListFlavor))
{
try
{
List filelist=(List)trans.getTransferData(df);
for(Objectf:filelist)
{
//======显示每个文件
showimage((File)f,dtde);
}
} catch (Exceptione)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
dtde.dropComplete(true);
}
}
newDropTarget(jf,DnDConstants.ACTION_COPY,new imagedroptargetlistener());
Swing
1.顶层容器:jframe/japplet/jwindow
中间:jpanel/jscroll/jsplitpane/jtoolbar/jinternalframe/jrootpane/jlayeredoane/jdesktoppane
基本组件:Jbutton/jcombobox/jlist/jmenu/jslider等交互
不可编辑:jlabel/jprogressbar/jtooltip
可编辑:jtable/jtextfiled/jtextarea
对话框组件jcolorchooser/jfilechooser
package com.zylg.www;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
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.SwingUtilities;
import javax.swing.UIManager;
public class find
{
JFrame frame=new JFrame("专业路过");
JButton ok=new JButton("确认");
JRadioButton male=new JRadioButton("男",true);
JRadioButton female=new JRadioButton("女",false);
ButtonGroup bg=new ButtonGroup();
JCheckBox married=new JCheckBox("is married",false);
String[] colors=new String[]{"red","green","blue"};
JComboBox<String> colorchooser=new JComboBox<>(colors);
JList<String> colorList = new JList<>(colors);
JTextArea ta=new JTextArea(8,20);
JTextField name=new JTextField(40);
JMenuBar menubar=new JMenuBar();
JMenu file=new JMenu("file"),edit=new JMenu("edit"), format=new JMenu("format");
JMenuItem newfile=new JMenuItem("new");
JMenuItem savefile=new JMenuItem("save");
JMenuItem exit=new JMenuItem("exit");
JCheckBoxMenuItem autowrap=new JCheckBoxMenuItem("auto wrap");
JMenuItem copyitem=new JMenuItem("copy");
JMenuItem pasteitem=new JMenuItem("paste");
JMenuItem contentitem=new JMenuItem("content");
JMenuItem cancelitem=new JMenuItem("cancel");
JPopupMenu pop=new JPopupMenu();
ButtonGroup flavorgroup=new ButtonGroup();
JRadioButtonMenuItem metalItem=new JRadioButtonMenuItem("Metal风格",true);
JRadioButtonMenuItem nimbusItem =new JRadioButtonMenuItem("Nimbus风格");
JRadioButtonMenuItem windowsItem =new JRadioButtonMenuItem("Windows风格");
JRadioButtonMenuItem classicItem =new JRadioButtonMenuItem("Windows经典风格");
JRadioButtonMenuItem motifItem =new JRadioButtonMenuItem("Motif风格");
public void init()
{
JPanel buttom=new JPanel();
buttom.add(name);buttom.add(ok);
frame.add(buttom,BorderLayout.SOUTH);
JPanel checkpanel=new JPanel();
checkpanel.add(colorchooser);
bg.add(male);bg.add(female);
checkpanel.add(male);checkpanel.add(female);checkpanel.add(married);
Box topleft=Box.createVerticalBox();
JScrollPane tajsp=new JScrollPane(ta);
topleft.add(tajsp);topleft.add(checkpanel);
Box top=Box.createHorizontalBox();
top.add(topleft);top.add(colorList);
frame.add(top);
newfile.addActionListener(e->ta.append("new menu\n"));
newfile.setAccelerator(KeyStroke.getKeyStroke('N',InputEvent.CTRL_MASK));
file.add(newfile);file.add(savefile);file.add(exit);
edit.add(autowrap);edit.addSeparator();edit.add(copyitem);edit.add(pasteitem);
contentitem.setToolTipText("我就是一个注释");
format.add(contentitem);format.add(cancelitem);
edit.add("-");
edit.add(format);
menubar.add(file);menubar.add(edit);
frame.setJMenuBar(menubar);
flavorgroup.add(metalItem);
flavorgroup.add(nimbusItem);
flavorgroup.add(windowsItem);
flavorgroup.add(classicItem);
flavorgroup.add(motifItem);
pop.add(metalItem);
pop.add(nimbusItem);
pop.add(windowsItem);
pop.add(classicItem);
pop.add(motifItem);
ActionListener flavorListener =e -> {
try
{
switch(e.getActionCommand())
{
case"Metal风格":
changeFlavor(1);
break;
case"Nimbus风格":
changeFlavor(2);
break;
case"Windows风格":
changeFlavor(3);
break;
case"Windows经典风格":
changeFlavor(4);
break;
case"Motif风格":
changeFlavor(5);
break;
}
}
catch (Exceptionee)
{
ee.printStackTrace();
}
};
// 为五个风格菜单项添加事件监听器
metalItem.addActionListener(flavorListener);
nimbusItem.addActionListener(flavorListener);
windowsItem.addActionListener(flavorListener);
classicItem.addActionListener(flavorListener);
motifItem.addActionListener(flavorListener);
// 调用该方法即可设置右键菜单,无须使用事件机制
ta.setComponentPopupMenu(pop); //④
// 设置关闭窗口时,退出程序
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void changeFlavor(intflavor)throws Exception
{
switch (flavor)
{
// 设置Metal风格
case 1:
UIManager.setLookAndFeel(
"javax.swing.plaf.metal.MetalLookAndFeel");
break;
// 设置Nimbus风格
case 2:
UIManager.setLookAndFeel(
"javax.swing.plaf.nimbus.NimbusLookAndFeel");
break;
// 设置Windows风格
case 3:
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
break;
// 设置Windows经典风格
case 4:
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
break;
// 设置Motif风格
case 5:
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.motif.MotifLookAndFeel");
break;
}
// 更新f窗口内顶级容器以及内部所有组件的UI
SwingUtilities.updateComponentTreeUI(frame.getContentPane()); //②
// 更新mb菜单条以及内部所有组件的UI
SwingUtilities.updateComponentTreeUI(menubar);
// 更新pop右键菜单以及内部所有组件的UI
SwingUtilities.updateComponentTreeUI(pop);
}
public static void main(String[]args)
{
new find().init();
}
}
2.边框
public class find
{
JFrame f=new JFrame("专业路过");
public void init()
{
f.setLayout(new GridLayout(3, 4));
f.setBounds(200,200,300,300);
Border bb=BorderFactory.createBevelBorder//四条边线的颜色
(BevelBorder.RAISED,Color.RED,Color.green,Color.BLUE,Color.DARK_GRAY);
f.add(getpanelborder(bb,"bevelborder"));
Border lb=BorderFactory.createLineBorder(Color.ORANGE,10);//颜色和宽度
f.add(getpanelborder(lb,"Lineborder"));
Border eb=BorderFactory.createEmptyBorder(5,5, 10, 10);//四周空出来的地方
f.add(getpanelborder(eb,"emptyborder"));
Border ecb=BorderFactory.createEtchedBorder
(EtchedBorder.RAISED,Color.red,Color.green);//两种颜色混合
f.add(getpanelborder(ecb,"etchedborder"));
TitledBorder tb=new TitledBorder//为别的边框增加标题
(lb,"title",TitledBorder.CENTER,TitledBorder.BOTTOM,new Font("", Font.BOLD, 20),Color.red);
f.add(getpanelborder(tb,"titleborder"));
Border mb=BorderFactory.createMatteBorder(10,20, 10, 20, Color.GREEN);//四周设置颜色
f.add(getpanelborder(mb,"matteborder"));
CompoundBorder cb=new CompoundBorder(new LineBorder(Color.red,8),tb);//两种边框进行组合
f.add(getpanelborder(cb,"compoundborder"));
f.setVisible(true);
}
public JPanel getpanelborder(Border b,String name)
{
JPanel p=new JPanel();
p.add(new JLabel(name));
p.setBorder(b);
returnp;
}
public static void main(String[] args)
{
new find().init();
}
}
3.Swing组件的键盘驱动
public class find
{
JFrame f=new JFrame("专业路过");
JTextArea area=new JTextArea(6,30);
JTextField txtfield=new JTextField(15);
JButton bt=new JButton("send");
public void init()
{
f.add(area);
Panel p=new Panel();
p.add(txtfield);p.add(bt);
f.add(p,BorderLayout.SOUTH);
Action msg=newAbstractAction()
{
public void actionPerformed(ActionEvent e)
{
area.append(txtfield.getText()+"\n");
txtfield.setText("");
}
};
bt.addActionListener(msg);
//在txtfield区域将‘z’与“发送”相关联
txtfield.getInputMap().put((KeyStroke)KeyStroke.getAWTKeyStroke('z'), "发送");
//将“发送”和监听器msg相关联
txtfield.getActionMap().put("发送", msg);
f.pack();
f.setLocation(200,200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public static void main(String[] args)
{
new find().init();
}
}
4.Action的jtoolbar的使用
public class find
{
JFrame f=new JFrame("专业路过");
JTextArea txarea=new JTextArea(6,30);
JToolBar jtb=new JToolBar();
JMenuBar jmb=new JMenuBar();
JMenu edit=new JMenu("编辑");
Clipboard clipboard=Toolkit.getDefaultToolkit().getSystemClipboard();
Action pasteation=newAbstractAction("粘贴")
{
public void actionPerformed(ActionEvent e)
{
if(clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor))
{
try
{
String content=(String)clipboard.getData(DataFlavor.stringFlavor);
txarea.replaceRange(content,txarea.getSelectionStart(), txarea.getSelectionEnd());
}
catch (Exceptione1)
{
e1.printStackTrace();
}
}
}
};
Action copyation =newAbstractAction("复制")
{
@Override
public void actionPerformed(ActionEvent e)
{
StringSelection content=new StringSelection(txarea.getSelectedText());
clipboard.setContents(content,null);
if(clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor))
{
pasteation.setEnabled(true);
}
}
};
public void init()
{
//主体的设置
pasteation.setEnabled(false);
f.add(new JScrollPane(txarea));
JButton copybutton=newJButton(copyation);
JButton pastebutton=newJButton(pasteation);
JPanel p=new JPanel();
p.add(copybutton);
p.add(pastebutton);
f.add(p, BorderLayout.SOUTH);
//工具栏的设置=============
jtb.add(pasteation);
jtb.add(copyation);
jtb.setMargin(newInsets(5, 5, 5, 5));
f.add(jtb,BorderLayout.NORTH);
//===菜单栏设置==================
edit.add(copyation);
edit.add(pasteation);
jmb.add(edit);
f.setJMenuBar(jmb);
f.pack();
f.setLocation(200,200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public static void main(String[] args)
{
new find().init();
}
}
颜色选择JColorChooser.showDialog(f, "专业路过的颜色选择", Color.red);
文件dialog
JFileChooser filechooser=new JFileChooser("E:\\");//创建文件选择器
filechooser.setSelectedFile(new File("1.txt"));//默认选择1.txt文件
filechooser.setMultiSelectionEnabled(true);//可以选择多个文件
filechooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);//可以选择文件和路径
filechooser.addChoosableFileFilter(null);//添加文件过滤器,或setFileFilter
filechooser.showSaveDialog(f);
File file=filechooser.getSelectedFile();//得到选择的文件
packagecom.zylg.www;
importjava.awt.Dimension;
importjava.awt.Image;
importjava.io.File;
importjava.util.ArrayList;
importjavax.swing.BorderFactory;
importjavax.swing.Icon;
importjavax.swing.ImageIcon;
importjavax.swing.JFileChooser;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.JMenu;
importjavax.swing.JMenuBar;
importjavax.swing.JMenuItem;
importjavax.swing.JScrollPane;
importjavax.swing.filechooser.FileFilter;
importjavax.swing.filechooser.FileView;
publicclass find
{
int PREVIEW_SIZE=100;
JFrame jf=new JFrame("简单图片查看器");
JMenuBar menubar=new JMenuBar();
JLabel label=new JLabel();
JFileChooser filechooser=newJFileChooser(".");
JLabel accessory=new JLabel();
ExtendFilefilter filter=newExtendFilefilter();
public void init()
{
//set file filter
filter.addExtension("jpg");
filter.addExtension("jpeg");
filter.addExtension("gif");
filter.addExtension("png");
filter.setDescription("图片文件(*.jpg,*.jpeg,*.gif,*.png)");
//set filechooser
filechooser.addChoosableFileFilter(filter);//addfilter
filechooser.setAcceptAllFileFilterUsed(false);//Don`tto show all file type
filechooser.setFileView(newFileIconView(filter));//set file view`s icon
filechooser.setAccessory(accessory);//addcomponent to view pictrue
accessory.setPreferredSize(newDimension(PREVIEW_SIZE, PREVIEW_SIZE));
accessory.setBorder(BorderFactory.createEtchedBorder());
filechooser.addPropertyChangeListener(e->//selectedfile changeevent
{
if(e.getPropertyName()==JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)
{
//Theselected file changes
File f=(File)e.getNewValue();
if(f==null){accessory.setIcon(null);return;}
ImageIconicon=new ImageIcon(f.getPath());
if(icon.getIconWidth()>PREVIEW_SIZE)//changeimage size
{
icon=newImageIcon
(icon.getImage().getScaledInstance(PREVIEW_SIZE,-1, Image.SCALE_DEFAULT));
}
accessory.setIcon(icon);
}
});
//set windown(this is menubar)
JMenu menu=newJMenu("file");
JMenuItem openitem=newJMenuItem("open");
menu.add(openitem);
openitem.addActionListener(e->
{
intresult=filechooser.showDialog(jf, "open image");
if(result==JFileChooser.APPROVE_OPTION)
{
Stringname=filechooser.getSelectedFile().getPath();
ImageIconicon=new ImageIcon(name);
label.setIcon(newImageIcon(icon.getImage().getScaledInstance(480, 420
,Image.SCALE_AREA_AVERAGING)));
}
});
JMenuItem exititem=newJMenuItem("Exit");
menu.add(exititem);
exititem.addActionListener(e->{System.exit(0);});
menubar.add(menu);
jf.setJMenuBar(menubar);
JScrollPane sc=newJScrollPane(label);
jf.add(sc);
jf.setBounds(200, 200, 500, 500);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setResizable(false);
jf.setVisible(true);
}
public static void main(String[] args)
{
new find().init();
}
//自定义过滤器
class ExtendFilefilterextends FileFilter
{
private Stringdescription;
privateArrayList< String> extensions=new ArrayList<>();
@Override
public booleanaccept(File f)//判断是否接受该文件
{
if(f.isDirectory())returntrue;
Stringname=f.getName().toLowerCase();
for(Stringextension:extensions)
{
if(name.endsWith(extension))returntrue;
}
returnfalse;
}
@Override
public StringgetDescription()
{
returndescription;
}
public voidsetDescription(String description)
{
this.description=description;
}
public voidaddExtension(String extension)
{
if(!extension.startsWith("."))
{
extension="."+extension;
extensions.add(extension.toLowerCase());
}
}
}
// 自定义一个FileView类,用于为指定类型的文件或文件夹设置图标
class FileIconViewextends FileView
{
privateFileFilter filter;
publicFileIconView(FileFilter filter)
{
this.filter=filter;
}
@Override
public IcongetIcon(File f)
{
if(!f.isDirectory()&&filter.accept(f))
{
returnnew ImageIcon("pict.png");
}
elseif(f.isDirectory())
{
File[]Flist=File.listRoots();//require all rootfiles diretory
for(Filetmp:Flist)
{//ifthe diretory is rootdiretory
if(tmp.equals(f)){returnnew ImageIcon("dsk.png");}
}
returnnew ImageIcon("folder.png");
}
else//usedefault icon
{
returnnull;
}
}
}
}
Joptionpane可以方便的产生一些简单的对话框
package com.zylg.www;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
public class find
{
JFrame jf=new JFrame("joptionpane");
// 定义一个JPanel类扩展类,该类的对象包含多个纵向排列的
// JRadioButton控件,且Panel扩展类可以指定一个字符串作为TitledBorder
classButtonPanel extendsJPanel
{
private ButtonGroupgroup;
publicButtonPanel(String title, String[] options)
{
setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(),title));
setLayout(newBoxLayout(this, BoxLayout.Y_AXIS));
group = newButtonGroup();
for (int i =0; options!=null && i < options.length; i++)
{
JRadioButton b = newJRadioButton(options[i]);
b.setActionCommand(options[i]);
add(b);
group.add(b);
b.setSelected(i == 0);
}
}
// 定义一个方法,用于返回用户选择的选项
public String getSelection()
{
returngroup.getSelection().getActionCommand();
}
}
// 分别定义6个面板用于定义对话框的几种选项
private ButtonPanelmessagePanel;
private ButtonPanelmessageTypePanel;
private ButtonPanelmsgPanel;
private ButtonPanelconfirmPanel;
private ButtonPaneloptionsPanel;
private ButtonPanelinputPanel;
private StringmessageString = "消息区内容";
private IconmessageIcon = new ImageIcon("ico/heart.png");
private ObjectmessageObject = new Date();
private ComponentmessageComponent = new JButton("组件消息");
private JButtonmsgBn = new JButton("消息对话框");
private JButtonconfrimBn = new JButton("确认对话框");
private JButtoninputBn = new JButton("输入对话框");
private JButtonoptionBn = new JButton("选项对话框");
public void init()
{
//set window of top
JPanel top=new JPanel();
top.setBorder(new TitledBorder(new EtchedBorder(),"对话框的常用选项",TitledBorder.CENTER,TitledBorder.TOP));
top.setLayout(new GridLayout(1, 2));
messageTypePanel=new ButtonPanel("选择消息类型",new String[]{"ERROR_MESSAGE","INFORMATION_MESSAGE"
, "WARNING_MESSAGE","QUESTION_MESSAGE", "PLAIN_MESSAGE" });
messagePanel = new ButtonPanel("选择消息内容的类型",
new String[]{"字符串消息","图标消息","组件消息","普通对象消息" ,"Object[]消息"});
top.add(messageTypePanel);top.add(messagePanel);
//set window of bottom
JPanel bottom=new JPanel();
bottom.setBorder(new TitledBorder(new EtchedBorder()
, "弹出不同的对话框" , TitledBorder.CENTER ,TitledBorder.TOP));
bottom.setLayout(new GridLayout(1, 4));
msgPanel = new ButtonPanel("消息对话框",null);
msgBn.addActionListener(new ShowAction());
msgPanel.add(msgBn);
// 创建用于弹出确认对话框的Panel
confirmPanel = new ButtonPanel("确认对话框",
new String[]{"DEFAULT_OPTION","YES_NO_OPTION"
, "YES_NO_CANCEL_OPTION","OK_CANCEL_OPTION"});
confrimBn.addActionListener(new ShowAction());
confirmPanel.add(confrimBn);
// 创建用于弹出输入对话框的Panel
inputPanel = new ButtonPanel("输入对话框"
, new String[]{"单行文本框","下拉列表选择框"});
inputBn.addActionListener(new ShowAction());
inputPanel.add(inputBn);
// 创建用于弹出选项对话框的Panel
optionsPanel = new ButtonPanel("选项对话框"
, new String[]{"字符串选项","图标选项","对象选项"});
optionBn.addActionListener(new ShowAction());
optionsPanel.add(optionBn);
bottom.add(msgPanel);
bottom.add(confirmPanel);
bottom.add(inputPanel);
bottom.add(optionsPanel);
Box box = new Box(BoxLayout.Y_AXIS);
box.add(top);
box.add(bottom);
jf.add(box);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.pack();
jf.setVisible(true);
}
public static void main(String[] args)
{
new find().init();
}
// 根据用户选择返回选项类型
private int getOptionType()
{
switch(confirmPanel.getSelection())
{
case"DEFAULT_OPTION":
return JOptionPane.DEFAULT_OPTION;
case"YES_NO_OPTION":
return JOptionPane.YES_NO_OPTION;
case"YES_NO_CANCEL_OPTION":
return JOptionPane.YES_NO_CANCEL_OPTION;
default:
return JOptionPane.OK_CANCEL_OPTION;
}
}
// 根据用户选择返回消息
private Object getMessage()
{
switch(messagePanel.getSelection())
{
case"字符串消息":
returnmessageString;
case"图标消息":
returnmessageIcon;
case"组件消息":
returnmessageComponent;
case"普通对象消息":
returnmessageObject;
default:
return new Object[]{messageString , messageIcon
, messageObject ,messageComponent};
}
}
// 根据用户选择返回消息类型(决定图标区的图标)
private int getDialogType()
{
switch(messageTypePanel.getSelection())
{
case"ERROR_MESSAGE":
return JOptionPane.ERROR_MESSAGE;
case"INFORMATION_MESSAGE":
return JOptionPane.INFORMATION_MESSAGE;
case"WARNING_MESSAGE":
return JOptionPane.WARNING_MESSAGE;
case"QUESTION_MESSAGE":
return JOptionPane.QUESTION_MESSAGE;
default:
return JOptionPane.PLAIN_MESSAGE;
}
}
private Object[] getOptions()
{
switch(optionsPanel.getSelection())
{
case"字符串选项":
return new String[]{"a" , "b" , "c" , "d"};
case"图标选项":
return new Icon[]{new ImageIcon("ico/1.gif")
, new ImageIcon("ico/2.gif")
, new ImageIcon("ico/3.gif")
, new ImageIcon("ico/4.gif")};
default:
return new Object[]{new Date() ,new Date() ,new Date()};
}
}
// 为各按钮定义事件监听器
private class ShowAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
switch(event.getActionCommand())
{
case"确认对话框":
JOptionPane.showConfirmDialog(jf, getMessage()
,"确认对话框", getOptionType(), getDialogType());
break;
case"输入对话框":
if (inputPanel.getSelection().equals("单行文本框"))
{
JOptionPane.showInputDialog(jf, getMessage()
, "输入对话框", getDialogType());
}
else
{
JOptionPane.showInputDialog(jf, getMessage()
, "输入对话框", getDialogType() ,null
, new String[]{"轻量级Java EE企业应用实战"
, "疯狂Java讲义"},"疯狂Java讲义");
}
break;
case"消息对话框":
JOptionPane.showMessageDialog(jf,getMessage()
,"消息对话框", getDialogType());
break;
case"选项对话框":
JOptionPane.showOptionDialog(jf , getMessage()
, "选项对话框", getOptionType() , getDialogType()
, null,getOptions(),"a");
break;
}
}
}
}
Jsplitpane可以分割面板
public class find
{
JFrame jf=new JFrame("jSplitpane Test");
book[] books=new book[]{new book("专业路过1",new ImageIcon("背景.jpg"),"没有什么好描述的")
,new book("专业路过2",new ImageIcon("nihao.jpg"),"no anything todescription")};
JList
JLabel bookcavor=new JLabel();
JTextArea bookdesc=new JTextArea();
public void init()
{
booklist.setPreferredSize(new Dimension(150, 300));
bookcavor.setPreferredSize(new Dimension(300, 150));
bookdesc.setPreferredSize(new Dimension(300, 150));
booklist.addListSelectionListener(e->
{
book bk=(book)booklist.getSelectedValue();
bookcavor.setIcon(bk.geticon());
bookdesc.setText(bk.gettext());
});
//splitpane start
JSplitPane left=newJSplitPane(JSplitPane.VERTICAL_SPLIT,bookcavor,newJScrollPane(bookdesc));
left.setOneTouchExpandable(true);//一触即发
left.setContinuousLayout(true);//支持连续布局
left.setDividerSize(10);//设置分隔条的大小
// left.setDividerLocation(0.9);//9:1划分
JSplitPane content=newJSplitPane(JSplitPane.HORIZONTAL_SPLIT,left,booklist);
content.setContinuousLayout(true);
content.setOneTouchExpandable(true);
//windown seting
jf.add(content);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLocation(300, 300);
jf.pack();
jf.setVisible(true);
}
public static void main(String[] args)
{
new find().init();
}
class book
{
private Stringname;
private Stringdescription;
private Iconicon;
public book(Stringname , Icon ico , Stringdesc)
{
this.name =name;
this.icon =ico;
this.description =desc;
}
public Icon geticon()
{
returnicon;
}
public String gettext()
{
returndescription;
}
public String toString()
{
returnname;
}
}
}
Jtabbedpane
/*
*JTabbedPane(tabplacement,tablelayoutpolicy) top/bottom/left/right 换行和滚动
*addtab() inserttab() setcomponentat() removetabat()
*setselectedindex()选择显示的标签
* setdisableat(index,icon)将指定位置禁用图标设置为icon
* setenable(index,boolean)指定位置的标签是否启用
* setforgroundat(index,color)设置前景色
* seticon()
* settitleat()
* settooltiptextat()
* 监听的addchangelistener()
*/
public class find
{
JFrame jf = new JFrame("测试Tab页面");
// 创建一个Tab页面的标签放在左边,采用换行布局策略的JTabbedPane
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.LEFT
, JTabbedPane.WRAP_TAB_LAYOUT);
ImageIcon icon = new ImageIcon("背景.jpg");
String[] layouts = {"换行布局" ,"滚动条布局"};
String[] positions = {"左边" ,"顶部" ,"右边" ,"底部"};
Map
public void init()
{
books.put("疯狂Java讲义" ,"java.png");
books.put("轻量级Java EE企业应用实战" , "ee.png");
books.put("疯狂Ajax讲义" ,"ajax.png");
books.put("疯狂Android讲义" , "android.png");
books.put("经典Java EE企业应用实战" , "classic.png");
String tip = "可看到本书的封面照片";
// 向JTabbedPane中添加5个标签页面,指定了标题、图标和提示
// 但该标签页面的组件为null
for (StringbookName : books.keySet())
{
tabbedPane.addTab(bookName,icon, null ,tip);
}
jf.add(tabbedPane, BorderLayout.CENTER);
// 为JTabbedPane添加事件监听器
tabbedPane.addChangeListener(event -> {
// 如果被选择的组件依然是空
if (tabbedPane.getSelectedComponent() ==null)
{
// 获取所选标签页
intn = tabbedPane.getSelectedIndex();
// 为指定标前页加载内容
loadTab(n);
}
});
// 系统默认选择第一页,加载第一页内容
loadTab(0);
tabbedPane.setPreferredSize(new Dimension(500 , 300));
// 增加控制标签布局、标签位置的单选按钮
JPanel buttonPanel = new JPanel();
ChangeAction action = new ChangeAction();
buttonPanel.add(new ButtonPanel(action
, "选择标签布局策略" ,layouts));
buttonPanel.add (new ButtonPanel(action
, "选择标签位置" ,positions));
jf.add(buttonPanel, BorderLayout.SOUTH);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.pack();
jf.setVisible(true);
}
// 为指定标签页加载内容
private void loadTab(intn)
{
String title = tabbedPane.getTitleAt(n);
// 根据标签页的标题获取对应图书封面
ImageIcon bookImage = new ImageIcon("ico/"
+ books.get(title));
tabbedPane.setComponentAt(n ,new JLabel(bookImage));
// 改变标签页的图标
tabbedPane.setIconAt(n,new ImageIcon("ico/open.gif"));
}
// 定义改变标签页的布局策略,放置位置的监听器
class ChangeAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
JRadioButton source = (JRadioButton)event.getSource();
String selection = source.getActionCommand();
// 设置标签页的标题的布局策略
if (selection.equals(layouts[0]))
{
tabbedPane.setTabLayoutPolicy(
JTabbedPane.WRAP_TAB_LAYOUT);
}
else if (selection.equals(layouts[1]))
{
tabbedPane.setTabLayoutPolicy(
JTabbedPane.SCROLL_TAB_LAYOUT);
}
// 设置标签页上的标题的放置位置
else if (selection.equals(positions[0]))
{
tabbedPane.setTabPlacement(JTabbedPane.LEFT);
}
else if (selection.equals(positions[1]))
{
tabbedPane.setTabPlacement(JTabbedPane.TOP);
}
else if (selection.equals(positions[2]))
{
tabbedPane.setTabPlacement(JTabbedPane.RIGHT);
}
else if (selection.equals(positions[3]))
{
tabbedPane.setTabPlacement(JTabbedPane.BOTTOM);
}
}
}
public static void main(String[] args)
{
new find().init();
}
}
// 定义一个JPanel类扩展类,该类的对象包含多个纵向排列的JRadioButton控件
// 且JPanel扩展类可以指定一个字符串作为TitledBorder
class ButtonPanelextends JPanel
{
private ButtonGroupgroup;
public ButtonPanel(find.ChangeActionaction
, String title, String[]labels)
{
setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(),title));
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
group = new ButtonGroup();
for (inti = 0; labels!=null && i < labels.length;i++)
{
JRadioButton b = new JRadioButton(labels[i]);
b.setActionCommand(labels[i]);
add(b);
// 添加事件监听器
b.addActionListener(action);
group.add(b);
b.setSelected(i == 0);
}
}
}
JlayeredPane有层次深度的容器
public class find
{
JFrame jf = new JFrame("JLayeredPane Test");
JLayeredPane jlp=new JLayeredPane();
public void init()
{
jlp.add(newContentPanel(60, 60, "zylg1","背景.jpg"),JLayeredPane.MODAL_LAYER);
jlp.add(new ContentPanel(30, 30,"zylg2", "背景2.jpg"), 200);
jlp.add(new ContentPanel(0, 0,"zylg3", "背景2.jpg"),400);
jlp.setVisible(true);
jf.add(jlp);
jf.setBounds(300,300,500,530);
jf.setVisible(true);
}
public static void main(String[] args)
{
new find().init();
}
}
class ContentPanelextends JPanel
{
public ContentPanel(intxPos , intyPos
, String title , Stringico)
{
setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),title));
JLabel label = new JLabel(new ImageIcon(ico));
add(label);
setBounds(xPos , yPos , 400,420); // ①
}
}
Jdesktopane和jinternalframe同时存在,且依存于别的容器
// 创建内部窗口
private MyJDesktopPane desktop = newMyJDesktopPane();
final JInternalFrameiframe = new JInternalFrame("新文档",
true, // 可改变大小
true, // 可关闭
true, // 可最大化
true); // 可最小化
iframe.add(new JScrollPane(new JTextArea(8, 40)));
// 将内部窗口添加到虚拟桌面中
desktop.add(iframe);
// 设置内部窗口的原始位置(内部窗口默认大小是0X0,放在0,0位置)
iframe.reshape(nextFrameX,nextFrameY, width,height);
// 使该窗口可见,并尝试选中它
iframe.show();
5拖动和装饰
public class find
{
JFrame jf=new JFrame("swing实现拖放功能");
JTextArea txarea=new JTextArea(8,30);
JTextField txfield=new JTextField(30);
public void init()
{
jf.add(txarea);
jf.add(txfield,BorderLayout.SOUTH);
// txarea.setDragEnabled(true);
txfield.setDragEnabled(true);
jf.pack();
jf.setLocation(200,200);
jf.setVisible(true);
}
public static void main(String[] args)
{
new find().init();
}
}
/*实现装饰只需要两行代码
*LayerUI
*JLayer
*/
public class find
{
JFrame jf=new JFrame("swing实现装饰功能");
JTextArea txarea=new JTextArea(8,30);
JTextField txfield=new JTextField(30);
public void init()
{
LayerUI
JLayer
jf.add(jlayer);
jf.add(txfield,BorderLayout.SOUTH);
jf.pack();
jf.setLocation(200,200);
jf.setVisible(true);
}
public static void main(String[] args)
{
new find().init();
}
}
class mylayerUIextends LayerUI
{
@Override
public void paint(Graphics g, JComponentc)
{
super.paint(g,c);
Graphics2D g2=(Graphics2D)g.create();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,.5f));
g2.fillRect(0, 0, c.getWidth(), c.getHeight());
g2.dispose();
}
}
模糊处理(重写了mylayerUI这个类)
class mylayerUIextends LayerUI
{
private BufferedImagescreenblurlamge;
private BufferedImageOpoperation;
float ninth=0.2f;
@Override
public void paint(Graphics g, JComponentc)
{
ninth-=0.001f;
if(ninth<=0){ninth=0.2f;}
float[]bluekernel={ninth,ninth,ninth,ninth,ninth,ninth,ninth,ninth,ninth};
//进行模糊处理convolveop
operation=new ConvolveOp(new Kernel(3, 3,bluekernel),ConvolveOp.EDGE_NO_OP,null);
int w=c.getWidth();
int h=c.getHeight();
if(w==0||h==0)return;
if(screenblurlamge==null||
screenblurlamge.getWidth()!=w||screenblurlamge.getHeight()!=h)
{
screenblurlamge=new BufferedImage(w,h, BufferedImage.TYPE_INT_RGB);
}
Graphics2D g2=screenblurlamge.createGraphics();
g2.clip(g.getClip());
super.paint(g2,c);
g2.dispose();
Graphics2D tmp=(Graphics2D)g;
tmp.drawImage(screenblurlamge,operation,0,0);
}
}
class mylayerUIextends LayerUI
{
private boolean active;
private int cx,cy;
@Override
public void installUI(JComponent c)
{
super.installUI(c);
JLayer layer=(JLayer)c;
//添加鼠标事件
layer.setLayerEventMask(AWTEvent.MOUSE_EVENT_MASK|AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
@Override
public void uninstallUI(JComponent c)
{
JLayer layer=(JLayer)c;
layer.setLayerEventMask(0);
super.uninstallUI(c);
}
@Override
public void paint(Graphics g, JComponentc)
{
Graphics2D g2=(Graphics2D)g.create();
super.paint(g2,c);
if(active)
{
Point2D center=new Point2D.Float(cx,cy);
floatradius=72f;
float[]dist={0.0f,1.0f};
Color colors[]={Color.YELLOW,Color.BLACK};
//创建渐变的效果
RadialGradientPaint p=new RadialGradientPaint(center,radius,dist,colors);
g2.setPaint(p);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.6f));//透明度
g2.fillRect(0, 0, c.getWidth(), c.getHeight());
}
g2.dispose();
}
@Override
protected void processMouseEvent(MouseEvent e,JLayer layer)
{
if(e.getID()==MouseEvent.MOUSE_ENTERED)active=true;
if(e.getID()==MouseEvent.MOUSE_EXITED)active=false;
layer.repaint();
}
@Override
protected void processMouseMotionEvent(MouseEvent e, JLayerextends JComponent>l)
{
Point p=SwingUtilities.convertPoint(e.getComponent(),e.getPoint(), l);//得到坐标值
cx=p.x;
cy=p.y;
l.repaint();
}
}
创建透明不规则形状的窗口
setShape设置形状 setopacity设置透明度
// set son window
transWin.setLayout(new GridBagLayout());
transWin.setLocation(200,200);
transWin.setSize(200, 200);
transWin.setUndecorated(true);
transWin.setOpacity(0.7f);
transWin.add(new JButton("透明窗口里的简单按钮"));
gradientWin.setUndecorated(true);
gradientWin.setBackground(new Color(0, 0, 0, 0));
gradientWin.setSize(new Dimension(300, 200));
// 使用一个JPanel对象作为渐变透明的背景
JPanel panel = newJPanel()
{
protected voidpaintComponent(Graphics g)
{
if (g instanceofGraphics2D)
{
final intR = 240;
final intG = 240;
final intB = 240;
// 创建一个渐变画笔
Paint p = newGradientPaint(0.0f, 0.0f// x1 y1 color x2 y2
//color
, newColor(R, G, B, 0), 0.0f, getHeight(),new Color(R, G, B, 255), true);
Graphics2D g2d =(Graphics2D) g;
g2d.setPaint(p);
g2d.fillRect(0, 0,getWidth(), getHeight());
}
}
};
// 使用JPanel对象作为JFrame的contentPane
gradientWin.setContentPane(panel);
panel.setLayout(new GridBagLayout());
gradientWin.add(new JButton("渐变透明窗口里的简单按钮"));
// -------设置有背景图片的窗口-------
//bgWin.setBackground(new Color(0,0, 0, 0));
bgWin.setSize(new Dimension(300, 200));
// 使用一个JPanel对象作为背景图片
JPanel bgPanel = newJPanel()
{
protected voidpaintComponent(Graphics g)
{
try
{
Image bg = ImageIO.read(newFile("背景.jpg"));
// 绘制一张图片作为背景
g.drawImage(bg, 0,0, getWidth(), getHeight(),null);
} catch (IOException ex)
{
ex.printStackTrace();
}
}
};
// 使用JPanel对象作为JFrame的contentPane
bgWin.setContentPane(bgPanel);
bgPanel.setLayout(new GridBagLayout());
bgWin.add(new JButton("有背景图片窗口里的简单按钮"));
// -------设置椭圆形窗口-------
shapeWin.setLayout(new GridBagLayout());
shapeWin.setUndecorated(true);
shapeWin.setOpacity(0.7f);
// 通过为shapeWin添加监听器来设置窗口的形状。
// 当shapeWin窗口的大小被改变时,程序动态设置该窗口的形状
shapeWin.addComponentListener(new ComponentAdapter()
{
// 当窗口大小被改变时,椭圆的大小也会相应地改变
public void componentResized(ComponentEvent e)
{
//设置窗口的形状
shapeWin.setShape(newEllipse2D.Double(0, 0, shapeWin.getWidth(), shapeWin.getHeight())); // ①
}
});
shapeWin.setSize(300, 200);
shapeWin.add(new JButton("椭圆形窗口里的简单按钮"));
6.进度条
Jprogressbar
/****
* JProgressBar jprobar=newJProgressBar(JProgressBar.VERTICAL);//to create verticalpaogressbar
*jprobar.setIndeterminate(check1.isSelected());不确定进度
*jprobar.setStringPainted(!check1.isSelected());显示数字
* jprobar.setMinimum(0);设置最小值
* jprobar.setMaximum(100);设置最大值
*jprobar.setBorderPainted(!check2.isSelected());是否显示边框
* jprobar.setValue(i);设置个显示的值
* */
public class find
{
JFrame jf=new JFrame("jprogressbar Test");
JProgressBar jprobar=new JProgressBar(JProgressBar.VERTICAL);//to create vertical paogressbar
JCheckBox check1=new JCheckBox("不确定进度");
JCheckBox check2=new JCheckBox("不绘制边框");
public void init()
{
Box box=new Box(BoxLayout.Y_AXIS);
box.add(check1);box.add(check2);
jf.setLayout(new FlowLayout());
jf.add(box);jf.add(jprobar);
jprobar.setMinimum(0);
jprobar.setMaximum(100);
jprobar.setStringPainted(true);
check1.addActionListener(e->
{
jprobar.setIndeterminate(check1.isSelected());
jprobar.setStringPainted(!check1.isSelected());
});
check2.addActionListener(e->
{
jprobar.setBorderPainted(!check2.isSelected());
});
jf.pack();
jf.setLocation(300,300);
jf.setVisible(true);
int i=0;
while(true)
{
jprobar.setValue(i);
i++;
if(i>=101){i=0;}
try
{
Thread.sleep(100);
}
catch (Exceptione)
{
System.out.println("have erro");
}
}
}
public static void main(String[] args)
{
new find().init();
}
}
对于boundrangemodel,为保存数据的对象,为此他有一个监听器addchangelistener
jprobar.getModel().addChangeListener(e->
{
//if value changed
});
Jslider和bounedrangemodel创建滑动条
/****
*slider.setExtent(30);添加保留区为30的滑动条
*slider.setPaintTrack(false);没有滑轨
*slider.setPaintLabels(true);设置数字标签
*slider.setInverted(true);设置方向反转
*slider.setPaintTicks(true);slider.setMajorTickSpacing(20);slider.setMinorTickSpacing(5);设置刻度
*slider.setSnapToTicks(true);滑块必须停留在刻度处
*slider = new JSlider(30, 200);构造时可以添加范围
*slider.setPaintLabels(true);设置标签内容
Dictionary
labelTable.put(0, newJLabel("A"));
labelTable.put(20, newJLabel("B"));
labelTable.put(40, newJLabel("C"));
labelTable.put(60, newJLabel("D"));
labelTable.put(80, newJLabel("E"));
labelTable.put(100, newJLabel("F"));
slider.setLabelTable(labelTable);
*/
public class find
{
JFrame jf = new JFrame("jslider Test");
Box sliderbox = new Box(BoxLayout.Y_AXIS);
JTextField txval = new JTextField();
ChangeListener listener;
public void init()
{
listener = e ->
{
JSlider source = (JSlider)e.getSource();
txval.setText("The value of the currentscroll bar is " +source.getValue());
};
// =================add jslider===============
JSlider slider = new JSlider();
addslider(slider, "Plain scorllbar");
// -----------添加保留区为30的滑动条-----------
slider = new JSlider();
slider.setExtent(30);
addslider(slider, "保留区为30");
// ---添加带主、次刻度的滑动条,并设置其最大值,最小值---
slider = new JSlider(30, 200);
// 设置绘制刻度
slider.setPaintTicks(true);
// 设置主、次刻度的间距
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
addslider(slider, "有刻度");
// -----------添加滑块必须停在刻度处滑动条-----------
slider = new JSlider();
// 设置滑块必须停在刻度处
slider.setSnapToTicks(true);
// 设置绘制刻度
slider.setPaintTicks(true);
// 设置主、次刻度的间距
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
addslider(slider, "滑块停在刻度处");
// -----------添加没有滑轨的滑动条-----------
slider = new JSlider();
// 设置绘制刻度
slider.setPaintTicks(true);
// 设置主、次刻度的间距
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
// 设置不绘制滑轨
slider.setPaintTrack(false);
addslider(slider, "无滑轨");
// -----------添加方向反转的滑动条-----------
slider = new JSlider();
// 设置绘制刻度
slider.setPaintTicks(true);
// 设置主、次刻度的间距
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
// 设置方向反转
slider.setInverted(true);
addslider(slider, "方向反转");
// --------添加绘制默认刻度标签的滑动条--------
slider = new JSlider();
// 设置绘制刻度
slider.setPaintTicks(true);
// 设置主、次刻度的间距
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
// 设置绘制刻度标签,默认绘制数值刻度标签
slider.setPaintLabels(true);
addslider(slider, "数值刻度标签");
jf.add(sliderbox);
jf.add(txval, BorderLayout.SOUTH);
jf.setSize(300, 300);
// ------添加绘制Label类型的刻度标签的滑动条------
slider = new JSlider();
// 设置绘制刻度
slider.setPaintTicks(true);
// 设置主、次刻度的间距
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
// 设置绘制刻度标签
slider.setPaintLabels(true);
Dictionary
labelTable.put(0, new JLabel("A"));
labelTable.put(20, new JLabel("B"));
labelTable.put(40, new JLabel("C"));
labelTable.put(60, new JLabel("D"));
labelTable.put(80, new JLabel("E"));
labelTable.put(100, new JLabel("F"));
// 指定刻度标签,标签是JLabel
slider.setLabelTable(labelTable);
addslider(slider, "JLable标签");
jf.setLocation(300, 300);
jf.setVisible(true);
}
public void addslider(JSlider slider, Stringdescription)
{
slider.addChangeListener(listener);
Box box = new Box(BoxLayout.X_AXIS);
box.add(new JLabel(description +":"));
box.add(slider);
sliderbox.add(box);
}
public static void main(String[] args)
{
new find().init();
}
}
Jspinner微调控制器
public class find
{
JFrame jf = new JFrame("jspinner Test");
Box box = new Box(BoxLayout.Y_AXIS);
JSpinner spinner = new JSpinner();
public void init()
{
// -----------普通JSpinner-----------
spinner = new JSpinner();
addspinner(spinner, "普通");
// -----------指定最小值、最大值、步长的JSpinner-----------
// 创建一个SpinnerNumberModel对象,开始值,指定最小值、最大值和步长
SpinnerNumberModel numModel =new SpinnerNumberModel(3.4, -1.1, 4.3,0.1);
spinner = new JSpinner(numModel);
addspinner(spinner, "数值范围");
//======字符串作为微调的值===========
String strvalue[]=new String[]{"专业路过1","专业路过2","专业路过3"};
SpinnerListModel strModel =new SpinnerListModel(strvalue);
spinner = new JSpinner(strModel);
addspinner(spinner, "字符串描述");
//=========image作为微调值============
ArrayList
icon.add(new ImageIcon("背景.jpg"));
icon.add(new ImageIcon("背景.jpg"));
SpinnerListModel imagemodel=new SpinnerListModel(icon);
spinner=new JSpinner(imagemodel);
addspinner(spinner, "image描述");
jf.add(box);
jf.setSize(300, 300);
jf.setLocation(300, 300);
jf.setVisible(true);
}
public void addspinner(JSpinner spinner, Stringdesc)
{
Box bx = new Box(BoxLayout.X_AXIS);
bx.add(new JLabel(desc));
bx.add(spinner);
box.add(bx);
}
public static void main(String[] args)
{
new find().init();
}
}
7.自定义listmodel和comboxmodel
public class find
{
JFrame jf=new JFrame("JList Test");
JList
JComboBox
JTextField txvalue=new JTextField();
public void init()
{
//listmodel
numlist.setVisibleRowCount(5);//显示四个列表项
numlist.setSelectionInterval(2, 4);//choose 3 to 5
numlist.setFixedCellWidth(90);//set width
numlist.setFixedCellHeight(30);//set height
numlist.addListSelectionListener(e->{
List
txvalue.setText("");
for(Doublenum:nums)
{
txvalue.setText(txvalue.getText()+num.toString()+" " );
}
});
//comboxmodel
numlistor.setPreferredSize(new Dimension(50, 30));
numlistor.setMaximumRowCount(5);
numlistor.addActionListener(e->{
Object obj=numlistor.getSelectedItem();
txvalue.setText(obj.toString());
});
JPanel top=new JPanel();
top.add(new JScrollPane(numlist));top.add(numlistor);
jf.add(top);jf.add(txvalue,BorderLayout.SOUTH);
jf.pack();
jf.setVisible(true);
}
public static void main(String[] args)
{
new find().init();
}
}
class NumberListModelextends AbstractListModel
{
protected double start;
protected double end;
protected double step;
public NumberListModel(doublestart
, doubleend , doublestep)
{
this.start =start;
this.end =end;
this.step =step;
}
@Override
public int getSize()
{
return (int)((end-start)/step)+1;
}
@Override
public Double getElementAt(intindex)
{
return (double)(index*step+start);
}
}
class NumberComboBoxModelextends NumberListModel
implements ComboBoxModel
{
// 用于保存用户选中项的索引
private int selectId = 0;
public NumberComboBoxModel(doublestart
, doubleend , doublestep)
{
super(start ,end , step);
}
// 设置选中“选择项”
public void setSelectedItem(Object anItem)
{
if (anIteminstanceof Double)
{
Double target = (Double)anItem;
// 根据选中的值来修改选中项的索引
selectId =(int)((target-start)/step);
}
}
// 获取“选择项”的值
public Double getSelectedItem()
{
// 根据选中项的索引来取得选中项
return (selectId*step+start);
}
}
/****
*
*/
public class find
{
JFrame jf=new JFrame("Defaultlistmodel Test");
JList
JButton addbt=new JButton("Add");
JButton removebt=new JButton("Remove");
DefaultListModel
JTextField jtx=new JTextField(15);
public void init()
{
namemodel.addElement("zylg1");
namemodel.addElement("zylg2");
namemodel.addElement("zylg3");
namemodel.addElement("zykg4");
namelist=new JList
namelist.setVisibleRowCount(3);
addbt.addActionListener(e->
{
if(!jtx.getText().trim().equals(""))
{
namemodel.addElement(jtx.getText());
}
});
removebt.addActionListener(e->
{
if(namelist.getSelectedIndex()>=0)
{
namemodel.removeElementAt(namelist.getSelectedIndex());
}
});
JPanel p=new JPanel();
p.add(jtx);
p.add(addbt);
p.add(removebt);
jf.add(new JScrollPane(namelist));
jf.add(p,BorderLayout.SOUTH);
jf.pack();
jf.setLocation(300,300);
jf.setVisible(true);
}
public static void main(String[] args)
{
new find().init();
}
}
Listcellrederer改变列表项的外观
/****
*
*/
public class find
{
private JFramejf = new JFrame("好友列表");
private String[]friends = new String[]
{
"李清照",
"苏格拉底",
"李白",
"弄玉",
"虎头"
};
private JList
public void init()
{
friendsList.setCellRenderer(newImageCellRenderer());
jf.add(new JScrollPane(friendsList));
jf.pack();
jf.setLocation(300,100);
jf.setVisible(true);
}
public static void main(String[] args)
{
new find().init();
}
}
classImageCellRenderer extends JPanel
implements ListCellRenderer
{
private ImageIconicon;
private Stringname;
// 定义绘制单元格时的背景色
private Colorbackground;
// 定义绘制单元格时的前景色
private Colorforeground;
public Component getListCellRendererComponent(JListlist
, String value , intindex
, booleanisSelected , booleancellHasFocus)
{
icon = new ImageIcon(value + ".gif");
name = value;
background = isSelected ? list.getSelectionBackground()
: list.getBackground();
foreground = isSelected ? list.getSelectionForeground()
: list.getForeground();
// 返回该JPanel对象作为列表项绘制器
return this;
}
// 重写paintComponent方法,改变JPanel的外观
publicvoid paintComponent(Graphics g)
{
int imageWidth =icon.getImage().getWidth(null);
int imageHeight =icon.getImage().getHeight(null);
g.setColor(background);
g.fillRect(0, 0, getWidth(),getHeight());
g.setColor(foreground);
// 绘制好友图标
g.drawImage(icon.getImage() ,getWidth() / 2-imageHeight/2, 10 ,null);
g.setFont(newFont("SansSerif" , Font.BOLD , 18));
// 绘制好友用户名
g.drawString(name, getWidth() /2-name.length()*10 , imageHeight + 30 );
}
// 通过该方法来设置该ImageCellRenderer的最佳大小
public Dimension getPreferredSize()
{
return new Dimension(60, 80);
}
}
8.Jtree
packagecom.zylg.www;
importjava.awt.BorderLayout;
importjava.awt.event.MouseAdapter;
importjava.awt.event.MouseEvent;
importjava.awt.event.MouseListener;
import javax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JOptionPane;
importjavax.swing.JPanel;
importjavax.swing.JScrollPane;
importjavax.swing.JTextArea;
importjavax.swing.JTree;
importjavax.swing.tree.DefaultMutableTreeNode;
importjavax.swing.tree.DefaultTreeModel;
importjavax.swing.tree.TreeNode;
importjavax.swing.tree.TreePath;
/****
* 添加
* selectednode.add(newnode);
* model.insertNodeInto(newnode, parent,parent.getIndex(selectednode));
* 添加之后显示
*TreeNode[] nodes=model.getPathToRoot(newnode);
*TreePath path=new TreePath(nodes);
*tree.scrollPathToVisible(path);
*/
publicclass find
{
private JFrame jf = new JFrame("TreeTest");
JTree tree;
DefaultTreeModel model;
TreePath movepath;
DefaultMutableTreeNode gx, gd, nn, bs,gl, st, sz, fs, root;
JTextArea jtx = new JTextArea(8, 20);
JButton addsiblingbt=newJButton("add sibling button"),addchildbt=new JButton("add childbutton"),
deletebt=newJButton("delete button");
public void init()
{
root = new DefaultMutableTreeNode("Root");
gx = newDefaultMutableTreeNode("广西");
gd = newDefaultMutableTreeNode("广东");
nn = newDefaultMutableTreeNode("南宁");
bs = newDefaultMutableTreeNode("百色");
gl = newDefaultMutableTreeNode("桂林");
st = newDefaultMutableTreeNode("汕头");
sz = newDefaultMutableTreeNode("深圳");
fs = newDefaultMutableTreeNode("佛山");
gx.add(nn);
gx.add(gl);
gx.add(bs);
gd.add(fs);
gd.add(st);
gd.add(sz);
root.add(gx);
root.add(gd);
tree = new JTree(root);
tree.setRootVisible(false);// rootinvisible
tree.setEditable(true);// can toedit
tree.putClientProperty("JTree.lineStyle","None");// invisible lines
//between nodes and
//nodes
jf.add(new JScrollPane(tree));
tree.addTreeSelectionListener(e->
{
String str = new String();
str = "广西 sibling count is " +gx.getSiblingCount();// get sibling
//counts
str = str + "\n next sibling is " +gx.getNextSibling();// get next
//sibling
//name
str += "\n 百色的父节点 " +bs.getParent();// get parent of baise
str += "\n 根节点:" + bs.getRoot();//get root of baise
str += "\n 百色是否叶子节点:" +bs.isLeaf();// 是否为叶子结点
str += "\n 百色是否为广西的子节点:" +gx.isNodeChild(bs);// 是否为广西的子节点
jtx.setText(str);
});
model = (DefaultTreeModel)tree.getModel();// model is obtained
MouseListener mouse = newMouseAdapter()
{
@Override
public voidmousePressed(MouseEvent e)
{
TreePath tp = tree.getPathForLocation(e.getX(),e.getY());
// gets thecoordinates of the seleced position
if (tp != null)
{
movepath =tp;
}
}
@Override
public voidmouseReleased(MouseEvent e)
{
TreePath tp =tree.getPathForLocation(e.getX(), e.getY());
if (tp != null&& movepath != null)
{
// 阻止向子节点拖动
if(movepath.isDescendant(tp) && movepath != tp)
{
JOptionPane.showMessageDialog(jf,"The node already exists", "illegal operation",
JOptionPane.ERROR_MESSAGE);
return;
} // popuperror message
// 既不是向子节点移动,而且鼠标按下、松开的不是同一个节点
else if(movepath != tp)
{
// add方法先将该节点从原父节下删除,再添加到新父节点下
((DefaultMutableTreeNode)tp.getLastPathComponent())
.add((DefaultMutableTreeNode)movepath.getLastPathComponent());
movepath=null;
tree.updateUI();
}
}
}
};
tree.addMouseListener(mouse);
addsiblingbt.addActionListener(e->
{
DefaultMutableTreeNode selectednode=(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
if(selectednode==null)return;
DefaultMutableTreeNodeparent=(DefaultMutableTreeNode) selectednode.getParent();
if(parent==null)return ;
DefaultMutableTreeNodenewnode=new DefaultMutableTreeNode("new node");
model.insertNodeInto(newnode, parent,parent.getIndex(selectednode));
TreeNode[]nodes=model.getPathToRoot(newnode);
TreePathpath=new TreePath(nodes);
tree.scrollPathToVisible(path);
});
addchildbt.addActionListener(e->
{
DefaultMutableTreeNodeselectednode=(DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
if(selectednode==null)return;
DefaultMutableTreeNodenewnode=new DefaultMutableTreeNode("new node");
selectednode.add(newnode);
TreeNode[]nodes=model.getPathToRoot(newnode);
TreePathpath=new TreePath(nodes);
tree.scrollPathToVisible(path);
});
deletebt.addActionListener(e->
{
DefaultMutableTreeNodeselectednode=(DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
if(selectednode!=null&&selectednode.getParent()!=null)
{
model.removeNodeFromParent(selectednode);
}
});
DefaultTreeCellRenderer cellrender=new DefaultTreeCellRenderer();
cellrender.setBackgroundNonSelectionColor(new Color(220, 220, 220));
cellrender.setBackgroundSelectionColor(new Color(140, 140, 140));
cellrender.setBorderSelectionColor(Color.BLACK);
ImageIcon icon=new ImageIcon("背景.jpg");
icon=newImageIcon(icon.getImage().getScaledInstance(20,20, -1));
cellrender.setClosedIcon(icon);
cellrender.setFont(new Font("", Font.BOLD, 14));
tree.setCellRenderer(cellrender);
JPanel panel=new JPanel();
panel.add(addchildbt);panel.add(addsiblingbt);panel.add(deletebt);
jf.add(panel,BorderLayout.NORTH);
jf.add(jtx, BorderLayout.SOUTH);
jf.pack();
jf.setLocation(300, 100);
jf.setVisible(true);
}
public static void main(String[] args)
{
new find().init();
}
}
public class find
{
private JFramejf = new JFrame("Tree Test");
JTree tree;
DefaultMutableTreeNode myfriends,liqingzaho,sugeladi,libai,nongyu,hutou;
public void init()
{
myfriends=new DefaultMutableTreeNode("我的好友");
liqingzaho=new DefaultMutableTreeNode("李清照");
sugeladi=new DefaultMutableTreeNode("苏格拉底");
libai=new DefaultMutableTreeNode("李白");
nongyu=new DefaultMutableTreeNode("弄玉");
hutou=new DefaultMutableTreeNode("虎头");
myfriends.add(liqingzaho);
myfriends.add(sugeladi);
myfriends.add(libai);
myfriends.add(nongyu);
myfriends.add(hutou);
tree = new JTree(myfriends);
// tree.setRootVisible(false);
tree.setShowsRootHandles(true);
tree.setCellRenderer(new ImageCellRenderer());
jf.add(new JScrollPane(tree));
jf.pack();
jf.setLocation(300, 100);
jf.setVisible(true);
}
public static void main(String[] args)
{
new find().init();
}
}
class ImageCellRendererextends JPanel implements TreeCellRenderer
{
private ImageIconicon;
private Stringname;
private Colorbackground;
private Colorforeground;
public ComponentgetTreeCellRendererComponent(JTreetree
, Object value , boolean sel ,boolean expanded
, booleanleaf , introw , booleanhasFocus)
{
icon = new ImageIcon("" +value + ".gif");
name = value.toString();
background = hasFocus ? new Color(140 , 200 ,235)
: new Color(255 , 255 , 255);
foreground = hasFocus ? new Color(255 , 255 ,3)
: new Color(0 , 0 , 0);
return this;
}
// 重写paintComponent方法,改变JPanel的外观
public void paintComponent(Graphics g)
{
int imageWidth = icon.getImage().getWidth(null);
int imageHeight = icon.getImage().getHeight(null);
g.setColor(background);
g.fillRect(0 , 0 , getWidth() ,getHeight());
g.setColor(foreground);
// 绘制好友图标
g.drawImage(icon.getImage() , getWidth() / 2
- imageWidth / 2 , 10 ,null);
g.setFont(new Font("SansSerif" , Font.BOLD , 18));
// 绘制好友用户名
g.drawString(name, getWidth() / 2
- name.length() * 10 ,imageHeight + 30 );
}
// 通过该方法来设置该ImageCellRenderer的最佳大小
public Dimension getPreferredSize()
{
return new Dimension(80, 80);
}
}
9.Jtable and Jtablemodel
package www.zylg.com;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
/****
*table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);//自动调整宽度
*
*table.getSelectionModel().setSelectionMode(selectModes[index]); ;//选择方式
* int[] selectModes = new int[]
* {ListSelectionModel.MULTIPLE_INTERVAL_SELECTION,ListSelectionModel.SINGLE_INTERVAL_SELECTION,
*ListSelectionModel.SINGLE_SELECTION };
*
* table.setRowSelectionAllowed(selecedunit[0].isSelected());
*
* TableColumn namecolumn=table.getColumn(columntitle[0]);//getfirst column
*namecolumn.setPreferredWidth(100);
*
*/
public class find
{
private JFramejf = new JFrame("adjust the table width");
private JTabletable;
JMenuBar menubar = new JMenuBar();
JMenu adjustmode = new JMenu("Adjust mode");
JMenu selectunit = new JMenu("select unit");
JMenu selectmode = new JMenu("select mode");
JMenu manager=new JMenu("manager");
// 定义5个单选框按钮,用以控制表格的宽度调整方式
JRadioButtonMenuItem[] adjustModesItem =new JRadioButtonMenuItem[5];
int[] adjustModes = new int[]
{ JTable.AUTO_RESIZE_OFF, JTable.AUTO_RESIZE_NEXT_COLUMN, JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS,
JTable.AUTO_RESIZE_LAST_COLUMN, JTable.AUTO_RESIZE_ALL_COLUMNS };
ButtonGroup adjustBg = new ButtonGroup();
// 定义3个单选框按钮,用以控制表格的选择方式
JRadioButtonMenuItem[] selectModesItem =new JRadioButtonMenuItem[3];
int[] selectModes = new int[]
{ ListSelectionModel.MULTIPLE_INTERVAL_SELECTION, ListSelectionModel.SINGLE_INTERVAL_SELECTION,
ListSelectionModel.SINGLE_SELECTION };
ButtonGroup selectBg = new ButtonGroup();
// 定义3个selectedunit========================
JCheckBoxMenuItem[] selecedunit =new JCheckBoxMenuItem[3];
//===============定义操作的按钮===================
JMenuItem hidebt=new JMenuItem("Hide Data");
JMenuItem showbt=new JMenuItem("Show Data");
JMenuItem addrow=new JMenuItem("AddRow");
JMenuItem delrow=new JMenuItem("Delete Row");
JMenuItem insertcolumn=new JMenuItem("插入选中的列");
ArrayList< TableColumn> hideenlist=new ArrayList<>();
private Objectdata[][] =
{ new Object[]
{ "李清照", 29,"女" },new Object[]
{ "苏格拉底", 56,"男" },new Object[]
{ "李白", 35,"男" },new Object[]
{ "弄玉", 18,"女" },new Object[]
{ "虎头", 2,"男" } };
Object[] columntitle =
{ "姓名","年龄","性别" };
public void init()
{
DefaultTableModel tablemodel=newDefaultTableModel();
tablemodel.setDataVector(data,columntitle);
table=newJTable(tablemodel);
// -----------为窗口安装设置表格调整方式的菜单-----------
adjustModesItem[0] = new JRadioButtonMenuItem("只调整表格");
adjustModesItem[1] = new JRadioButtonMenuItem("只调整下一列");
adjustModesItem[2] = new JRadioButtonMenuItem("平均调整余下列");
adjustModesItem[3] = new JRadioButtonMenuItem("只调整最后一列");
adjustModesItem[4] = new JRadioButtonMenuItem("平均调整所有列");
menubar.add(adjustmode);
for (inti = 0; i < adjustModesItem.length; i++)
{
// 默认选中第三个菜单项,即对应表格默认的宽度调整方式
if (i == 2)
{
adjustModesItem[i].setSelected(true);
}
adjustBg.add(adjustModesItem[i]);
adjustmode.add(adjustModesItem[i]);
final int index = i;
// 为设置调整方式的菜单项添加监听器
adjustModesItem[i].addActionListener(evt ->
{
// 如果当前菜单项处于选中状态,表格使用对应的调整方式
if (adjustModesItem[index].isSelected())
{
table.setAutoResizeMode(adjustModes[index]);// ①
}
});
}
// -----------为窗口安装设置表格选择方式的菜单-----------
selectModesItem[0] = new JRadioButtonMenuItem("无限制");
selectModesItem[1] = new JRadioButtonMenuItem("单独的连续区");
selectModesItem[2] = new JRadioButtonMenuItem("单选");
menubar.add(selectmode);
for (inti = 0; i < selectModesItem.length; i++)
{
// 默认选中第一个菜单项,即对应表格默认的选择方式
if (i == 0)
{
selectModesItem[i].setSelected(true);
}
selectBg.add(selectModesItem[i]);
selectmode.add(selectModesItem[i]);
final int index = i;
// 为设置选择方式的菜单项添加监听器
selectModesItem[i].addActionListener(evt ->
{
// 如果当前菜单项处于选中状态,表格使用对应的选择方式s
if (selectModesItem[index].isSelected())
{
table.getSelectionModel().setSelectionMode(selectModes[index]);// ②
}
});
}
// -----------为窗口安装设置表格选择单元的菜单---------
selecedunit[0]=new JCheckBoxMenuItem("选择行");
selecedunit[1]=new JCheckBoxMenuItem("选择列");
selecedunit[2]=new JCheckBoxMenuItem("选择单元格");
menubar.add(selectunit);
for(inti=0;i<selecedunit.length;i++)
{
selectunit.add(selecedunit[i]);
}
selecedunit[0].addActionListener(e->
{
table.clearSelection();
table.setRowSelectionAllowed(selecedunit[0].isSelected());
selecedunit[1].setSelected(false);
selecedunit[2].setSelected(false);
});
selecedunit[1].addActionListener(e->
{
table.clearSelection();
table.setColumnSelectionAllowed(selecedunit[1].isSelected());
selecedunit[0].setSelected(false);
selecedunit[2].setSelected(false);
//
});
selecedunit[2].addActionListener(e->
{
table.clearSelection();
table.setCellSelectionEnabled(selecedunit[2].isSelected());
selecedunit[1].setSelected(false);
selecedunit[0].setSelected(false);
});
//============set width ==========
table.setRowHeight(30);
table.getTableHeader().setPreferredSize(new Dimension(20, 30));
TableColumn namecolumn=table.getColumn(columntitle[0]);//get first column
namecolumn.setPreferredWidth(100);
TableColumn agecolumn=table.getColumn(columntitle[1]);
agecolumn.setMinWidth(100);
TableColumn sexcolumn=table.getColumn(columntitle[2]);
sexcolumn.setMaxWidth(30);
//===============add,remove,move数据的操作hide,show=============
hidebt.addActionListener(e->{
int[]selected=table.getSelectedColumns();
TableColumnModel columnmodel=table.getColumnModel();
for(inti=selected.length-1;i>=0;i--)
{
TableColumn column=columnmodel.getColumn(i);
table.removeColumn(column);
hideenlist.add(column);
}
});
showbt.addActionListener(e->{
for(TableColumntc:hideenlist)
{
table.addColumn(tc);
}
hideenlist.clear();
});
insertcolumn.addActionListener(e->{
int[]selected=table.getSelectedColumns();
TableColumnModel columnmodel=table.getColumnModel();
for(inti=selected.length-1;i>=0;i--)
{
TableColumn column =columnmodel.getColumn(selected[i]);
table.addColumn(column);
}
});
addrow.addActionListener(e->{
String[] row=new String[table.getColumnCount()];
for(inti=0;i<row.length;i++)
{
row[i]="new"+table.getRowCount();
}
tablemodel.addRow(row);
});
delrow.addActionListener(e->{
int []selected=table.getSelectedRows();
for(inti=selected.length-1;i>=0;i--)
{
tablemodel.removeRow(selected[i]);
}
});
sortclass sortmodel=newsortclass(table.getModel());
table.setModel(sortmodel);
// 为每列的列头增加鼠标监听器
table.getTableHeader().addMouseListener(newMouseAdapter()
{
public voidmouseClicked(MouseEvent event) // ①
{
// 如果单击次数小于2,即不是双击,直接返回
if(event.getClickCount() < 2)
{
return;
}
// 找出鼠标双击事件所在的列索引
inttableColumn = table.columnAtPoint(event.getPoint());
// 将JTable中的列索引转换成对应TableModel中的列索引
intmodelColumn = table.convertColumnIndexToModel(tableColumn);
// 根据指定列进行排序
sortmodel.sort(modelColumn);
}
});
manager.add(hidebt);
manager.add(showbt);
manager.add(addrow);
manager.add(insertcolumn);
manager.add(delrow);
menubar.add(manager);
jf.setJMenuBar(menubar);
jf.add(new JScrollPane(table));
jf.pack();
jf.setLocation(300, 100);
jf.setVisible(true);
}
public static void main(String[] args)
{
new find().init();
}
}
classsortclass extends AbstractTableModel
{
private TableModel model;
private int sortcolumn;
private Row[] rows;
publicsortclass(TableModel m)
{
model=m;
rows=newRow[model.getRowCount()];
for (int i = 0;i < rows.length; i++)
{
rows[i] = newRow(i);
}
}
public void sort(intc)
{
sortcolumn=c;
java.util.Arrays.sort(rows);
fireTableDataChanged();
}
// 下面三个方法需要访问model中的数据,所以涉及本model中数据
// 和被包装model数据中的索引转换,程序使用rows数组完成这种转换。
public ObjectgetValueAt(int r,int c)
{
returnmodel.getValueAt(rows[r].index, c);
}
public booleanisCellEditable(int r,int c)
{
returnmodel.isCellEditable(rows[r].index, c);
}
public voidsetValueAt(Object aValue,int r, int c)
{
model.setValueAt(aValue,rows[r].index, c);
}
// 下面方法的实现把该model的方法委托为原封装的model来实现
public intgetRowCount()
{
returnmodel.getRowCount();
}
public intgetColumnCount()
{
returnmodel.getColumnCount();
}
public StringgetColumnName(int c)
{
returnmodel.getColumnName(c);
}
public ClassgetColumnClass(int c)
{
returnmodel.getColumnClass(c);
}
class Row implementsComparable
{
public intindex;
public Row(intindex)
{
this.index=index;;
}
@Override
public intcompareTo(Row o)
{
Objecta=model.getValueAt(index, sortcolumn);
Object b=model.getValueAt(o.index,sortcolumn);
if (a instanceofComparable)
{
return ((Comparable)a).compareTo(b);
}
else
{
returna.toString().compareTo(b.toString());
}
}
}
}
此外addcolumnmodellistener()监听column的改变
public class find
{
JFrame jf=new JFrame("表格内容重绘");
JTable table;
extendmodel model;
private Objectdata[][] ={
new Object[]{"李清照","29", "女" ,new ImageIcon("李清照.gif")},
new Object[]{"苏格拉底","56", "男" ,new ImageIcon("苏格拉底.gif")},
new Object[]{"李白","35", "男",new ImageIcon("李白.gif") },
new Object[]{"弄玉","18", "女" ,new ImageIcon("弄玉.gif")},
new Object[]{"虎头","2", "男" ,new ImageIcon("虎头.gif")} };
Object[] columntitle ={ "姓名","年龄","性别","头像" };
public void init()
{
model=new extendmodel();
model.setDataVector(data,columntitle);
table=new JTable(model);
//==============文本编辑,对头像==================
table.setRowSelectionAllowed(false);
TableColumn editimage =table.getColumnModel().getColumn(3);
JComboBox
String[] name=new String[]{"李清照","苏荷拉底","李白","弄玉","虎头"};
for (Stringstr:name)
{
editCombo.addItem(new ImageIcon(str +".gif"));
}
editimage.setCellEditor(new DefaultCellEditor(editCombo));
//=============进行重绘====================
TableColumn sex=table.getColumnModel().getColumn(2);
sex.setCellRenderer(new tablecellrender());
//=============表格数据设置(字体,居中)==========
DefaultTableCellRenderer r=new DefaultTableCellRenderer();
r.setHorizontalAlignment(JLabel.CENTER);
table.setDefaultRenderer(Object.class,r);
table.setFont(new Font("", Font.BOLD, 14));
table.setRowHeight(50);
jf.add(new JScrollPane(table));
jf.pack();
jf.setVisible(true);
}
public static void main(String[] srgs)
{
new find().init();
}
class extendmodel extends DefaultTableModel//显示其他类型的数据,头像
{
@Override
public Class getColumnClass(intcolumnIndex)
{
return getValueAt(0,columnIndex).getClass();
}
}
class tablecellrender extends JPanelimplements TableCellRenderer//渲染器去改变表格内容,性别
{
private Stringvalue;
@Override
public ComponentgetTableCellRendererComponent(JTabletable, Object value,boolean isSelected, boolean hasFocus,
introw, intcolumn)
{
this.value=(String)value;
return this;
}
@Override
public void paint(Graphics g)
{
if(value.equals("男")){drawImage(g , new ImageIcon("male.gif").getImage());}
if(value.equals("女")){drawImage(g , new ImageIcon("female.gif").getImage());}
}
private void drawImage(Graphics g , Imageimage)
{
g.drawImage(image, (getWidth() - 30 ) / 2
, (getHeight() - 30) /2 , null);
}
}
}
10.使用jtextpane和jformattedtextfiled创建格式文本
Jtextcompinnet={jtetarea,jtextfield={jpasswordfield,jformattedtextfield},jeditorpane={jtextpane}};
public class find
{
JFrame mainWin = new JFrame("监听Document对象");
JTextArea target = new JTextArea(4, 35);
JTextArea msg = new JTextArea(5, 35);
JLabel label = new JLabel("文本域的修改信息");
Document doc = target.getDocument();
// 保存撤销操作的List对象
LinkedList
// 最多允许撤销多少次
final int UNDO_COUNT = 20;
public void init()
{
msg.setEditable(false);
//==========文本监听(发生改变、插入、删除)=============
doc.addDocumentListener(newDocumentListener()
{
public voidchangedUpdate(DocumentEvent e){}
public voidinsertUpdate(DocumentEvent e)
{
int len =e.getLength();
msg.setText("havetext insert");
}
public voidremoveUpdate(DocumentEvent e)
{
msg.setText("havetext remove");
}
});
//============监听撤销事件==================
doc.addUndoableEditListener(e-> {
UndoableEdit edit =e.getEdit();
if (edit.canUndo()&& undoList.size() < UNDO_COUNT)
{
undoList.add(edit);
}
else if(edit.canUndo() && undoList.size() >= UNDO_COUNT)
{
undoList.pop();
undoList.add(edit);
}
});
//==============与发生撤销操作的键盘值相关联================
target.addKeyListener(newKeyAdapter()
{
public voidkeyTyped(KeyEvent e) // ②
{
if(e.getKeyChar() == 26)
{
if(undoList.size() > 0)
{
// 移出最后一个可撤销操作,并取消该操作
undoList.removeLast().undo();
}
}
}
});
Box box = new Box(BoxLayout.Y_AXIS);
box.add(new JScrollPane(target));
JPanel panel = new JPanel();
panel.add(label);
box.add(panel);
box.add(new JScrollPane(msg));
mainWin.add(box);
mainWin.pack();
mainWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWin.setVisible(true);
}
public static void main(String[] args) throws Exception
{
new find().init();
}
}
publicclass find
{
//界面所用到的变量
private JFrame mainWin = new JFrame("测试格式化文本框");
private JPanel mainPanel = new JPanel();
private JPanel elsePanel=new JPanel();
JFormattedTextField[] fields = newJFormattedTextField[6];
private JButton okButton = newJButton("确定");
String[] behaviorLabels = new String[]
{
"最近的满足要求的值",
"满足要求或者重新格式化",
"总是显示",
"格式化"
};
//文本控制的值
int[] behaviors = new int[]
{
JFormattedTextField.COMMIT,//如果输入满足要求则输出
JFormattedTextField.COMMIT_OR_REVERT,//不满足则格式化文本
JFormattedTextField.PERSIST,//总是输出
JFormattedTextField.REVERT//不满足要求则格式化文本
};
ButtonGroup bg = new ButtonGroup();
public void init() throws Exception
{
//===========编写界面(由两个jpanel组成,1,存放6个文本框,2,行为和确定)=============
mainPanel.setLayout(new GridLayout(0,3));
fields[0] = newJFormattedTextField(new InternationalFormatter(NumberFormat.getInstance())
{
//重写了函数,这样添加进去过滤器,然后输入时过滤的内容输不进去
protected DocumentFiltergetDocumentFilter()
{
return new myfilter();
}
});
fields[0].setValue(100);
fields[0].setInputVerifier(newmyverify());
addRow("整数格式文本框 :", fields[0]);
fields[1] = new JFormattedTextField(NumberFormat.getCurrencyInstance());
fields[1].setValue(100.0);
addRow("货币格式文本框:", fields[1]);
fields[2] = newJFormattedTextField(DateFormat.getDateInstance());
fields[2].setValue(new Date());
addRow("默认的日期格式器:", fields[2]);
DateFormatformat=DateFormat.getDateInstance(DateFormat.SHORT);
format.setLenient(false);
fields[3] = newJFormattedTextField(format);
fields[3].setValue(new Date());
addRow("SHORT类型的日期格式器(语法严格):", fields[3]);
myformatformatter=new myformat();
formatter.setOverwriteMode(false);
fields[4] = newJFormattedTextField(formatter);
fields[4].setValue(newbyte[]{(byte)125,(byte)217,37,1});
addRow("IP地址:", fields[4]);
MaskFormatter formatter2 = newMaskFormatter("020-########");
formatter2.setPlaceholderCharacter('□');
fields[5] = newJFormattedTextField(formatter);
fields[5].setValue("020-28309378");
mainWin.add(mainPanel,BorderLayout.CENTER);
for (int i = 0; i
{
final int index = i;
final JRadioButton radio = newJRadioButton(behaviorLabels[i]);
if (i == 1){radio.setSelected(true);}
elsePanel.add(radio);
bg.add(radio);
radio.addActionListener(e -> {
if (radio.isSelected())
{
for (int j = 0 ; j
{
fields[j].setFocusLostBehavior(behaviors[index]);
}
}
});
}
elsePanel.add(okButton);
elsePanel.setBorder(new TitledBorder(newEtchedBorder(),
"请选择失去焦点后的行为",TitledBorder.CENTER,TitledBorder.ABOVE_TOP));
mainWin.add(elsePanel,BorderLayout.SOUTH);
//========主窗体的设置=================
mainWin.pack();
mainWin.setLocation(200, 200);
mainWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWin.setVisible(true);
}
// 定义添加一行格式化文本框的方法
private void addRow(String labelText, finalJFormattedTextField field)
{
mainPanel.add(new JLabel(labelText));
mainPanel.add(field);
final JLabel valueLabel = new JLabel();
mainPanel.add(valueLabel);
okButton.addActionListener(event -> {
Object value = field.getValue();
valueLabel.setText(value.toString());
});
}
public static void main(String[] args)throws Exception
{
new find().init();
}
}
//输入校验器(返回修改的值是否成功)
class myverify extends InputVerifier
{
public boolean verify(JComponent component)
{
JFormattedTextField field =(JFormattedTextField)component;
return field.isEditValid();
}
}
//过滤器
class myfilter extends DocumentFilter
{
@Override
public void insertString(FilterBypass fb,int offset, String text, AttributeSet attr) throws BadLocationException
{
if(text!=null)
{
StringBuilder builder = newStringBuilder(text);
filter(builder);
text=builder.toString();
}
super.insertString(fb, offset, text,attr);
}
@Override
public void replace(FilterBypass fb, intoffset, int length, String text, AttributeSet attrs)
throws BadLocationException
{
if(text!=null)
{
StringBuilder builder = newStringBuilder(text);
filter(builder);
text=builder.toString();
}
super.replace(fb, offset, length, text,attrs);
}
public void filter(StringBuilder builder)//对数据进行操作,这里除去数字以外的东西
{
for (int i = builder.length() - 1; i>= 0; i--)
{
int cp = builder.codePointAt(i);
if (cp > '9' || cp < '0')
{
builder.deleteCharAt(i);
}
}
}
}
class myformat extends DefaultFormatter
{
//重写返回的值的函数,返回string
public String valueToString(Object value)
throws ParseException
{
if (!(value instanceof byte[]))
{
throw new ParseException("该IP地址的值只能是字节数组", 0);
}
byte[] a = (byte[])value;
if (a.length != 4)
{
throw new ParseException("IP地址必须是四个整数", 0);
}
StringBuilder builder = newStringBuilder();
for (int i = 0; i < 4; i++)
{
int b = a[i];
if (b < 0) b += 256;
builder.append(String.valueOf(b));
if (i < 3) builder.append('.');
}
return builder.toString();
}
public void setOverwriteMode(boolean b)
{
// TODO Auto-generated method stub
}
//重写返回的值的函数,返回string
public Object stringToValue(String text)throws ParseException
{
String[] nums =text.split("\\.");
if (nums.length != 4)
{
throw new ParseException("IP地址必须是四个整数", 0);
}
byte[] a = new byte[4];
for (int i = 0; i < 4; i++)
{
int b = 0;
try
{
b = Integer.parseInt(nums[i]);
}
catch (NumberFormatException e)
{
throw new ParseException("IP地址必须是整数", 0);
}
if (b < 0 || b >= 256)
{
throw new ParseException("IP地址值只能在0~255之间", 0);
}
a[i] = (byte) b;
}
return a;
}
}
Jtextpane
public class find
{
JFrame mainWin=new JFrame("JTextpane");
JTextPane txt=new JTextPane();
StyledDocument doc=txt.getStyledDocument();
SimpleAttributeSet style1=new SimpleAttributeSet();
SimpleAttributeSet style2=new SimpleAttributeSet();
SimpleAttributeSet style3=new SimpleAttributeSet();
public void init()
{
//=============样式的设置===============
StyleConstants.setFontSize(style1, 24);
StyleConstants.setForeground(style1, Color.RED);
StyleConstants.setFontSize(style2, 30);
StyleConstants.setForeground(style2, Color.green);
StyleConstants.setFontSize(style3, 10);
StyleConstants.setForeground(style3, Color.yellow);
//============设置内容==================
txt.setEditable(false);
txt.setText("zylg1\nzylg2\nzylg3\n");
doc.setCharacterAttributes(0, 6,style1, true);
doc.setCharacterAttributes(6, 6,style2, true);
doc.setCharacterAttributes(12, 6,style3, true);
//=========设置主窗口===================
mainWin.add(new JScrollPane(txt));
mainWin.setBounds(200, 200, Toolkit.getDefaultToolkit().getScreenSize().width-400,
Toolkit.getDefaultToolkit().getScreenSize().height-400);
mainWin.setVisible(true);
}
public static void main(String[] args)
{
new find().init();
}
}
实现数据的更改:
table.getModel().addTableModelListener(new TableModelListener()
{
@Override
public void tableChanged(TableModelEvent e)
{
if(e.getFirstRow()>=0)
{
String newvalue =table.getValueAt(e.getFirstRow(),e.getColumn()).toString();
try
{
PreparedStatementstm=(PreparedStatement)
con.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=stm.executeQuery();
rs.absolute(e.getFirstRow()+1);
rs.updateString(e.getColumn()+1, newvalue);
rs.updateRow();
} catch (SQLExceptione1)
{
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(mainWin,"you have eror");
}
}
}
});