目錄java
1.Panel/applet默認使用flowlayout.2node
Frame/dialog/Scorllpane默認borderlayout.2android
2.佈局管理器..2ajax
3.經常使用組件..6sql
4.事件..8canvas
5.AWT菜單..14windows
1.頂層容器:jframe/japplet/jwindow..21數組
2.邊框..26app
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<Image> imglist=new ArrayList<>();
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<book> booklist=new JList<>(books);
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<String , String> books =new LinkedHashMap<>();
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<JCompnent> layerUI=new xxxLayerUI();
*JLayer<JComponent> layer=newJLayer<JComponnet>(panel,layerUI);
*/
public class find
{
JFrame jf=new JFrame("swing實現裝飾功能");
JTextArea txarea=new JTextArea(8,30);
JTextField txfield=new JTextField(30);
public void init()
{
LayerUI<JComponent> layerUI=new mylayerUI();
JLayer<JComponent> jlayer=new JLayer<JComponent>(txarea,layerUI);
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<JComponent>
{
@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<JComponent>
{
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<JComponent>
{
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, JLayer<? extends 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<Integer,Component> labelTable = newHashtable<>();
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<Integer,Component> labelTable = new Hashtable<>();
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<ImageIcon> icon=new 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<Double>numlist=new JList<Double>(new NumberListModel(1.0, 21.0, 1.0));
JComboBox<Double> numlistor=new JComboBox<>(new NumberComboBoxModel(0.1, 1.2,0.1));
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<Double> nums=numlist.getSelectedValuesList();
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<Double>
{
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<Double>
{
// 用於保存用戶選中項的索引
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<String> namelist=new JList<String>();
JButton addbt=new JButton("Add");
JButton removebt=new JButton("Remove");
DefaultListModel<String>namemodel=new DefaultListModel<>();
JTextField jtx=new JTextField(15);
public void init()
{
namemodel.addElement("zylg1");
namemodel.addElement("zylg2");
namemodel.addElement("zylg3");
namemodel.addElement("zykg4");
namelist=new JList<String>(namemodel);
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<String> friendsList =newJList<>(friends);
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<String>
{
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);
}
}
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);
}
}
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<Row>
{
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<ImageIcon> editCombo =new 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<UndoableEdit> undoList =new 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 <behaviorLabels.length ; 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.length ; 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");
}
}
}
});