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();
}
}
做方便实用的SWING控件! 欢迎大家测试并提交BUG报告. 由于个人能力和时间上的局限,希望有兴趣一起开发SWING控件的朋友,请与我联系.让我们一起努力! 为了方便查看,需要讨论的朋友请到另外一个置顶贴子. [讨论]关于"开源SWING控件" -------------------------------------------------------------------- 2004/03/25 首次发布 2004/04/08 把以前的组件和新做的组件合并到一个OpenSwing.jar文件中, 并初步将该组件库命名为”OpenSwing” 2004/06/17 加入了一个打印模板和一些新做的组件。 2004/07/25 加入了一个类似QQ界面的JGroupPane,修正了一些以前的组件的BUG. 对几乎所有的组件全部加入了JavaBeans处理, 使OpenSwing支持可视开发. 2005/04/17 将JNumberField最大长度,小数位长度修正成符合数据库定义的规范,如:NUMBER(10,2) 2005/04/21 修改了JNumberField的参数方式及不能输入负数的BUG,及数字验证方法 JDatePicker弹出时不能显示当前输入日期的BUG 加入了好多人在CJW论坛上贴子中想要的带关闭按钮的JCloseableTabbedPane可关闭的JTabbedPane的组件 2005/06/21 对JDatePicker加入了时分秒的输入 2006/01/20 修正了JPopupButton在XP风格下呈两个按钮样子的BUG 对JFontDialog进行了部分修改 2006/03/08 从JDatePicker提出来一个组件JCalendarPanel日期选择面板 并修改了JDatePicker的设计方式 2006/03/23 加入了韩文支持, 感谢在韩国工作的网友Sang Jian,韩文支持 OpenSwing_ko_KR.properties文件由他提供 2006/04/04 对JFileTree加入了文件过滤器建构式.并对显示进行了排序 -------------------------------------------------------------------- ■以下组件,均在j2sdk1.4.2_01+win2k环境下测试通过,继续欢迎大家测试并提交BUG报告. JCalendarPanel 日期选择面板, 从JDatePicker提出来的控件, 可以单独使用。 JCloseableTabbedPane 带关闭按钮/可设置菜单的JTabbedPane JDateField 日期输入框,输入正确格式的日期 JDatePicker 继承自JComboBox的日期选择框,保证输入正确格式的日期(yyyy-MM-dd) 履历: 2004/03/26 根据网友caiyj的建议引入了recoon写的关于JDateDocument的校验方法 2004/04/02 根据网友caiyj提交的BUG,修正了做为TableCellEditor时日期选择面板弹不出问题 JDirChooser 文件目录选择对话框 JFileTree 文件目录树 JFontDialog 字体对话框 JGroupPane 类似QQ界面的组群管理面板 JIpAddressField IP地址输入框,只能输入0~255数字的IP地址 JListChooser 列表选择对话框 JNumberField 数字输入框,可限制小数位数,数字最大长度,最大最小能输入的数字 JPopupButton 带下拉菜单的工具栏按钮 JStatusBar 模拟Windows的状态栏. JStringField 字符输入框,限制可输入的最大长度 JTreeComboBox 带有树形结构的下拉列表 com.sunking.swing.print.* 一个打印模板 -------------------------------------------------------------------- ■ OpenSwing的测试方法: 解压后是一个JBUILDER项目的目录结构,里面有一个test.bat文件和OpenSwing.jar(主库文件)/OpenSwingBeanInfo.jar(可视开发支持文件),直接执行test.bat进行测试。 ■ OpenSwing的发布: 只需要将OpenSwing.jar(主库文件)包含在CLASSPATH中即可。 OpenSwingBeanInfo.jar(可视开发支持文件)不需要发布, 仅提供可视化开发的支持 ■JBuilder上配置OpenSwing可视化开发组件 1.将OpenSwing.jar/ OpenSwingBeanInfo.jar文件复制到 %JBuilderX_HOME%\lib\ 目录下 2.打开JBuilderX 3.菜单Tools --> Configure Libraries…-->弹出Configure Libraries…对话框 ①New… --> Name中输入OpenSwing, Location中输入User Home -->OK ②选取对话框左边User Home下面出现的OpenSwing ③对话框右边Class和 Source页中分别做如下动作: Add…-->选择%JBuilder_HOME%\lib\OpenSwing.jar和OpenSwingBeanInfo.jar --> OK ④按OK关闭 Configure Libraries…对话框 4.菜单Tools--> Configure Palette… 弹出Palette Properties…对话框 ①Pages 页中按 Add… --> PageName中输入OpenSwing --> OK ②Add components页中 -->Select library…--> 选取User Home 下的OpenSwing类库-->OK ③Add components页中 -->在Component filtering块中选择 No filtering-->展开com.sunking.swing类包-->选择如下类: JGroupPanel,JStatusBar,JPopupButton,JDatePicker,JStringField,JNumberField,JFontDialog,JIpAddressField,JDateField (可按住Ctrl键复选)-->OK ④按OK关闭Palette Properties…对话框 5.配置成功标志: 随便打开一个JAVA文件,点下面的Design页,然后上面会出来一个设计工具条,诸如:Swing,Swing Containers…等,工具条的右上角有用来滚动工具栏的按钮,我们可以将其滚动到最末尾.如果看到有一个OpenSwing的页,并在它上面有几个可视组件的话,说明你已经配置成功了,开始你的OpenSwing可视开发之旅吧.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值