test.java

来自「java2 图形设计 卷II Swing」· Java 代码 · 共 69 行

JAVA
69
字号
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JFrame {
	static private JWindow window;

	public Test() {
		super("Animated Icon in a Window");

		Container contentPane = getContentPane();
		JPanel panel = new ImagePanel();
		JButton button = new JButton("Buffalo ...");

		contentPane.setLayout(new FlowLayout());
		contentPane.add(button);

		button.addActionListener(new ActionListener() {
			private Container wcp;

			public void actionPerformed(ActionEvent e) {
				if(window == null) {
					Point loc = getLocation();

					window = new JWindow();
					wcp = window.getContentPane();

					wcp.add(new ImagePanel());
					window.pack();
					window.setLocation(55, 10);
				}
				window.setVisible(true);
			}
		});
	}
	public static void main(String[] args) {
		JFrame f = new Test();
		f.setBounds(300, 300, 250, 100);
		f.setVisible(true);

		f.addWindowListener(new WindowAdapter() {
			public void windowClosed(WindowEvent e) {
				window.dispose();
				System.exit(0);
			}
		});
	}
}
class ImagePanel extends JPanel {
	ImageIcon icon = new ImageIcon("buffalo.gif");

	public ImagePanel() {
		setBorder(BorderFactory.createLineBorder(Color.black));
	}
	public void paintComponent(Graphics g) {
		Insets insets = getInsets();

		super.paintComponent(g);
		icon.paintIcon(this, g, insets.left, insets.top);
	}
	public Dimension getPreferredSize() {
		Insets insets = getInsets();

		return new Dimension(
			   icon.getIconWidth() + insets.left + insets.right, 
		       icon.getIconHeight() + insets.top + insets.bottom);
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?