java经典小例子

这个小教程是个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,手动来建立目录,那么这里没有问题。

Avatar photo

About Blackford

这是个最好的时代,这是个最坏的时代,这是个充满希望的春天,这是个令人绝望的冬天,我们前面什么都有,我们前面什么都没有。梦想,让我们一次次的走远,又一次次的回头,一个关于人生的梦想还在不断奔跑,带着喜悦和疼痛,不过一切才刚刚开始,并且直到今天也远远没有结束
This entry was posted in Java编程语言 and tagged , . Bookmark the permalink.

发表评论

电子邮件地址不会被公开。 必填项已用*标注