??xml version="1.0" encoding="utf-8" standalone="yes"?>
也希望大家有什么好的功能徏议提出来,
我会快完善功能.
MSN见首公?br>?span>能说?br>面板Q?nbsp;
提供鼠标点击修改功能
提供鼠标Ud数据跟随昄功能
提供数据扚w修改功能(右键拖拽选取Q按键盘上下键修?
数据修改提示曲线 (两条l色的细U?
数据修改回溯(键盘ESC?
面板右键菜单Q?br> 保存囄
颜色修改
标题字体修改
数据分时D修?br> 是否允许修改
曲线跟踪提示
是否有数据跟t显C?br>主菜单:
修改UImanager
数据昄表格Q?br> 昄数据
修改数据(输入数据后回车或者点d的行)
树面板:删除曲线
颜色修改
下蝲链接
jdk版本 1.6
截图Q?br>
]]>
import java.awt.Dimension;
import java.util.Vector;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class WideComboBox extends JComboBox {
public WideComboBox() {
}
public WideComboBox(final Object items[]) {
super(items);
}
public WideComboBox(Vector items) {
super(items);
}
public WideComboBox(ComboBoxModel aModel) {
super(aModel);
}
private boolean layingOut = false;
public void doLayout() {
try {
layingOut = true;
super.doLayout();
} finally {
layingOut = false;
}
}
public Dimension getSize() {
Dimension dim = super.getSize();
if (!layingOut)
dim.width = Math.max(dim.width, getPreferredSize().width);
return dim;
}
public static void main(String[] args) {
JFrame jf = new JFrame();
WideComboBox wc = new WideComboBox(new String[] { "11111111111111",
"22222222222222", "333" });
jf.getContentPane().add(wc);
jf.setVisible(true);
}
}
二:java对象序列化不仅保留一个对象的数据Q而且递归保存对象引用的每个对象的数据。可以将整个对象层次写入字节中Q可以保存在文g中或在网l连接上传递。利用对象序列化可以q行对象的“深复制”,卛_制对象本w及引用的对象本w。序列化一个对象可能得到整个对象序列?/p>
从上面的叙述中,我们知道了对象序列化是java~程中的必备武器Q那么让我们从基开始,好好学习一下它的机制和用法?/p>
java序列化比较简单,通常不需要编写保存和恢复对象状态的定制代码。实现java.io.Serializable接口的类对象可以转换成字节流或从字节恢复,不需要在cM增加M代码。只有极数情况下才需要定制代码保存或恢复对象状态。这里要注意Q不是每个类都可序列化,有些cL不能序列化的Q例如涉及线E的cM特定JVM有非常复杂的关系?/p>
序列化机Ӟ
序列化分Z大部分:序列化和反序列化。序列化是这个过E的W一部分Q将数据分解成字节流Q以便存储在文g中或在网l上传输。反序列化就是打开字节ƈ重构对象。对象序列化不仅要将基本数据cd转换成字节表C,有时q要恢复数据。恢复数据要求有恢复数据的对象实例。ObjectOutputStream中的序列化过E与字节连接,包括对象cd和版本信息。反序列化时QJVM用头信息生成对象实例Q然后将对象字节中的数据复制到对象数据成员中。下面我们分两大部分来阐qͼ
处理对象:
Q序列化q程和反序列化过E)
java.io包有两个序列化对象的cRObjectOutputStream负责对象写入字节流QObjectInputStream从字节流重构对象?/p>
我们先了解ObjectOutputStreamcd。ObjectOutputStreamcL展DataOutput接口?/p>
writeObject()Ҏ是最重要的方法,用于对象序列化。如果对象包含其他对象的引用Q则writeObject()Ҏ递归序列化这些对象。每个ObjectOutputStreaml护序列化的对象引用表,防止发送同一对象的多个拷贝。(q点很重要)׃writeObject()可以序列化整l交叉引用的对象Q因此同一ObjectOutputStream实例可能不小心被h序列化同一对象。这Ӟq行反引用序列化Q而不是再ơ写入对象字节流?/p>
下面Q让我们从例子中来了解ObjectOutputStreamq个cd?/p>
// 序列?today's date C个文件中.
FileOutputStream f = new FileOutputStream("tmp");
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject("Today");
s.writeObject(new Date());
s.flush();
现在Q让我们来了解ObjectInputStreamq个cR它与ObjectOutputStream怼。它扩展DataInput接口。ObjectInputStream中的Ҏ镜像DataInputStream中读取Java基本数据cd的公开Ҏ。readObject()Ҏ从字节流中反序列化对象。每ơ调用readObject()Ҏ都返回流中下一个Object。对象字节流q不传输cȝ字节码,而是包括cd及其{。readObject()收到对象ӞJVM装入头中指定的类。如果找不到q个c,则readObject()抛出ClassNotFoundException,如果需要传输对象数据和字节码,则可以用RMI框架。ObjectInputStream的其余方法用于定制反序列化过E?/p>
例子如下Q?/p>
//从文件中反序列化 string 对象?date 对象
FileInputStream in = new FileInputStream("tmp");
ObjectInputStream s = new ObjectInputStream(in);
String today = (String)s.readObject();
Date date = (Date)s.readObject();
定制序列化过E?
序列化通常可以自动完成Q但有时可能要对q个q程q行控制。java可以类声明为serializableQ但仍可手工控制声明为static或transient的数据成员?/p>
例子Q一个非常简单的序列化类?/p>
public class simpleSerializableClass implements Serializable{
String sToday="Today:";
transient Date dtToday=new Date();
}
序列化时Q类的所有数据成员应可序列化除了声明为transient或static的成员。将变量声明为transient告诉JVM我们会负责将变元序列化。将数据成员声明为transient后,序列化过E就无法其加进对象字节中Q没有从transient数据成员发送的数据。后面数据反序列化时Q要重徏数据成员Q因为它是类定义的一部分Q,但不包含M数据Q因个数据成员不向流中写入Q何数据。记住,对象不序列化static或transient。我们的c要用writeObject()与readObject()Ҏ以处理这些数据成员。用writeObject()与readObject()ҎӞq要注意按写入的序dq些数据成员?/p>
关于如何使用定制序列化的部分代码如下Q?/p>
//重写writeObject()Ҏ以便处理transient的成员?/p>
public void writeObject(ObjectOutputStream outputStream) throws IOException{
outputStream.defaultWriteObject();//使定制的writeObject()Ҏ可以
利用自动序列化中内置的逻辑?/p>
outputStream.writeObject(oSocket.getInetAddress());
outputStream.writeInt(oSocket.getPort());
}
//重写readObject()Ҏ以便接收transient的成员?/p>
private void readObject(ObjectInputStream inputStream) throws IOException,ClassNotFoundException{
inputStream.defaultReadObject();//defaultReadObject()补充自动序列?br /> InetAddress oAddress=(InetAddress)inputStream.readObject();
int iPort =inputStream.readInt();
oSocket = new Socket(oAddress,iPort);
iID=getID();
dtToday =new Date();
}
完全定制序列化过E?
如果一个类要完全负责自q序列化,则实现Externalizable接口而不是Serializable接口。Externalizable接口定义包括两个ҎwriteExternal()与readExternal()。利用这些方法可以控制对象数据成员如何写入字节流.cd现ExternalizableӞ头写入对象流中,然后cd全负责序列化和恢复数据成员,除了头以外,Ҏ没有自动序列化。这里要注意了。声明类实现Externalizable接口会有重大的安全风险。writeExternal()与readExternal()Ҏ声明为publicQ恶意类可以用这些方法读取和写入对象数据。如果对象包含敏感信息,则要格外心。这包括使用安全套接或加密整个字节流。到此ؓ臻I我们学习了序列化的基部分知识?br />
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.text.AttributeSet;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Document;
import javax.swing.text.EditorKit;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyledEditorKit;
public class NewJFrame extends javax.swing.JFrame implements ActionListener {
private JPanel jp1;
private JButton color;
private JTextPane jep;
private JScrollPane jsp;
private JButton font;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
NewJFrame inst = new NewJFrame();
inst.setVisible(true);
}
public NewJFrame() {
super();
initGUI();
}
private void initGUI() {
try {
BorderLayout thisLayout = new BorderLayout();
getContentPane().setLayout(thisLayout);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
{
jp1 = new JPanel();
getContentPane().add(jp1, BorderLayout.NORTH);
{
font = new JButton();
font.addActionListener(this);
jp1.add(font);
font.setText("font");
}
{
color = new JButton();
jp1.add(color);
color.addActionListener(this);
color.setText("color");
}
}
{
jsp = new JScrollPane();
getContentPane().add(jsp, BorderLayout.CENTER);
{
jep = new JTextPane();
jsp.setViewportView(jep);
jep.setDocument(new DefaultStyledDocument());
}
}
pack();
setSize(400, 300);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void setFontSize(JEditorPane editor, int size) {
if (editor != null) {
if ((size > 0) && (size < 512)) {
MutableAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setFontSize(attr, size);
setCharacterAttributes(editor, attr, false);
} else {
UIManager.getLookAndFeel().provideErrorFeedback(editor);
}
}
}
public static void setForeground(JEditorPane editor, Color fg) {
if (editor != null) {
if (fg != null) {
MutableAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setForeground(attr, fg);
setCharacterAttributes(editor, attr, false);
} else {
UIManager.getLookAndFeel().provideErrorFeedback(editor);
}
}
}
public static final void setCharacterAttributes(JEditorPane editor,
AttributeSet attr, boolean replace) {
int p0 = editor.getSelectionStart();
int p1 = editor.getSelectionEnd();
if (p0 != p1) {
StyledDocument doc = getStyledDocument(editor);
doc.setCharacterAttributes(p0, p1 - p0, attr, replace);
}
StyledEditorKit k = getStyledEditorKit(editor);
MutableAttributeSet inputAttributes = k.getInputAttributes();
if (replace) {
inputAttributes.removeAttributes(inputAttributes);
}
inputAttributes.addAttributes(attr);
}
protected static final StyledDocument getStyledDocument(JEditorPane e) {
Document d = e.getDocument();
if (d instanceof StyledDocument) {
return (StyledDocument) d;
}
throw new IllegalArgumentException("document must be StyledDocument");
}
protected static final StyledEditorKit getStyledEditorKit(JEditorPane e) {
EditorKit k = e.getEditorKit();
if (k instanceof StyledEditorKit) {
return (StyledEditorKit) k;
}
throw new IllegalArgumentException("EditorKit must be StyledEditorKit");
}
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
if (obj == font) {
JEditorPane editor = jep;
setFontSize(editor, 20);
}
if (obj == color) {
JEditorPane editor = jep;
setForeground(editor, Color.red);
}
}
}
JRadioButton motifButton = new JRadioButton("Motif"),
windowsButton = new JRadioButton("Windows"),
metalButton = new JRadioButton("Metal");
public ControlPanel() {
ActionListener listener = new RadioHandler();
ButtonGroup group = new ButtonGroup();
group.add(motifButton);
group.add(windowsButton);
group.add(metalButton);
motifButton.addActionListener(listener);
windowsButton.addActionListener(listener);
metalButton.addActionListener(listener);
add(motifButton);
add(windowsButton);
add(metalButton);
}
class RadioHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
JRadioButton src = (JRadioButton) e.getSource();
try {
if (src == motifButton)
UIManager.setLookAndFeel("com.sun.java.swing.plaf."
+ "motif.MotifLookAndFeel");
else if (src == windowsButton)
UIManager.setLookAndFeel("com.sun.java.swing.plaf."
+ "windows.WindowsLookAndFeel");
else if (src == metalButton)
UIManager.setLookAndFeel("javax.swing.plaf.metal."
+ "MetalLookAndFeel");
} catch (Exception ex) {
ex.printStackTrace();
}
SwingUtilities.updateComponentTreeUI(getContentPane());
}
}
}
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
public class NewJFrame extends javax.swing.JFrame {
private JPanel jp1;
private JButton jb1;
private JButton jb2;
private JMenuItem jm12;
private JMenuItem jm11;
private JMenu jm;
private JMenuBar jMenuBar1;
private JTextArea jta;
private JScrollPane jsp;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
NewJFrame inst = new NewJFrame();
inst.setVisible(true);
}
public NewJFrame() {
super();
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
{
jMenuBar1 = new JMenuBar();
setJMenuBar(jMenuBar1);
{
jm = new JMenu();
jMenuBar1.add(jm);
jm.setText("jm");
{
jm11 = new JMenuItem(redoAction);
jm.add(jm11);
jm11.setText("re");
}
{
jm12 = new JMenuItem(undoAction);
jm.add(jm12);
jm12.setText("undo");
}
jm12.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z,
InputEvent.CTRL_MASK));
}
}
{
jp1 = new JPanel();
getContentPane().add(jp1, BorderLayout.NORTH);
jp1.setPreferredSize(new java.awt.Dimension(392, 35));
{
jb1 = new JButton(redoAction);
jp1.add(jb1);
jb1.setText("redo");
}
// jb1.registerKeyboardAction(redoAction, KeyStroke.getKeyStroke(
// KeyEvent.VK_Y, KeyEvent.CTRL_DOWN_MASK, true),
// JComponent.WHEN_IN_FOCUSED_WINDOW);
{
jb2 = new JButton(undoAction);
jp1.add(jb2);
jb2.setText("undo");
}
// jb2.registerKeyboardAction(undoAction, KeyStroke.getKeyStroke(
// KeyEvent.VK_Z, KeyEvent.CTRL_DOWN_MASK, true),
// JComponent.WHEN_IN_FOCUSED_WINDOW);
}
{
jsp = new JScrollPane();
getContentPane().add(jsp, BorderLayout.CENTER);
{
jta = new JTextArea();
jsp.setViewportView(jta);
jta.getDocument().addUndoableEditListener(undoHandler);
}
}
pack();
setSize(400, 300);
} catch (Exception e) {
e.printStackTrace();
}
}
protected UndoableEditListener undoHandler = new UndoHandler();
protected UndoManager undo = new UndoManager();
private UndoAction undoAction = new UndoAction();
private RedoAction redoAction = new RedoAction();
class UndoHandler implements UndoableEditListener {
/**
* Messaged when the Document has created an edit, the edit is
* added to <code>undo</code>, an instance of UndoManager.
*/
public void undoableEditHappened(UndoableEditEvent e) {
undo.addEdit(e.getEdit());
undoAction.update();
redoAction.update();
}
}
class UndoAction extends AbstractAction {
public UndoAction() {
super();
setEnabled(false);
}
public void actionPerformed(ActionEvent e) {
try {
undo.undo();
} catch (CannotUndoException ex) {
ex.printStackTrace();
}
update();
redoAction.update();
}
protected void update() {
if (undo.canUndo()) {
setEnabled(true);
// System.out.println(undo.getUndoPresentationName());
putValue(Action.NAME, undo.getUndoPresentationName());
} else {
setEnabled(false);
putValue(Action.NAME, "撤消");
}
}
}
class RedoAction extends AbstractAction {
public RedoAction() {
super();
setEnabled(false);
}
public void actionPerformed(ActionEvent e) {
try {
undo.redo();
} catch (CannotRedoException ex) {
ex.printStackTrace();
}
update();
undoAction.update();
}
protected void update() {
if (undo.canRedo()) {
setEnabled(true);
putValue(Action.NAME, undo.getRedoPresentationName());
} else {
setEnabled(false);
putValue(Action.NAME, "重做");
}
}
}
}
/**
* 用Java模拟出QQ桌面截图功能
*/
public class Test extends JFrame {
private static final long serialVersionUID = -267804510087895906L;
private JButton button = null;
private JLabel imgLabel = null;
public Test() {
button = new JButton("模拟屏幕Q点右键退出)");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
new ScreenWindow(imgLabel);
} catch (Exception e1) {
JOptionPane.showConfirmDialog(null, "出现意外错误Q?, "pȝ提示", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
}
}
});
JPanel pane = new JPanel();
pane.setBackground(Color.WHITE);
imgLabel = new JLabel();
pane.add(imgLabel);
JScrollPane spane = new JScrollPane(pane);
this.getContentPane().add(button, BorderLayout.NORTH);
this.getContentPane().add(spane);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(300, 200);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
new Test();
}
}
class ScreenWindow extends JFrame {
private static final long serialVersionUID = -3758062802950480258L;
private boolean isDrag = false;
private int x = 0;
private int y = 0;
private int xEnd = 0;
private int yEnd = 0;
public ScreenWindow(final JLabel imgLabel) throws AWTException, InterruptedException {
Dimension screenDims = Toolkit.getDefaultToolkit().getScreenSize();
JLabel label = new JLabel(new ImageIcon(ScreenImage.getScreenImage(0, 0, screenDims.width, screenDims.height)));
label.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
label.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
dispose();
}
}
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
}
public void mouseReleased(MouseEvent e) {
if (isDrag) {
xEnd = e.getX();
yEnd = e.getY();
if(x > xEnd){
int temp = x;
x = xEnd;
xEnd = temp;
}
if(y > yEnd){
int temp = y;
y = yEnd;
yEnd = temp;
}
try {
imgLabel.setIcon(new ImageIcon(ScreenImage.getScreenImage(x, y, xEnd - x, yEnd - y)));
} catch (Exception ex) {
JOptionPane.showConfirmDialog(null, "出现意外错误Q?, "pȝ提示", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
}
dispose();
}
}
});
label.addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
if(!isDrag)
isDrag = true;
}
public void mouseMoved(MouseEvent e) {
/** 拖动q程的虚UK取框需自己实现 */
}
});
this.setUndecorated(true);
this.getContentPane().add(label);
this.setSize(screenDims.width, screenDims.height);
this.setVisible(true);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
}
class ScreenImage {
public static Image getScreenImage(int x, int y, int w, int h) throws AWTException, InterruptedException {
Robot robot = new Robot();
Image screen = robot.createScreenCapture(new Rectangle(x, y, w, h)).getScaledInstance(w, h, Image.SCALE_SMOOTH);
MediaTracker tracker = new MediaTracker(new Label());
tracker.addImage(screen, 1);
tracker.waitForID(0);
return screen;
}
}
截屏
public class GuiCamera {
private String fileName; //文g的前~
private String defaultName = "GuiCamera";
static int serialNum = 0;
private String imageFormat; //囑փ文g的格?
private String defaultImageFormat = "png";
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
/****************************************************************
* 默认的文件前~为GuiCameraQ文件格式ؓPNG格式
* The default construct will use the default
* Image file surname "GuiCamera",
* and default image format "png"
****************************************************************/
public GuiCamera() {
fileName = defaultName;
imageFormat = defaultImageFormat;
}
/****************************************************************
* @param s the surname of the snapshot file
* @param format the format of the image file,
* it can be "jpg" or "png"
* 本构造支持JPG和PNG文g的存?
****************************************************************/
public GuiCamera(String s, String format) {
fileName = s;
imageFormat = format;
}
/****************************************************************
* 对屏q进行拍?
* snapShot the Gui once
****************************************************************/
public void snapShot() {
try {
//拯屏幕C个BufferedImage对象screenshot
BufferedImage screenshot = (new Robot())
.createScreenCapture(new Rectangle(0, 0,
(int) d.getWidth(), (int) d.getHeight()));
serialNum++;
//Ҏ文g前缀变量和文件格式变量,自动生成文g?
String name = fileName + String.valueOf(serialNum) + "."
+ imageFormat;
File f = new File(name);
System.out.print("Save File " + name);
//screenshot对象写入囑փ文g
ImageIO.write(screenshot, imageFormat, f);
System.out.print("..Finished!\n");
} catch (Exception ex) {
System.out.println(ex);
}
}
public static void main(String[] args) {
GuiCamera cam = new GuiCamera("d:\\Hello", "png");//
cam.snapShot();
}
}
透明H体
public class TransparentBackground extends JComponent implements
ComponentListener, WindowFocusListener, Runnable {
private JFrame frame;
private Image background;
private long lastupdate = 0;
public boolean refreshRequested = true;
public TransparentBackground(JFrame frame) {
this.frame = frame;
updateBackground();
frame.addComponentListener(this);
frame.addWindowFocusListener(this);
new Thread(this).start();
}
public void componentShown(ComponentEvent evt) {
repaint();
}
public void componentResized(ComponentEvent evt) {
repaint();
}
public void componentMoved(ComponentEvent evt) {
repaint();
}
public void componentHidden(ComponentEvent evt) {
}
public void windowGainedFocus(WindowEvent evt) {
refresh();
}
public void windowLostFocus(WindowEvent evt) {
refresh();
}
public void refresh() {
if (frame.isVisible()) {
repaint();
refreshRequested = true;
lastupdate = new Date().getTime();
}
}
public void run() {
try {
while (true) {
Thread.sleep(250);
long now = new Date().getTime();
if (refreshRequested && ((now - lastupdate) > 1000)) {
if (frame.isVisible()) {
Point location = frame.getLocation();
// frame.setVisible(false);
updateBackground();
// frame.setVisible(true);
frame.setLocation(location);
refresh();
}
lastupdate = now;
refreshRequested = false;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Transparent Window");
frame.setUndecorated(true);
TransparentBackground bg = new TransparentBackground(frame);
// bg.snapBackground();
bg.setLayout(new BorderLayout());
JPanel panel = new JPanel() {
public void paintComponent(Graphics g) {
g.setColor(Color.blue);
Image img = new ImageIcon("d:/moon.gif").getImage();
g.drawImage(img, 150, 150, null);
// g.drawLine(0,0, 600, 500);
}
};
panel.setOpaque(false);
JLabel jl=new JLabel(new ImageIcon("d:/moon.gif"));
bg.add("North", jl);
bg.add("Center", panel);
frame.getContentPane().add("Center", bg);
frame.pack();
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension dim = tk.getScreenSize();
frame.setSize((int) dim.getWidth(), (int) dim.getHeight());
frame.setLocationRelativeTo(null);
frame.show();
}
public void updateBackground() {
try {
Robot rbt = new Robot();
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension dim = tk.getScreenSize();
background = rbt.createScreenCapture(new Rectangle(0, 0, (int) dim
.getWidth(), (int) dim.getHeight()));
} catch (Exception ex) {
// p(ex.toString( ));
// 此方法没有申明过Q因为无法得知上下文。因Z影响执行效果Q先注释掉它
ex.printStackTrace();
}
}
public void paintComponent(Graphics g) {
Point pos = this.getLocationOnScreen();
Point offset = new Point(-pos.x, -pos.y);
g.drawImage(background, offset.x, offset.y, null);
}
}
String filename = LocalAccess.getSaveFileName(comp,"JavaComponent.jpg");
if(filename==null)return false;
BufferedOutputStream bos =
new BufferedOutputStream(new FileOutputStream(filename));
com.sun.image.codec.jpeg.JPEGImageEncoder encoder = com.sun.image.codec.jpeg.JPEGCodec.createJPEGEncoder(bos);
com.sun.image.codec.jpeg.JPEGEncodeParam jep = encoder.getDefaultJPEGEncodeParam(image);
jep.setQuality(1.0f, false);
encoder.setJPEGEncodeParam(jep);
encoder.encode(image);
bos.close();
}
catch (Exception e) {
result = false;
e.printStackTrace();
}
return result;
}
javax.swing.UIManager.setLookAndFeel(alloyLnF);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
// You may handle the exception here
ex.printStackTrace();
}
import javax.swing.*;
public class T {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
}
final JTextField tf = new JTextField();
tf.setEnabled(false);
JPanel p = new JPanel(new GridLayout(0, 3, 5, 5));
for (int i = 0; i <= 9; i++) {
final JButton btn = new JButton(String.valueOf(i));
p.add(btn);
btn.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke((char) (i + '0')), "PressKeyAction");
btn.getActionMap().put("PressKeyAction", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
btn.doClick();
}
});
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tf.setText(tf.getText() + btn.getText());
}
});
}
JFrame f = new JFrame();
JComponent contentPane = (JComponent) f.getContentPane();
contentPane.setLayout(new BorderLayout(0, 5));
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
f.getContentPane().add(p, BorderLayout.CENTER);
f.getContentPane().add(tf, BorderLayout.NORTH);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
4、QҎq算
import java.math.BigDecimal;
/**
* ׃Java的简单类型不能够_的对点数进行运,q个工具cL供精
* 的点数运,包括加减乘除和四舍五入?br />*/
public class Arith {
//默认除法q算_ֺ
private static final int DEF_DIV_SCALE = 10;
//q个cM能实例化
private Arith() {
}
/**
* 提供_的加法运?br /> * @param v1 被加?br /> * @param v2 加数
* @return 两个参数的和
*/
public static float add(float v1, float v2) {
BigDecimal b1 = new BigDecimal(Float.toString(v1));
BigDecimal b2 = new BigDecimal(Float.toString(v2));
return b1.add(b2).floatValue();
}
/**
* 提供_的减法运?br /> * @param v1 被减?br /> * @param v2 减数
* @return 两个参数的差
*/
public static float sub(float v1, float v2) {
BigDecimal b1 = new BigDecimal(Float.toString(v1));
BigDecimal b2 = new BigDecimal(Float.toString(v2));
return b1.subtract(b2).floatValue();
}
/**
* 提供_的乘法运?br /> * @param v1 被乘?br /> * @param v2 乘数
* @return 两个参数的积
*/
public static float mul(float v1, float v2) {
BigDecimal b1 = new BigDecimal(Float.toString(v1));
BigDecimal b2 = new BigDecimal(Float.toString(v2));
return b1.multiply(b2).floatValue();
}
/**
* 提供Q相对)_的除法运,当发生除不尽的情冉|Q精到
* 数点以?0位,以后的数字四舍五入?br /> * @param v1 被除?br /> * @param v2 除数
* @return 两个参数的商
*/
public static float div(float v1, float v2) {
return div(v1, v2, DEF_DIV_SCALE);
}
/**
* 提供Q相对)_的除法运。当发生除不的情况Ӟ由scale参数?br /> * 定精度,以后的数字四舍五入?br /> * @param v1 被除?br /> * @param v2 除数
* @param scale 表示表示需要精到数点以后几位?br /> * @return 两个参数的商
*/
public static float div(float v1, float v2, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Float.toString(v1));
BigDecimal b2 = new BigDecimal(Float.toString(v2));
return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).floatValue();
}
/**
* 提供_的小C四舍五入处理?br /> * @param v 需要四舍五入的数字
* @param scale 数点后保留几位
* @return 四舍五入后的l果
*/
public static float round(float v, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Float.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).floatValue();
}
};
5、applet获得焦点
this.addComponentListener(new ComponentListener(){
public void componentHidden(ComponentEvent e) {
// TODO 自动生成Ҏ存根
}
public void componentMoved(ComponentEvent e) {
// TODO 自动生成Ҏ存根
}
public void componentResized(ComponentEvent e) {
// TODO 自动生成Ҏ存根
}
public void componentShown(ComponentEvent e) {
// TODO 自动生成Ҏ存根
startButton.requestFocusInWindow();
}
});
JFrame 获得焦点
this.addWindowListener(new WindowAdapter()
{
public void windowActivated(WindowEvent e)
{
jinput.requestFocus();
}
});
6、设定JSpinner格式
((JSpinner.DefaultEditor) j.getEditor()).getTextField()
.setFormatterFactory(
new DefaultFormatterFactory(new NumberFormatter(
new DecimalFormat("#,#"))));
7、字?/font>
FontMetrics fm = label.getFontMetrics(font); // fontZ所使用的字?br />int strWidth = fm.stringWidth("字符?); // q样可以得到字符串的长度(像素),字符串的高度一般是字体的大?br />int width = 200; // 矩Ş的长?br />int high = 50; // 矩Ş的高
drawString("字符?, (width - strWidth) / 2, (high - font.getSize()) / 2 + font.getSize());
8、translate(800,600)
系l坐标逻辑Ud(800,600)以后再画囑փ׃q个逻辑原点为参照点Q用完以后要translate(-800,-600)回去
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>
负荷预测pȝ1
</title>
</head>
<body>
<p align= "center">
<!--<script language="JavaScript" src="temp.js"> -->
<script language="JavaScript">
document.write('<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" width="100%" height="100%" name="DFApplet">\n');
document.write('<param name="code" value="applet.NewJApplet">\n');
document.write('<param name="archive" value=".">\n');
document.write('<param name="codebase" value=".">\n');
document.write('<param name="applet" value="applet.NewJApplet">\n');
document.write('</object>\n');
</script>
</body>
</html>
用了2个层Q第一个层Qid为loadingQ可以写上一些提C消息。而第2个层(id为myapplet)在一开始是不可见的。当applet下蝲好了Q马上把W?个层昄出来Qƈ把第一个层设ؓ不可见。因此,只要q?个层大小Q位|必d全一致。就可以实现我们的目标?/p>
现在我们只差最后一个问题需要解冻I如何知道applet已经完全下蝲了呢Q在IE和netscape中都有提供document.allq个属性,当应面的全部内容(包括applets,囄Q声音等Q已l下载后该属性ؓ真。好Q这P我们只需监测document.all是否为真Q如果是Q那可以把消息所在的层设Z可见Q而applet所在的层设为可见,q刷新applet的显C(因ؓ先前applet的显C隐藏了)Q否则则相反处理?/p>