这个小教程是个swing的小例子
[java]
package test;
import java.awt.event.*;
import javax.swing.*;
public class CheckBox extends JPanel implements ItemListener, ActionListener{
private static final long serialVersionUID = 1L;
protected JButton leftButton, rightButton;
public static void main(String args[]){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("测试窗口");
CheckBox contentPanel = new CheckBox();
contentPanel.setOpaque(true);
frame.setContentPane(contentPanel);
frame.setLocation(300, 300);
frame.setSize(300,300);
frame.setVisible(true);
}
public CheckBox(){
ImageIcon leftIcon = createImageIcon("left.gif");
leftButton = new JButton("左边按钮",leftIcon);
leftButton.setVerticalTextPosition(SwingConstants.CENTER);
leftButton.setHorizontalTextPosition(SwingConstants.LEADING);
leftButton.setEnabled(false);
leftButton.setActionCommand("disabled");
ImageIcon rightIcon = createImageIcon("/left.gif");
rightButton = new JButton("右边的按钮",rightIcon);
rightButton.setVerticalTextPosition(SwingConstants.BOTTOM);
rightButton.setHorizontalTextPosition(SwingConstants.CENTER);
rightButton.setActionCommand("rightButton");
rightButton.setEnabled(true);
add(leftButton);
add(rightButton);
leftButton.addActionListener(this);
rightButton.addActionListener(this);
}
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
}
protected static ImageIcon createImageIcon(String path){
java.net.URL imageUrl = CheckBox.class.getResource("/left.gif");
if(imageUrl != null){
return new ImageIcon(imageUrl);
} else {
System.out.println("can't find file"+path);
return null;
}
}
public void actionPerformed(ActionEvent e){
if("rightButton".equals(e.getActionCommand())){
leftButton.setEnabled(true);
} else {
System.out.println(e.getActionCommand());
}
}
}
[/java]
这里有个小地方需要注意一下就是使用CheckBox.class.getResource来读取图片资源的时候,如果使用eclispe来编写的时候会有些问题,这里需要修改一下run→run configurations→java application→你的项目名称→classpath→user entries→adcanced→add folser,然后添加图片的路径进去,这样才eclispe下面才能找到图片路径,如果没使用eclispe ide,手动来建立目录,那么这里没有问题。