1. 建立scrollbar
-> JScrollPane scroll=new JScrollPane(textarea);
-> scroll.setViewportView(textarea);
2. 建立弹出窗
->JOptionPane.showMessageDialog(null, "msg");
->JOptionPane.showMessageDialog(this, "msg","",JOptionPane.WARNING_MESSAGE);
->JOptionPane.showConfirmDialog(null, "msg", "title",JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE) 返回int可以用于判断是否关闭对话 框,eg:
if (JOptionPane.showConfirmDialog(null, "msg", "title",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
// .... code when press YES button in confirm dialog
}
3. 设置字体颜色
-> textarea.setForeground(Color.Blue); //textarea无法在文本域内设置不同字体颜色
->在文本域内设置不同字体颜色使用JTextPane
eg: JTextPane textpane=new JTextPane();
insertStr(str,Color.black); //为要插入文本域中不同的字符设置不同的样式,如颜色等
void insertString(String str,Color color){
SimpleAttributeSet set=new SimpleAttributeSet(); //设置字体样式参数set, javax.swing.text.*
StyleConstants.setForeground(set,color);//配置set, javax.swing.text.*
StyleConstants.setBold(set,true);//配置set
StyleConstants.setFontSize(set,12);//配置set
Document doc=textpane.getDocument(); //or textpane.getStyledDocument();
try{ doc.insertString(doc.length(), str, set) } catch(BadLocationException e) {...} //通过document.insertString(...)在文本域中插入字符和字符的文字样式set
4. 获取焦点
-> button.requestFocus();
-> button.requestFocusInWindow();
5. java.awt.event下的监听器
->button.addActionListener(new ActionListener(){....});
->textfield.addFocusListener(new FocusListener(){...});
->textfield.addKeyListener(new KeyListener(){...});
->textfield.addFocusListener(new FocusListener(){...});
->frame.addWindowListener(new WindowListener(){...});
5. javax.swing.event下的监听器
->listmodel.addListDataListener(new ListDataListener(){...});
8. 文本域设置选中状态
->testarea.setSelectionStart(start_index);
->testarea.setSelectionEnd(end_index);
9. Swing中的UI是单线程。 Swing系统中有一个java.awt.Container(可能是一个JFrame或JDialog实例),负责启动一个EventDispatchThread线程,单线程,负责处理UI事件。Swing的控件向EventtQueue提交一个event,EventDispatchThread负责调度各个event的执行。如按下一个JButton,JButton向EventQueue 申请执行一个postEvent,提交一个ActionEvent。 EventDispatchThread根据调度算法执行到该event时,会调用JButton上的processActionEvent,JButton再调用actionPerformed().即这个过程没有执行任何new Thread().start()代码,JButton的ActionListener.actionPerformed()代码都是在EventDispatchThread内部执行的。所以如果在ActioniListener,MouseListener中编写耗时的代码,整个swing UI都会响应迟钝,更有甚者,如果在Listener中执行线程wait(),那么整个EventDispatchThread都会被阻塞,整个系统界面会处于无响应状态,解决办法就是加上new Thread().start(),使EventDispatchThread执行到当前方法后可以快速返回,执行用户界面的其他响应。所以,SwingUtilities和EventQueue的invokeLater,invokeAndWait方法在swing UI中仍然是单线程的()。只是会把invokeLater中的代码放到最后去执行。eg:
button. addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("before eventqueue");
System.out.println(Thread.currentThread().getId()+Thread.currentThread().getName());
EventQueue.invokeLater(new Runnable(){
@Override
public void run() {
System.out.println("in eventqueue");
System.out.println(Thread.currentThread().getId()+Thread.currentThread().getName());}
});
System.out.println("out of eventqueue");
执行了 before eventqueue, out of eventqueue后才会执行in eventqueue. 在actionPerformed中的代码包括在invokeLater中的new Runnable的线程都是13AWT-EventQueue-0. SwingUtilities的invoke函数同理。如果再加上一个组件,如JButton,它的ActionListener.actionPerformed中的代码也会在线程13AWT-EventQueue-0中执行,即所有Listener都是在一个线程EVentQueueDispatch中按续执行.
所以,一般来说代码应该分为3层,第一层是UI层,包括UI控件上的Listener逻辑,这应该是在EventDispatchThread中执行,必须简短高校,快速return;这一层无法做完的放到new Thread().start()中执行,即第二层,控制层;控制层再去调用业务代码,即第三层,业务层。所有由UI控件触发的逻辑都应该这么分。
PS: Swing不推荐在EventDispatchThread外修改UI,如果需要在业务层repaint某个控件或者updateUI,这时可以用SwingUtilities,这才是使用SwingUtilities的场景。 (from OPEN 经验库)
10. 设置系统托盘
//加入窗口缩小的event
frame.addWindowListener(new WindowAdapter(){
public void windowIconfied(WindowEvent e){
frame.setVisible(false); //缩小时将屏幕隐藏
}} );
If (SystemTray.isSupported){ //java.awt.*,判断平台是否支持系统托盘
//设置托盘图标以及对应event
URL url=tryClass.class.getResource("trayicon.jpg"); //java.net.*, 从类tryClass的classloader中获取图片,即bin文件夹
ImageIcon icon=new ImageIcon(url);//java.awt.*;
Image image=icon.getImage(); //java.awt.*;
TrayIcon trayicon=new TrayIcon(image); //java.awt.*;
trayicon.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(e.getClickCount==2){
frame.setVisible(true); //鼠标点击两次即显示frame
frame.setState(Frame.NORMAL); //java.awt.*, 使frame show on top
// or frame.setState(JFrame.NORMAL);
} });
//为托盘图标加入右键菜单
PopupMenu popup=new PopupMenu(); //java.awt.*;
MenuItem exit new MenuItem("quit");
popup.add(quit);
exit.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
System.exit(0);
} });
trayicon.setPopupMenu(popup); //将右键菜单加入托盘图标中
//将托盘图标加入系统托盘中
SystemTray systemtray=SystemTray.getSystemTray(); //java.awt.*; Gets theSystemTray
instance that represents the desktop's tray area
try{ systemtray.add(trayicon) catch(AWTException e){e.printStackTrace();}}
11. 在.windowListener, .mouseListener, keyListener等监听器中实现接口WindowListener, MouseListener,KeyListener时,要实现的方法比较多。如果只需要实现其中一种而已,可以改用已经实现这些接口的WindowAdapter, MouseAdapter等类代替。如WindowAdapter已经实现WindowListener,所以如果只需要实现一种窗口event,比如缩小,可以直接
frame.addWindowListener(new WindowAdapter(){
public void windowIconfied(WindowEvent e){
frame.setVisible(false); //缩小时将屏幕隐藏
}} );
这样可以避免在代码中写很多不用并且也不会去实现的方法。
12. 设置splitpane
-> JSplitPane pane=new JSplitPane();
pane.setOrientation(JSplitPane.HORIZONTAL_SPLIT); //可水平或竖直 JSplitPane.VERTICAL_SPLIT
pane.setDividerSize(1); //分割线size
pane.setDividerLocation(100);
pane.addRightComponent(panel1);
pane.addLeftComponent(panel2);
13. 设置字体 :
Font font=new Font("Arial", Font.BOLD,12); //字体,粗体,字体大小
Font font=new Font("华文中宋", Font.PLAIN, 16)
PS:文本域等用Font类设置字题样式后,如Arial,如果在文本域显示汉字(不支持Arial样式),会乱码
14.
>>>UI生效: frame.validate();
>>>UI关闭: frame.dispose();
>>>UI隐藏: frame.setVisible(false);
15. 使setPreferedSize生效: frame.pack();
16. 使面板,文本域显示图像背景,需要重写该面板或文本域的javax.swing.JComponent.paint()方法或者javax.swing.JComponent.paintComponent()方法
>>> public void paint(Graphics g){
if(image!=null) //Image image
g.clearRect(0,0,getWidth(),getHeight()); //先清除面板或文本域的图像
g.drawImage(image,0,0,getWidth(),getHeigth(),this); }} //绘制图像
>>> public void BackgroundImage(File file){
BufferedImage bufferedimage=ImageIO.read(file);
Rectangle rectangle=new Rectangle(0,0,getWidth(),getHeight()); //设置涂制范围
paint=new TexturePaint(image,rectangle); // 该paint必须为成员变量以便在paintComponenet方法中使用
setOpaque(false);} //设为非透明
protected void paintComponenet(Graphics g){
Graphics2D g2=(Grahpics2D) g;
g2.set(paint);
g.fillRect(0,0,getWidth(),getHeight());
super.paintComponent(g);}
>>>paintComponent方法优先级不如paint,同时重写两个方法,只有paint方法会生效
17. 设置component边界样式: :EtchedBorder
>>> label.setBorder(new EtchedBorder(EtchedBorder.LOWERED)); //嵌入效果,EtchedBorder.RAISED是突出效果
18. 设置弹出窗口选择文件
>>>JFileChooser choose=new JFileChooser();
choose.setFileSelectionMode(JFileChooser.FILES_ONLY);
choose.setMultiSelectionEnabled(false);
choose.setFileFilter(new FileNameExtensioinFilter("jpg","gif")); //设置过滤器
int result=choose.showOpenDialog(this);
if(result==JFileChooser.APPROVE_OPTION){
File file=choose.getSelectedFile();
file.getAbsolutePath();
//...}
>>>使用过滤器选择文件夹下的所有符合条件的文件
choose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result=choose.showOpenDialog(this);
if(result==JFileChooser.APPROVE_OPTION){
File[] listFiles=choose.getSelectedFile.listFiles(new FileFilter(){
@Override
public boolean accept(File pathname){
if(pathname.getName().endsWith("txt")
return true;
else
return false; }}});
19. 设置菜单
>>> JMenuBar bar=new JMenuBar();
JMenu menu=JMenu("menu");
JPopupMenu popup=menu.getPopUpMenu();
JMenuItem item=JMenuItem("item1");
popup.add(item);
bar.add(menu);
contentpane.add(bar,BorderLayout.BEFORE_FIRST_LINE);
22. 设置当前窗口锁定无法操作其他窗口使用dialog.setModal(true);方法,即模态窗口
>>> JDialog d = new JDialog();
d.setSize(100, 100);
d.setModal(true);
//... 窗口代码
d.setVisible(true);
PS: setVisible(true)方法必须放在所有窗口代码后,否则由于setModal()的影响,界面不能生成。frame无此方法