java 窗体、控件收集

java 的 控件收集

1.图片查看器 ImageViewer
2.复选框 MulitCombobox
3.MulitPopup
4.Swing 控件集合
5.JOptionPane 提示框大全
6.JToolBar java工具条

图片查看器 ImageViewer
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileView;

public class ImageViewer  
{  
    final int PREVIEW_SIZE = 100;  
    JFrame jf = new JFrame("简单图片查看器");  
    JMenuBar menuBar = new JMenuBar();  
    //该label用于显示图片  
    JLabel label = new JLabel();  
    //以当前路径创建文件选择器  
    JFileChooser chooser = new JFileChooser(".");  
    JLabel accessory = new JLabel();  
    ExtensionFileFilter filter = new ExtensionFileFilter();  
    public void init()  
    {  
        //-------------------下面开始初始化JFileChooser的相关属性-----------------  
        // 创建一个FileFilter  
        filter.addExtension("jpg");  
        filter.addExtension("jpeg");  
        filter.addExtension("gif");  
        filter.addExtension("png");  
        filter.setDescription("图片文件(*.jpg,*.jpeg,*.gif,*.png)");  
        chooser.addChoosableFileFilter(filter);  
        //禁止“文件类型”下拉列表中显示“所有文件”选项。  
        chooser.setAcceptAllFileFilterUsed(false);   
        //为文件选择器指定自定义的FileView对象  
        chooser.setFileView(new FileIconView(filter));  
        //为文件选择器指定一个预览图片的附件组件  
        chooser.setAccessory(accessory);  
        //设置预览图片组件的大小和边框  
        accessory.setPreferredSize(new Dimension(PREVIEW_SIZE, PREVIEW_SIZE));  
        accessory.setBorder(BorderFactory.createEtchedBorder());  
        //用于检测被选择文件的改变事件  
        chooser.addPropertyChangeListener(new PropertyChangeListener()  
        {  
            public void propertyChange(PropertyChangeEvent event)   
            {  
                //JFileChooser的被选文件已经发生了改变  
                if (event.getPropertyName() == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)  
                {  
                    //获取用户选择的新文件   
                    File f = (File) event.getNewValue();  
                    if (f == null)  
                    {   
                        accessory.setIcon(null);   
                        return;   
                    }  
                    //将所文件读入ImageIcon对象中  
                    ImageIcon icon = new ImageIcon(f.getPath());  
                    //如果图像太大,则缩小它  
                    if(icon.getIconWidth() > PREVIEW_SIZE)  
                    {     
                        icon = new ImageIcon(icon.getImage()  
                            .getScaledInstance(PREVIEW_SIZE, -1, Image.SCALE_DEFAULT));  
                    }  
                    //改变accessory Label的图标  
                    accessory.setIcon(icon);  
                }  
            }  
        });  
 
        //----------下面代码开始为该窗口安装菜单------------  
        JMenu menu = new JMenu("文件");  
        menuBar.add(menu);  
        JMenuItem openItem = new JMenuItem("打开");  
        menu.add(openItem);  
        //单击openItem菜单项显示“打开文件”的对话框  
        openItem.addActionListener(new ActionListener()  
        {  
            public void actionPerformed(ActionEvent event)  
            {  
                //设置文件对话框的当前路径  
                //chooser.setCurrentDirectory(new File("."));  
                //显示文件对话框  
                int result = chooser.showDialog(jf , "打开图片文件");  
                //如果用户选择了APPROVE(赞同)按钮,即打开,保存及其等效按钮  
                if(result == JFileChooser.APPROVE_OPTION)  
                {  
                    String name = chooser.getSelectedFile().getPath();  
                    //显示指定图片  
                    label.setIcon(new ImageIcon(name));  
                }  
            }  
        });  
        JMenuItem exitItem = new JMenuItem("退出");  
        menu.add(exitItem);  
        exitItem.addActionListener(new ActionListener()  
        {  
            public void actionPerformed(ActionEvent event)  
            {  
                System.exit(0);  
            }  
        });  
        jf.setJMenuBar(menuBar);  
        //添加用于显示图片的JLabel组件。  
        jf.add(new JScrollPane(label));  
        jf.setSize(500, 400);  
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        jf.setVisible(true);  
    }  
 
    public static void main(String[] args)  
    {  
        new ImageViewer().init();  
    }  
}  
 
//创建FileFilter的子类,用以实现文件过滤功能  
class ExtensionFileFilter extends FileFilter  
{  
 
    private String description = "";  
    private ArrayList<String> extensions = new ArrayList<String>();  
    //自定义方法,用于添加文件扩展名  
    public void addExtension(String extension)  
    {  
        if (!extension.startsWith("."))  
        {  
            extension = "." + extension;  
            extensions.add(extension.toLowerCase());  
        }  
    }  
    //用于设置该文件过滤器的描述文本  
    public void setDescription(String aDescription)  
    {  
        description = aDescription;  
    }  
    //继承FileFilter类必须实现的抽象方法,返回该文件过滤器的描述文本  
    public String getDescription()  
    {  
        return description;   
    }  
    //继承FileFilter类必须实现的抽象方法,判断该文件过滤器是否接受该文件  
    public boolean accept(File f)  
    {  
        //如果该文件是路径,接受该文件  
        if (f.isDirectory()) return true;  
        //将文件名转为小写(全部转为小写后比较,用于忽略文件名大小写)  
        String name = f.getName().toLowerCase();  
        //遍历所有可接受的扩展名,如果扩展名相同,该文件就可接受。  
        for (String extension : extensions)  
        {  
            if (name.endsWith(extension))   
            {  
                return true;  
            }  
        }  
        return false;  
    }  
}  
//自定义一个FileView类,用于为指定类型的指定图标  
class FileIconView extends FileView  
{  
    private FileFilter filter;  
    public FileIconView(FileFilter filter)  
    {  
        this.filter = filter;  
    }  
    //如果文件不是目录,并且不是  
    public Icon getIcon(File f)  
    {  
        if (!f.isDirectory() && filter.accept(f))  
        {  
            return new ImageIcon("ico/pict.png");  
        }  
        else if (f.isDirectory())  
        {  
            //获取所有根路径  
            File[] fList = File.listRoots();  
            for (File tmp : fList)  
            {  
                //如果该路径是根路径  
                if (tmp.equals(f))  
                {  
                    return  new ImageIcon("ico/dsk.png");  
                }  
            }  
            return new ImageIcon("ico/folder.png");  
        }  
        //使用默认图标  
        else 
        {  
            return null;  
        }  
    }  
} 


3. 复选框 MulitCombobox
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicArrowButton;

/**
 * hi , this is my first ui component. my ui component "hello world"!!
 * 
 * @author bugu
 * 
 */
public class MulitCombobox extends JComponent {

	private Object[] values;

	private Object[] defaultValues;
	
	private List<ActionListener> listeners = new ArrayList<ActionListener>();
	
	private MulitPopup popup;
	
	private JTextField editor;
	
	protected JButton   arrowButton;
	
	private String valueSperator;
	
	private static final String DEFAULT_VALUE_SPERATOR = " "; 

	public MulitCombobox(Object[] value, Object[] defaultValue){
		this(value,defaultValue,DEFAULT_VALUE_SPERATOR);
	}
	
	public MulitCombobox(Object[] value, Object[] defaultValue , String valueSperator) {
		values = value;
		defaultValues = defaultValue;
		this.valueSperator = valueSperator;
		initComponent();
	}

	private void initComponent() {
		//暂时使用该布局,后续自己写个布局
		this.setLayout(new FlowLayout());
		popup =new  MulitPopup(values,defaultValues);
		popup.addActionListener(new PopupAction());
		editor = new JTextField();
		editor.setBackground(Color.WHITE);
		editor.setEditable(false);
		editor.setBorder(null);
		editor.addMouseListener(new EditorHandler());
		arrowButton = createArrowButton();
		arrowButton.addMouseListener(new EditorHandler());
		add(editor);
		add(arrowButton);
		setText() ;
		
		
	}

	public Object[] getSelectedValues() {
		return popup.getSelectedValues();
	}
	
	public void addActionListener(ActionListener listener) {
		if (!listeners.contains(listener))
			listeners.add(listener);
	}

	public void removeActionListener(ActionListener listener) {
		if (listeners.contains(listener))
			listeners.remove(listener);
	}
	
	protected void fireActionPerformed(ActionEvent e) {
		for (ActionListener l : listeners) {
			l.actionPerformed(e);
		}
	}
	
	private class PopupAction implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			
			if(e.getActionCommand().equals(MulitPopup.CANCEL_EVENT)){
				
			}else if(e.getActionCommand().equals(MulitPopup.COMMIT_EVENT)){
				defaultValues = popup.getSelectedValues();
				setText();
				//把事件继续传递出去
				fireActionPerformed(e);
			}
			
			togglePopup();
			
			
		}

	}
	
	private void togglePopup(){
		if(popup.isVisible()){
			popup.setVisible(false);
		}else{
			popup.setDefaultValue(defaultValues);
			popup.show(this, 0, getHeight());
		}
	}
	
	private void setText() {
		StringBuilder builder = new StringBuilder();
		for(Object dv : defaultValues){
			builder.append(dv);
			builder.append(valueSperator);
		}
		
		editor.setText(builder.substring(0, builder.length() > 0 ? builder.length() -1  : 0).toString());		
	}
	
	private class EditorHandler implements MouseListener{

		@Override
		public void mouseClicked(MouseEvent e) {
			togglePopup();
		}

		@Override
		public void mousePressed(MouseEvent e) {
			
		}

		@Override
		public void mouseReleased(MouseEvent e) {
			
		}

		@Override
		public void mouseEntered(MouseEvent e) {
			
		}

		@Override
		public void mouseExited(MouseEvent e) {
			
		}
		
	}
	
	
	  public void paintComponent(Graphics g){
	        g.setColor(Color.white);
	        g.fillRect(0,0,getWidth(),getHeight());
	    }
	  
	  
	  /**
	   	 * 摘自JDK
	     * Creates an button which will be used as the control to show or hide
	     * the popup portion of the combo box.
	     *
	     * @return a button which represents the popup control
	     */
	    protected JButton createArrowButton() {
	        JButton button = new BasicArrowButton(BasicArrowButton.SOUTH,
	                                    UIManager.getColor("ComboBox.buttonBackground"),
	                                    UIManager.getColor("ComboBox.buttonShadow"),
	                                    UIManager.getColor("ComboBox.buttonDarkShadow"),
	                                    UIManager.getColor("ComboBox.buttonHighlight"));
	        button.setName("ComboBox.arrowButton");
	        return button;
	    }
	    
	   private class MulitComboboxLayout  implements LayoutManager{

			@Override
			public void addLayoutComponent(String name, Component comp) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void removeLayoutComponent(Component comp) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public Dimension preferredLayoutSize(Container parent) {
				return parent.getPreferredSize();
			}

			@Override
			public Dimension minimumLayoutSize(Container parent) {
				return parent.getMinimumSize();
			}

			@Override
			public void layoutContainer(Container parent) {
				int w=parent.getWidth();
	            int h=parent.getHeight();
	            Insets insets=parent.getInsets();
	            h=h-insets.top-insets.bottom;
				
			}
	    	
	    }

}




3.MulitPopup



import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;

/**
 * 
 * @author bugu
 * 
 */
public class MulitPopup extends JPopupMenu {

	private List<ActionListener> listeners = new ArrayList<ActionListener>();

	private Object[] values;
	
	private Object[] defaultValues;
	
	private List<JCheckBox> checkBoxList = new ArrayList<JCheckBox>();
	
	private JButton commitButton ;
	
	private JButton cancelButton;
	
	public static final String COMMIT_EVENT = "commit";
	
	public static final String CANCEL_EVENT = "cancel";
	
	public MulitPopup(Object[] value , Object[] defaultValue) {
		super();
		values = value;
		defaultValues = defaultValue;
		initComponent();
	}

	public void addActionListener(ActionListener listener) {
		if (!listeners.contains(listener))
			listeners.add(listener);
	}

	public void removeActionListener(ActionListener listener) {
		if (listeners.contains(listener))
			listeners.remove(listener);
	}

	private void initComponent() {
		
		JPanel checkboxPane = new JPanel();
		
		JPanel buttonPane = new JPanel();
		
		this.setLayout(new BorderLayout());
		
		
		for(Object v : values){
			JCheckBox temp = new JCheckBox(v.toString() , selected(v));
			checkBoxList.add(temp);
		}
		checkboxPane.setLayout(new GridLayout(checkBoxList.size() , 1 ,3, 3));
		for(JCheckBox box : checkBoxList){
			checkboxPane.add(box);
		}
		
		commitButton = new JButton("ok");
		
		commitButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				commit();
			}
			
		});
		
		cancelButton = new JButton("cancel");
		
		cancelButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				cancel();
			}
			
		});
		
		buttonPane.add(commitButton);
		
		buttonPane.add(cancelButton);
		
		this.add(checkboxPane , BorderLayout.CENTER);
		
		this.add(buttonPane , BorderLayout.SOUTH);
		
		
	}

	private boolean selected(Object v) {
		for(Object dv : defaultValues){
			if( dv .equals(v) ){
				return true;
			}
		}
		return false;
	}

	protected void fireActionPerformed(ActionEvent e) {
		for (ActionListener l : listeners) {
			l.actionPerformed(e);
		}
	}
	
	public Object[] getSelectedValues(){
		List<Object> selectedValues = new ArrayList<Object>();
		for(int i = 0 ; i < checkBoxList.size() ; i++){
			if(checkBoxList.get(i).isSelected())
				selectedValues.add(values[i]);
		}
		return selectedValues.toArray(new Object[selectedValues.size()]);
	}

	public void setDefaultValue(Object[] defaultValue) {
		defaultValues = defaultValue;
		
	}
	
	public void commit(){
		fireActionPerformed(new ActionEvent(this, 0, COMMIT_EVENT));
	}
	
	public void cancel(){
		fireActionPerformed(new ActionEvent(this, 0, CANCEL_EVENT));
	}

}


4.SwingComponent 控件集合


import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;

import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.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 SwingComponent  
{  
    JFrame f = new JFrame("测试");  
    //定义一个按钮,并为之指定图标  
    Icon okIcon = new ImageIcon("ico/ok.png");  
    JButton ok = new JButton("确认" , okIcon);  
    //定义一个单选按钮,初始处于选中状态  
    JRadioButton male = new JRadioButton("男" , true);  
    //定义一个单按钮,初始处于没有选中状态  
    JRadioButton female = new JRadioButton("女" , false);  
    //定义一个ButtonGroup,用于将上面两个JRadioButton组合在一起  
    ButtonGroup bg = new ButtonGroup();  
    //定义一个复选框,初始处于没有选中状态。  
    JCheckBox married = new JCheckBox("是否已婚?" , false);  
    String[] colors = new String[]{"红色" , "绿色"  , "蓝色"};  
    //定义一个下拉选择框  
    JComboBox colorChooser = new JComboBox(colors);  
    //定义一个列表选择框  
    JList colorList = new JList(colors);  
    //定义一个8行、20列的多行文本域  
    JTextArea ta = new JTextArea(8, 20);  
    //定义一个40列的单行文本域  
    JTextField name = new JTextField(40);  
    JMenuBar mb = new JMenuBar();  
    JMenu file = new JMenu("文件");  
    JMenu edit = new JMenu("编辑");  
    //创建“新建”菜单项,并为之指定图标  
    Icon newIcon = new ImageIcon("ico/new.png");  
    JMenuItem newItem = new JMenuItem("新建" , newIcon);  
    //创建“保存”菜单项,并为之指定图标  
    Icon saveIcon = new ImageIcon("ico/save.png");  
    JMenuItem saveItem = new JMenuItem("保存" , saveIcon);  
    //创建“退出”菜单项,并为之指定图标  
    Icon exitIcon = new ImageIcon("ico/exit.png");  
    JMenuItem exitItem = new JMenuItem("退出" , exitIcon);      
    JCheckBoxMenuItem autoWrap = new JCheckBoxMenuItem("自动换行");  
    //创建“复制”菜单项,并为之指定图标  
    JMenuItem copyItem = new JMenuItem("复制" , new ImageIcon("ico/copy.png"));  
    //创建“粘贴”菜单项,并为之指定图标  
    JMenuItem pasteItem = new JMenuItem("粘贴" , new ImageIcon("ico/paste.png"));  
    JMenu format = new JMenu("格式");  
    JMenuItem commentItem = new JMenuItem("注释");  
    JMenuItem cancelItem = new JMenuItem("取消注释");  
      
    //定义一个右键菜单用于设置程序风格  
    JPopupMenu pop = new JPopupMenu();  
    //用于组合三个风格菜单项的ButtonGroup  
    ButtonGroup flavorGroup = new ButtonGroup();  
    //创建三个单选框按钮,用于设定程序的外观风格  
    JRadioButtonMenuItem metalItem = new JRadioButtonMenuItem("Metal风格" , true);  
    JRadioButtonMenuItem windowsItem = new JRadioButtonMenuItem("Windows风格");  
    JRadioButtonMenuItem motifItem = new JRadioButtonMenuItem("Motif风格");  
 
    public void init()  
    {  
        //创建一个装载了文本框、按钮的JPanel  
        JPanel bottom = new JPanel();  
        bottom.add(name);  
        bottom.add(ok);  
        f.add(bottom , BorderLayout.SOUTH);  
        //创建一个装载了下拉选择框、三个JCheckBox的JPanel  
        JPanel checkPanel = new JPanel();  
        checkPanel.add(colorChooser);  
        bg.add(male);  
        bg.add(female);  
        checkPanel.add(male);  
        checkPanel.add(female);  
        checkPanel.add(married);  
        //创建一个垂直排列组件的Box,盛装多行文本域JPanel  
        Box topLeft = Box.createVerticalBox();  
        //使用JScrollPane作为普通组件的JViewPort  
        JScrollPane taJsp = new JScrollPane(ta);  
        topLeft.add(taJsp);  
        topLeft.add(checkPanel);  
        //创建一个垂直排列组件的Box,盛装topLeft、colorList  
        Box top = Box.createHorizontalBox();  
        top.add(topLeft);  
        top.add(colorList);  
//        将top Box容器添加到窗口的中间  
        f.add(top);   
        //-----------下面开始组合菜单、并为菜单添加事件监听器----------  
        //为newItem设置快捷键,设置快捷键时要使用大写字母  
        newItem.setAccelerator(KeyStroke.getKeyStroke('N' , InputEvent.CTRL_MASK));   
        newItem.addActionListener(new ActionListener()  
        {  
            public void actionPerformed(ActionEvent e)  
            {  
                ta.append("用户单击了“新建”菜单/n");  
            }  
        });  
        //为file菜单添加菜单项  
        file.add(newItem);  
        file.add(saveItem);  
        file.add(exitItem);  
        //为edit菜单添加菜单项  
        edit.add(autoWrap);  
        //使用addSeparator方法来添加菜单分隔线  
        edit.addSeparator();  
        edit.add(copyItem);  
        edit.add(pasteItem);  
        commentItem.setToolTipText("将程序代码注释起来!");  
        //为format菜单添加菜单项  
        format.add(commentItem);  
        format.add(cancelItem);  
        //使用添加new JMenuItem("-")的方式不能添加菜单分隔符  
        edit.add(new JMenuItem("-"));  
        //将format菜单组合到edit菜单中,从而形成二级菜单  
        edit.add(format);  
        //将file、edit菜单添加到mb菜单条中  
        mb.add(file);  
        mb.add(edit);  
        //为f窗口设置菜单条  
        f.setJMenuBar(mb);  
        //-----------下面开始组合右键菜单、并安装右键菜单----------  
        flavorGroup.add(metalItem);  
        flavorGroup.add(windowsItem);  
        flavorGroup.add(motifItem);  
        pop.add(metalItem);  
        pop.add(windowsItem);  
        pop.add(motifItem);  
        //为三个菜单创建事件监听器  
        ActionListener flavorListener = new ActionListener()  
        {  
            public void actionPerformed(ActionEvent e)  
            {  
                try 
                {  
                    if (e.getActionCommand().equals("Metal风格"))  
                    {  
                        changeFlavor(1);  
                    }  
                    else if (e.getActionCommand().equals("Windows风格"))  
                    {  
                        changeFlavor(2);  
                    }  
                    else if (e.getActionCommand().equals("Motif风格"))  
                    {  
                        changeFlavor(3);  
                    }  
                }  
                catch (Exception ee)  
                {  
                    ee.printStackTrace();  
                }  
            }  
        };  
        //为三个菜单添加事件监听器  
        metalItem.addActionListener(flavorListener);  
        windowsItem.addActionListener(flavorListener);  
        motifItem.addActionListener(flavorListener);  
        //调用该方法即可设置右键菜单,无需使用事件机制  
        ta.setComponentPopupMenu(pop);   
        //设置关闭窗口时,退出程序  
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        f.pack();  
        f.setVisible(true);  
    }  
 
    //定义一个方法,用于改变界面风格  
    private void changeFlavor(int flavor)throws Exception  
    {  
        switch (flavor)  
        {  
            //设置Metal风格  
            case 1:  
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");  
                break;  
            //设置Windows风格  
            case 2:  
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");  
                break;  
            //设置Motif风格  
            case 3:  
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");  
                break;            
        }  
        //更新f窗口内顶级容器以及内部所有组件的UI  
        SwingUtilities.updateComponentTreeUI(f.getContentPane());  
        //更新mb菜单条以及内部所有组件的UI  
        SwingUtilities.updateComponentTreeUI(mb);  
        //更新pop右键菜单以及内部所有组件的UI  
        SwingUtilities.updateComponentTreeUI(pop);  
 
    }  
    public static void main(String[] args)   
    {  
        //设置Swing窗口使用Java风格  
        JFrame.setDefaultLookAndFeelDecorated(true);   
        new SwingComponent().init();  
    }  
}  


5.JOptionPane  java 提示框
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 TestJOptionPane  
{  
    JFrame jf = new JFrame("测试JOptionPane");  
    //分别定义6个面板用于定义对话框的几种选项  
    private ButtonPanel messagePanel;  
    private ButtonPanel messageTypePanel;  
    private ButtonPanel msgPanel;  
    private ButtonPanel confirmPanel;  
    private ButtonPanel optionsPanel;  
    private ButtonPanel inputPanel;  
    private String messageString = "消息区内容";  
    private Icon messageIcon = new ImageIcon("ico/heart.png");  
    private Object messageObject = new Date();  
    private Component messageComponent = new JButton("组件消息");  
    private JButton msgBn = new JButton("消息对话框");  
    private JButton confrimBn = new JButton("确认对话框");  
    private JButton inputBn = new JButton("输入对话框");  
    private JButton optionBn = new JButton("选项对话框");  
 
    public void init()  
    {  
        JPanel top = new JPanel();  
//        top.setBorder(new TitledBorder(new EtchedBorder(), "对话框的通用选项" ,   
//            TitledBorder.CENTER ,TitledBorder.TOP ));  
        top.setLayout(new GridLayout(1 , 2));  
        //消息类型Panel,该Panel中的选项决定对话框的图标  
        messageTypePanel = new ButtonPanel("选择消息的类型",   
            new String[]{"ERROR_MESSAGE", "INFORMATION_MESSAGE", "WARNING_MESSAGE",   
            "QUESTION_MESSAGE", "PLAIN_MESSAGE" });  
        //消息内容类型的Panel,该Panel中的选项决定对话框的消息区的内容  
        messagePanel = new ButtonPanel("选择消息内容的类型",   
            new String[]{"字符串消息", "图标消息", "组件消息",   "普通对象消息" , "Object[]消息"});  
        top.add(messageTypePanel);  
        top.add(messagePanel);  
        JPanel bottom = new JPanel();  
        bottom.setBorder(new TitledBorder(new EtchedBorder(), "弹出不同的对话框" ,   
            TitledBorder.CENTER ,TitledBorder.TOP));  
        bottom.setLayout(new GridLayout(1 , 4));  
        //创建用于弹出消息对话框的Panel  
        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);  
    }  
    //根据用户选择返回选项类型  
    private int getOptionType()  
    {  
        if (confirmPanel.getSelection().equals("DEFAULT_OPTION"))  
            return JOptionPane.DEFAULT_OPTION;  
        else if (confirmPanel.getSelection().equals("YES_NO_OPTION"))  
            return JOptionPane.YES_NO_OPTION;  
        else if (confirmPanel.getSelection().equals("YES_NO_CANCEL_OPTION"))  
            return JOptionPane.YES_NO_CANCEL_OPTION;  
        else 
            return JOptionPane.OK_CANCEL_OPTION;  
    }  
    //根据用户选择返回消息  
    private Object getMessage()  
    {  
        if (messagePanel.getSelection().equals("字符串消息"))  
            return messageString;  
        else if (messagePanel.getSelection().equals("图标消息"))  
            return messageIcon;  
        else if (messagePanel.getSelection().equals("组件消息"))  
            return messageComponent;  
        else if(messagePanel.getSelection().equals("普通对象消息"))  
            return messageObject;  
        else 
            return  new Object[]{messageString , messageIcon ,   
                messageObject , messageComponent};  
    }  
    //根据用户选择返回消息类型(决定图标区的图标)  
    private int getDialogType()  
    {  
        if (messageTypePanel.getSelection().equals("ERROR_MESSAGE"))  
            return JOptionPane.ERROR_MESSAGE;  
        else if (messageTypePanel.getSelection().equals("INFORMATION_MESSAGE"))  
            return JOptionPane.INFORMATION_MESSAGE;  
        else if (messageTypePanel.getSelection().equals("WARNING_MESSAGE"))  
            return JOptionPane.WARNING_MESSAGE;  
        else if(messageTypePanel.getSelection().equals("QUESTION_MESSAGE"))  
            return JOptionPane.QUESTION_MESSAGE;  
        else 
            return JOptionPane.PLAIN_MESSAGE;  
    }  
    private Object[] getOptions()  
    {  
        if (optionsPanel.getSelection().equals("字符串选项"))  
            return new String[]{"a" , "b" , "c" , "d"};  
        else if (optionsPanel.getSelection().equals("图标选项"))  
            return new Icon[]{new ImageIcon("ico/1.gif") , new ImageIcon("ico/2.gif"),  
            new ImageIcon("ico/3.gif"),new ImageIcon("ico/4.gif")};  
        else 
            return new Object[]{new Date() ,new Date() , new Date()};  
    }  
 
    //为各按钮定义事件监听器  
    private class ShowAction implements ActionListener  
    {  
        public void actionPerformed(ActionEvent event)  
        {    
            if (event.getActionCommand().equals("确认对话框"))  
            {  
                JOptionPane.showConfirmDialog(jf , getMessage(),"确认对话框",   
                    getOptionType(), getDialogType());  
            }  
            else if (event.getActionCommand().equals("输入对话框"))  
            {    
                if (inputPanel.getSelection().equals("单行文本框"))  
                {  
                    JOptionPane.showInputDialog(jf, getMessage(), "输入对话框", getDialogType());  
                }  
                else 
                {  
                    JOptionPane.showInputDialog(jf, getMessage(), "输入对话框", getDialogType(),  
                    null,   new String[] {"轻量级J2EE企业应用实战", "Struts2权威指南"},   
                    "Struts2权威指南");  
                }  
            }  
            else if (event.getActionCommand().equals("消息对话框"))  
            {  
                JOptionPane.showMessageDialog(jf,getMessage(),"消息对话框",getDialogType());  
            }  
            else if (event.getActionCommand().equals("选项对话框"))  
            {  
                JOptionPane.showOptionDialog(jf , getMessage() , "选项对话框", getOptionType(),  
                    getDialogType(), null,  getOptions(), "a");  
            }  
        }  
    }  
 
    public static void main(String[] args)  
    {    
        new TestJOptionPane().init();  
    }  
}  
 
//定义一个JPanel类扩展类,该类的对象包含多个纵向排列的JRadioButton控件  
//且Panel扩展类可以指定一个字符串作为TitledBorder  
class ButtonPanel extends JPanel  
{    
    private ButtonGroup group;  
    public ButtonPanel(String title, String[] options)  
    {    
        setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), title));  
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));  
        group = new ButtonGroup();  
        for (int i = 0; options!= null && i < options.length; i++)  
        {    
            JRadioButton b = new JRadioButton(options[i]);  
            b.setActionCommand(options[i]);  
            add(b);  
            group.add(b);  
            b.setSelected(i == 0);  
        }  
    }  
    //定义一个方法,用于返回用户选择的选项  
    public String getSelection()  
    {    
        return group.getSelection().getActionCommand();  
    }     
} 


6.JToolBar java工具条
import java.awt.BorderLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;

public class TestJToolBar  
{  
    JFrame jf = new JFrame("测试工具条");  
    JTextArea jta = new JTextArea(6, 35);  
    JToolBar jtb = new JToolBar();  
    JMenuBar jmb = new JMenuBar();  
    JMenu edit = new JMenu("编辑");  
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();  
    //创建"粘贴"Action,该Action用于创建菜单项、工具按钮和普通按钮  
    Action pasteAction = new AbstractAction("粘贴", new ImageIcon("ico/paste.png"))  
    {  
        public void actionPerformed(ActionEvent e)  
        {  
            //如果剪贴板中包含stringFlavor内容  
            if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor))  
            {  
                try 
                {  
                    //取出剪贴板中stringFlavor内容  
                    String content = (String)clipboard.getData(DataFlavor.stringFlavor);  
                    //将选中内容替换成剪贴板中的内容  
                    jta.replaceRange(content , jta.getSelectionStart() , jta.getSelectionEnd());  
                }  
                catch (Exception ee)  
                {  
                    ee.printStackTrace();  
                }  
            }  
        }  
    };  
    //创建"复制"Action  
    Action copyAction = new AbstractAction("复制", new ImageIcon("ico/copy.png"))  
    {  
        public void actionPerformed(ActionEvent e)  
        {  
            StringSelection contents = new StringSelection(jta.getSelectedText());  
            //将StringSelection对象放入剪贴板  
            clipboard.setContents(contents, null);  
            //如果剪贴板中包含stringFlavor内容  
            if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor))  
            {  
                //将pasteAction激活  
                pasteAction.setEnabled(true);  
            }  
        }  
    };  
    public void init()  
    {  
        //pasteAction默认处于不激活状态  
        pasteAction.setEnabled(false);  
        jf.add(new JScrollPane(jta));  
        //以Action创建按钮,并将该按钮添加到Panel中  
        JButton copyBn = new JButton(copyAction);  
        JButton pasteBn = new JButton(pasteAction);  
        JPanel jp = new JPanel();  
        jp.add(copyBn);  
        jp.add(pasteBn);  
        jf.add(jp , BorderLayout.SOUTH);  
        //向工具条中添加Action对象,该对象将会转换成工具按钮  
        jtb.add(copyAction);  
        jtb.addSeparator();  
        jtb.add(pasteAction);  
        //向菜单中添加Action对象,该对象将会转换成菜单项  
        edit.add(copyAction);  
        edit.add(pasteAction);  
        //将edit菜单添加到菜单条中  
        jmb.add(edit);  
        jf.setJMenuBar(jmb);  
        //设置工具条和工具按钮之间的距离  
        jtb.setMargin(new Insets(20 ,10 , 5 , 30));  
        //向窗口中添加工具条  
        jf.add(jtb , BorderLayout.NORTH);  
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        jf.pack();  
        jf.setVisible(true);  
    }  
    public static void main(String[] args)   
    {  
        new TestJToolBar().init();  
    }  
} 

你可能感兴趣的:(java)