package test21; import javax.swing.JDesktopPane; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JMenuBar; import javax.swing.JFrame; import javax.swing.KeyStroke; import java.awt.event.*; import java.awt.*; /** * Title: 内部窗体演示 * Description: 这是演示一个内部窗体。可以选择“新文档”菜单不停的生成内部窗体。 * Filename: */ public class InternalFrameDemo extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; JDesktopPane desktop; /** *方法说明:构造器,添加窗体成员 *输入参数: *返回类型: */ public InternalFrameDemo() { super("InternalFrameDemo"); //这里设置了一个比较大的窗体,给四周只留了50px的边界 int inset = 50; Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setBounds(inset, inset, screenSize.width - inset*2, screenSize.height - inset*2); //定义界面 desktop = new JDesktopPane(); //桌面面板 createFrame(); //创建第一个内部窗体 setContentPane(desktop);//将桌面添加到窗体 setJMenuBar(createMenuBar()); //设置托拽模式 desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE); } /** *方法说明:组建菜单 *输入参数: *返回类型: */ protected JMenuBar createMenuBar() { JMenuBar menuBar = new JMenuBar(); //定义一个菜单 JMenu menu = new JMenu("文件"); menu.setMnemonic(KeyEvent.VK_D); menuBar.add(menu); //定义“新文档”菜单 JMenuItem menuItem = new JMenuItem("新文档"); menuItem.setMnemonic(KeyEvent.VK_N); menuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_N, ActionEvent.ALT_MASK)); menuItem.setActionCommand("new"); menuItem.addActionListener(this); menu.add(menuItem); //定义“退出”菜单 menuItem = new JMenuItem("退出"); menuItem.setMnemonic(KeyEvent.VK_Q); menuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_Q, ActionEvent.ALT_MASK)); menuItem.setActionCommand("quit"); menuItem.addActionListener(this); menu.add(menuItem); return menuBar; } /** *方法说明:事件监听,对选择的菜单做出反映 *输入参数:ActionEvent e 事件 *返回类型: */ public void actionPerformed(ActionEvent e) { if ("new".equals(e.getActionCommand())) { //新文档 createFrame(); } else { //退出 quit(); } } /** *方法说明:调用MyInternalFrame类创建新的内部窗体, *输入参数: *返回类型: */ protected void createFrame() { MyInternalFrame frame = new MyInternalFrame(); frame.setVisible(true); desktop.add(frame); try { frame.setSelected(true); } catch (java.beans.PropertyVetoException e) {} } /** *方法说明:退出程序 *输入参数: *返回类型: */ protected void quit() { System.exit(0); } /** *方法说明:主方法 *输入参数: *返回类型: */ public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); //建立一个内部窗体 InternalFrameDemo frame = new InternalFrameDemo(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //显示窗体 frame.setVisible(true); } }
- package test21;
-
- import javax.swing.JInternalFrame;
- import javax.swing.JTextArea;
-
-
-
-
-
-
- public class MyInternalFrame extends JInternalFrame {
-
- private static final long serialVersionUID = 1L;
- static int openFrameCount = 0;
- static final int xOffset = 30, yOffset = 30;
-
- public MyInternalFrame() {
- super("文档 #" + (++openFrameCount),
- true,
- true,
- true,
- true);
-
-
- JTextArea j = new JTextArea(5,20);
- getContentPane().add(j);
-
- setSize(300,300);
-
-
- setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
- }
- }
package test21; import javax.swing.JInternalFrame; import javax.swing.JTextArea; /** * Title: 内部窗体 * Description: 生成一个内部窗体,提供InternalFrameDemo类使用 * Filename: MyInternalFrame.java */ public class MyInternalFrame extends JInternalFrame { private static final long serialVersionUID = 1L; static int openFrameCount = 0; static final int xOffset = 30, yOffset = 30; public MyInternalFrame() { super("文档 #" + (++openFrameCount), true, //可变尺寸 true, //有关闭按钮 true, //有最大化按钮 true);//最小化按钮 //给内部窗体添加一个文本域 JTextArea j = new JTextArea(5,20); getContentPane().add(j); //设置内部窗体的大小 setSize(300,300); //设置内部窗体的显示位置 setLocation(xOffset*openFrameCount, yOffset*openFrameCount); } }
- package test22;
-
- import java.awt.*;
- import javax.swing.*;
- import javax.swing.event.*;
-
-
-
-
-
-
- public class SplitPaneDemo implements ListSelectionListener {
- private String[] imageNames={"Bird.gif","Cat.gif","Dog.gif","Pig.gif"};
- private JLabel picture;
- private JList list;
- private JSplitPane splitPane;
-
-
-
-
-
- public SplitPaneDemo() {
-
-
- list = new JList(imageNames);
- list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
- list.setSelectedIndex(0);
- list.addListSelectionListener(this);
- JScrollPane listScrollPane = new JScrollPane(list);
-
-
- ImageIcon firstImage = createImageIcon("images/" +
- (String)imageNames[0]);
- if (firstImage != null) {
- picture = new JLabel(firstImage);
- picture.setPreferredSize(new Dimension(firstImage.getIconWidth(),
- firstImage.getIconHeight()));
- } else {
- picture = new JLabel((String)imageNames[0]);
- }
- JScrollPane pictureScrollPane = new JScrollPane(picture);
-
-
- splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,
- listScrollPane, pictureScrollPane);
- splitPane.setOneTouchExpandable(true);
- splitPane.setDividerLocation(150);
-
-
- Dimension minimumSize = new Dimension(100, 50);
- listScrollPane.setMinimumSize(minimumSize);
- pictureScrollPane.setMinimumSize(minimumSize);
-
-
- splitPane.setPreferredSize(new Dimension(400, 200));
- }
-
-
-
-
-
- public JSplitPane getSplitPane() {
- return splitPane;
- }
-
-
-
-
-
- public void valueChanged(ListSelectionEvent e) {
- if (e.getValueIsAdjusting())
- return;
-
- JList theList = (JList)e.getSource();
- if (theList.isSelectionEmpty()) {
- picture.setIcon(null);
- picture.setText(null);
- } else {
- int index = theList.getSelectedIndex();
- ImageIcon newImage = createImageIcon("images/" +
- (String)imageNames[index]);
- picture.setIcon(newImage);
- if (newImage != null) {
- picture.setText(null);
- picture.setPreferredSize(new Dimension(newImage.getIconWidth(),
- newImage.getIconHeight() ));
- } else {
- picture.setText("Image not found: "
- + (String)imageNames[index]);
- }
- picture.revalidate();
- }
- }
-
-
-
-
-
- protected static ImageIcon createImageIcon(String path) {
- java.net.URL imgURL = SplitPaneDemo.class.getResource(path);
- if (imgURL != null) {
- return new ImageIcon(imgURL);
- } else {
- System.err.println("Couldn't find file: " + path);
- return null;
- }
- }
-
-
-
-
-
- public static void main(String[] args) {
- JFrame.setDefaultLookAndFeelDecorated(true);
-
-
- JFrame frame = new JFrame("SplitPaneDemo");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- SplitPaneDemo splitPaneDemo = new SplitPaneDemo();
- frame.getContentPane().add(splitPaneDemo.getSplitPane());
-
-
- frame.pack();
- frame.setVisible(true);
- }
- }
package test22; import java.awt.*; import javax.swing.*; import javax.swing.event.*; /** * Title: 分割面板 * Description: 演示将面板分割成左右两部分 * Fiename:SplitPaneDemo.java */ public class SplitPaneDemo implements ListSelectionListener { private String[] imageNames={"Bird.gif","Cat.gif","Dog.gif","Pig.gif"}; private JLabel picture; private JList list; private JSplitPane splitPane; /** *方法说明:构造器,定义了所有要使用的构件 *输入参数: *返回类型: */ public SplitPaneDemo() { //创建一个图像名称的列表,设置为单选方式 list = new JList(imageNames); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setSelectedIndex(0); list.addListSelectionListener(this); JScrollPane listScrollPane = new JScrollPane(list); //获取默认的图片 ImageIcon firstImage = createImageIcon("images/" + (String)imageNames[0]); if (firstImage != null) { picture = new JLabel(firstImage); picture.setPreferredSize(new Dimension(firstImage.getIconWidth(), firstImage.getIconHeight())); } else { picture = new JLabel((String)imageNames[0]); } JScrollPane pictureScrollPane = new JScrollPane(picture); //创建一个水平分割的面板,定义了两个面板的名字。 splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true, listScrollPane, pictureScrollPane); splitPane.setOneTouchExpandable(true); splitPane.setDividerLocation(150); //定义面板的最小尺寸 Dimension minimumSize = new Dimension(100, 50); listScrollPane.setMinimumSize(minimumSize); pictureScrollPane.setMinimumSize(minimumSize); //定义初始尺寸 splitPane.setPreferredSize(new Dimension(400, 200)); } /** *方法说明:获得这个分割的面板 *输入参数: *返回类型:JSplitPane 对象 */ public JSplitPane getSplitPane() { return splitPane; } /** *方法说明:列表监听事件处理 *输入参数:ListSelectionEvent e 列表选择事件 *返回类型: */ public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) return; JList theList = (JList)e.getSource(); if (theList.isSelectionEmpty()) { picture.setIcon(null); picture.setText(null); } else { int index = theList.getSelectedIndex(); ImageIcon newImage = createImageIcon("images/" + (String)imageNames[index]); picture.setIcon(newImage); if (newImage != null) { picture.setText(null); picture.setPreferredSize(new Dimension(newImage.getIconWidth(), newImage.getIconHeight() )); } else { picture.setText("Image not found: " + (String)imageNames[index]); } picture.revalidate(); } } /** *方法说明:根据路径获取图形对象 *输入参数:String path 图片路径 *返回类型:ImageIcon 图片对象 */ protected static ImageIcon createImageIcon(String path) { java.net.URL imgURL = SplitPaneDemo.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println("Couldn't find file: " + path); return null; } } /** *方法说明:主方法 *输入参数: *返回类型: */ public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); //定义窗体 JFrame frame = new JFrame("SplitPaneDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); SplitPaneDemo splitPaneDemo = new SplitPaneDemo(); frame.getContentPane().add(splitPaneDemo.getSplitPane()); //显示窗体 frame.pack(); frame.setVisible(true); } }
- package test23;
-
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- import javax.swing.event.*;
-
-
-
-
-
- public class SliderDemo extends JPanel
- implements ActionListener,
- WindowListener,
- ChangeListener {
-
- private static final long serialVersionUID = 1L;
-
- static final int FPS_MIN = 0;
- static final int FPS_MAX = 30;
- static final int FPS_INIT = 15;
- int frameNumber = 0;
- int NUM_FRAMES = 14;
- ImageIcon[] images = new ImageIcon[NUM_FRAMES];
- int delay;
- Timer timer;
- boolean frozen = false;
-
-
- JLabel picture;
-
- public SliderDemo() {
- setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
-
- delay = 1000 / FPS_INIT;
-
-
- JLabel sliderLabel = new JLabel("调整滑动杆,改变播放速度!", JLabel.CENTER);
- sliderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
-
-
- JSlider framesPerSecond = new JSlider(JSlider.HORIZONTAL,
- FPS_MIN, FPS_MAX, FPS_INIT);
- framesPerSecond.addChangeListener(this);
-
-
- framesPerSecond.setMajorTickSpacing(10);
- framesPerSecond.setMinorTickSpacing(1);
- framesPerSecond.setPaintTicks(true);
- framesPerSecond.setPaintLabels(true);
- framesPerSecond.setBorder(
- BorderFactory.createEmptyBorder(0,0,10,0));
-
-
- picture = new JLabel();
- picture.setHorizontalAlignment(JLabel.CENTER);
- picture.setAlignmentX(Component.CENTER_ALIGNMENT);
- picture.setBorder(BorderFactory.createCompoundBorder(
- BorderFactory.createLoweredBevelBorder(),
- BorderFactory.createEmptyBorder(10,10,10,10)));
- updatePicture(0);
-
-
- add(sliderLabel);
- add(framesPerSecond);
- add(picture);
- setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
-
-
- timer = new Timer(delay, this);
- timer.setInitialDelay(delay * 7);
- timer.setCoalesce(true);
- }
-
-
-
-
-
- void addWindowListener(Window w) {
- w.addWindowListener(this);
- }
- public void windowIconified(WindowEvent e) {
- stopAnimation();
- }
- public void windowDeiconified(WindowEvent e) {
- startAnimation();
- }
- public void windowOpened(WindowEvent e) {}
- public void windowClosing(WindowEvent e) {}
- public void windowClosed(WindowEvent e) {}
- public void windowActivated(WindowEvent e) {}
- public void windowDeactivated(WindowEvent e) {}
-
-
-
-
-
- public void stateChanged(ChangeEvent e) {
- JSlider source = (JSlider)e.getSource();
- if (!source.getValueIsAdjusting()) {
- int fps = (int)source.getValue();
- if (fps == 0) {
- if (!frozen) stopAnimation();
- } else {
- delay = 1000 / fps;
- timer.setDelay(delay);
- timer.setInitialDelay(delay * 10);
- if (frozen) startAnimation();
- }
- }
- }
-
-
-
-
-
- public void startAnimation() {
- timer.start();
- frozen = false;
- }
-
-
-
-
-
- public void stopAnimation() {
- timer.stop();
- frozen = true;
- }
-
-
-
-
-
- public void actionPerformed(ActionEvent e) {
-
- if (frameNumber == (NUM_FRAMES - 1)) {
- frameNumber = 0;
- } else {
- frameNumber++;
- }
-
- updatePicture(frameNumber);
-
- if ( frameNumber==(NUM_FRAMES - 1)
- || frameNumber==(NUM_FRAMES/2 - 1) ) {
- timer.restart();
- }
- }
-
-
-
-
-
- protected void updatePicture(int frameNum) {
- if (images[frameNumber] == null) {
- images[frameNumber] = createImageIcon("images/doggy/T"
- + frameNumber
- + ".gif");
- }
-
-
- if (images[frameNumber] != null) {
- picture.setIcon(images[frameNumber]);
- } else {
- picture.setText("image #" + frameNumber + " not found");
- }
- }
-
-
-
-
-
- protected static ImageIcon createImageIcon(String path) {
- java.net.URL imgURL = SliderDemo.class.getResource(path);
- if (imgURL != null) {
- return new ImageIcon(imgURL);
- } else {
- System.err.println("Couldn't find file: " + path);
- return null;
- }
- }
-
-
-
-
-
- public static void main(String[] args) {
- JFrame.setDefaultLookAndFeelDecorated(true);
-
-
- JFrame frame = new JFrame("SliderDemo");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
-
-
- SliderDemo animator = new SliderDemo();
- animator.setOpaque(true);
- frame.setContentPane(animator);
-
-
- frame.pack();
- frame.setVisible(true);
- animator.startAnimation();
- }
- }
package test23; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; /** * Title: 滑动杆演示 * Description: 使用滑动杆控制定时器,来控制图片的播放速度 * Filename: SliderDemo.java */ public class SliderDemo extends JPanel implements ActionListener, WindowListener, ChangeListener { private static final long serialVersionUID = 1L; //设置图片的参数 static final int FPS_MIN = 0; //设置最小值 static final int FPS_MAX = 30; //设置最大值 static final int FPS_INIT = 15; //初始数值 int frameNumber = 0; int NUM_FRAMES = 14; ImageIcon[] images = new ImageIcon[NUM_FRAMES]; int delay; Timer timer; boolean frozen = false; //这个标签用来显示这只小狗 JLabel picture; public SliderDemo() { setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); delay = 1000 / FPS_INIT; //信息提示标签 JLabel sliderLabel = new JLabel("调整滑动杆,改变播放速度!", JLabel.CENTER); sliderLabel.setAlignmentX(Component.CENTER_ALIGNMENT); //创建一个滑动杆,定义了最小值和最大值以及初始值 JSlider framesPerSecond = new JSlider(JSlider.HORIZONTAL, FPS_MIN, FPS_MAX, FPS_INIT); framesPerSecond.addChangeListener(this); //定义滑动杆参数 framesPerSecond.setMajorTickSpacing(10);//每10刻度标注一次 framesPerSecond.setMinorTickSpacing(1);//最小刻度为1 framesPerSecond.setPaintTicks(true);//绘制滑动杆上的刻度 framesPerSecond.setPaintLabels(true);//在滑动过程中绘制滑动块 framesPerSecond.setBorder( BorderFactory.createEmptyBorder(0,0,10,0)); //定义一个用来显示图片的标签 picture = new JLabel(); picture.setHorizontalAlignment(JLabel.CENTER); picture.setAlignmentX(Component.CENTER_ALIGNMENT); picture.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLoweredBevelBorder(), BorderFactory.createEmptyBorder(10,10,10,10))); updatePicture(0); //显示第一张图 //将成员添加到面板上 add(sliderLabel); add(framesPerSecond); add(picture); setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); //设置一个定时器来触发这个事件 timer = new Timer(delay, this); timer.setInitialDelay(delay * 7); //在每轮循环停顿时间 timer.setCoalesce(true);//设置重复循环 } /** *方法说明:添加一个窗体监听 *输入参数: *返回类型: */ void addWindowListener(Window w) { w.addWindowListener(this); } public void windowIconified(WindowEvent e) { stopAnimation(); } public void windowDeiconified(WindowEvent e) { startAnimation(); } public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} /** *方法说明:对滑动杆进行监听 *输入参数:ChangeEvent e 滑动杆变动事件 *返回类型: */ public void stateChanged(ChangeEvent e) { JSlider source = (JSlider)e.getSource(); if (!source.getValueIsAdjusting()) { int fps = (int)source.getValue();//获得滑动杆的值 if (fps == 0) { if (!frozen) stopAnimation(); } else { delay = 1000 / fps; timer.setDelay(delay); timer.setInitialDelay(delay * 10); if (frozen) startAnimation(); } } } /** *方法说明:开始动画 *输入参数: *返回类型: */ public void startAnimation() { timer.start(); frozen = false; } /** *方法说明:停止动画 *输入参数: *返回类型: */ public void stopAnimation() { timer.stop(); frozen = true; } /** *方法说明:事件监听 *输入参数: *返回类型: */ public void actionPerformed(ActionEvent e) { //改变图片帧 if (frameNumber == (NUM_FRAMES - 1)) { frameNumber = 0; } else { frameNumber++; } updatePicture(frameNumber); //显示下张图 if ( frameNumber==(NUM_FRAMES - 1) || frameNumber==(NUM_FRAMES/2 - 1) ) { timer.restart(); } } /** *方法说明:绘制当前帧 *输入参数:int frameNum 图片帧数数 *返回类型: */ protected void updatePicture(int frameNum) { if (images[frameNumber] == null) { images[frameNumber] = createImageIcon("images/doggy/T" + frameNumber + ".gif"); } //绘制图片 if (images[frameNumber] != null) { picture.setIcon(images[frameNumber]); } else { //如果没有发现图片 picture.setText("image #" + frameNumber + " not found"); } } /** *方法说明:获取图片 *输入参数:String path 图片路径 *返回类型:ImageIcon 图片对象 */ protected static ImageIcon createImageIcon(String path) { java.net.URL imgURL = SliderDemo.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println("Couldn't find file: " + path); return null; } } /** *方法说明:主方法 *输入参数: *返回类型: */ public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); //定义窗体 JFrame frame = new JFrame("SliderDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //实例化本类 SliderDemo animator = new SliderDemo(); animator.setOpaque(true); frame.setContentPane(animator); //显示窗体 frame.pack(); frame.setVisible(true); animator.startAnimation(); } }
- package test24;
-
- import java.awt.*;
- import javax.swing.*;
- import javax.swing.event.*;
-
-
-
-
-
-
-
- public class ColorChooserDemo extends JPanel
- implements ChangeListener {
-
-
- private static final long serialVersionUID = 1L;
- protected JColorChooser tcc;
- protected JLabel banner;
-
- public ColorChooserDemo() {
- super(new BorderLayout());
-
-
- banner = new JLabel("欢迎使用颜色选择器!",
- JLabel.CENTER);
- banner.setForeground(Color.yellow);
- banner.setBackground(Color.blue);
- banner.setOpaque(true);
- banner.setFont(new Font("SansSerif", Font.BOLD, 24));
- banner.setPreferredSize(new Dimension(100, 65));
-
- JPanel bannerPanel = new JPanel(new BorderLayout());
- bannerPanel.add(banner, BorderLayout.CENTER);
- bannerPanel.setBorder(BorderFactory.createTitledBorder("广告"));
-
-
- tcc = new JColorChooser(banner.getForeground());
- tcc.getSelectionModel().addChangeListener(this);
- tcc.setBorder(BorderFactory.createTitledBorder("选择颜色"));
-
- add(bannerPanel, BorderLayout.CENTER);
- add(tcc, BorderLayout.PAGE_END);
- }
-
-
-
-
-
- public void stateChanged(ChangeEvent e) {
- Color newColor = tcc.getColor();
- banner.setForeground(newColor);
- }
-
-
-
-
-
- public static void main(String[] args) {
- JFrame.setDefaultLookAndFeelDecorated(true);
-
-
- JFrame frame = new JFrame("ColorChooserDemo");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
-
-
- JComponent newContentPane = new ColorChooserDemo();
- newContentPane.setOpaque(true);
- frame.setContentPane(newContentPane);
-
-
- frame.pack();
- frame.setVisible(true);
- }
- }
package test24; import java.awt.*; import javax.swing.*; import javax.swing.event.*; /** * Title: 颜色选择器 * Description: 演示一个颜色选择器,可以从样本中选择,可以使用HSB模式和RGB模式 * Filename: ColorChooserDemo.java */ public class ColorChooserDemo extends JPanel implements ChangeListener { private static final long serialVersionUID = 1L; protected JColorChooser tcc; protected JLabel banner; public ColorChooserDemo() { super(new BorderLayout()); //设置一个标签,做广告的。也用来显示用户选择的颜色。 banner = new JLabel("欢迎使用颜色选择器!", JLabel.CENTER); banner.setForeground(Color.yellow); banner.setBackground(Color.blue); banner.setOpaque(true); banner.setFont(new Font("SansSerif", Font.BOLD, 24)); banner.setPreferredSize(new Dimension(100, 65)); JPanel bannerPanel = new JPanel(new BorderLayout()); bannerPanel.add(banner, BorderLayout.CENTER); bannerPanel.setBorder(BorderFactory.createTitledBorder("广告")); //设置选择颜色选择器 tcc = new JColorChooser(banner.getForeground());//设置初始颜色 tcc.getSelectionModel().addChangeListener(this);//给所有模式添加监听 tcc.setBorder(BorderFactory.createTitledBorder("选择颜色")); add(bannerPanel, BorderLayout.CENTER); add(tcc, BorderLayout.PAGE_END); } /** *方法说明:事件监听。用户选择颜色触发 *输入参数:ChangeEvent e 用户选择事件 *返回类型: */ public void stateChanged(ChangeEvent e) { Color newColor = tcc.getColor();//获取用户选择的颜色 banner.setForeground(newColor); } /** *方法说明:主方法 *输入参数: *返回类型: */ public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); //创建窗体 JFrame frame = new JFrame("ColorChooserDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //创建面板容器 JComponent newContentPane = new ColorChooserDemo(); newContentPane.setOpaque(true); frame.setContentPane(newContentPane); //显示窗体 frame.pack(); frame.setVisible(true); } }
- package test25;
-
- import javax.swing.JTable;
- import javax.swing.table.AbstractTableModel;
-
- import javax.swing.JScrollPane;
- import javax.swing.JFrame;
- import java.awt.*;
- import java.awt.event.*;
-
-
-
-
-
- public class MyTableDemo extends JFrame {
-
-
- private static final long serialVersionUID = 1L;
- public MyTableDemo() {
- super("MyTableDemo");
-
- MyTableModel myModel = new MyTableModel();
- JTable table = new JTable(myModel);
- table.setPreferredScrollableViewportSize(new Dimension(500, 70));
-
-
- JScrollPane scrollPane = new JScrollPane(table);
-
-
- getContentPane().add(scrollPane, BorderLayout.CENTER);
-
- addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- System.exit(0);
- }
- });
- }
-
-
-
-
-
- class MyTableModel extends AbstractTableModel {
-
- private static final long serialVersionUID = 1L;
-
- final String[] columnNames = {"姓名",
- "性别",
- "学历",
- "年龄",
- "是否已婚"};
-
- final Object[][] data = {
- {"张三", "男",
- "大本", new Integer(25), new Boolean(false)},
- {"李四", "男",
- "大本", new Integer(33), new Boolean(true)},
- {"王五", "男",
- "高中", new Integer(20), new Boolean(false)},
- {"赵倩", "女",
- "大专", new Integer(26), new Boolean(true)},
- {"周大", "男",
- "大本", new Integer(24), new Boolean(false)}
- };
-
-
-
-
-
- public int getColumnCount() {
- return columnNames.length;
- }
-
-
-
-
-
- public int getRowCount() {
- return data.length;
- }
-
-
-
-
-
- public String getColumnName(int col) {
- return columnNames[col];
- }
-
-
-
-
-
-
- public Object getValueAt(int row, int col) {
- return data[row][col];
- }
-
-
-
-
-
- @SuppressWarnings("unchecked")
- public Class getColumnClass(int c) {
- return getValueAt(0, c).getClass();
- }
-
-
-
-
-
- public boolean isCellEditable(int row, int col) {
- if (col < 2) {
- return false;
- } else {
- return true;
- }
- }
-
-
-
-
-
- public void setValueAt(Object value, int row, int col) {
- System.out.println("修改数据位置: " + row + "," + col
- + " 新数据为: " + value);
-
- data[row][col] = value;
- fireTableCellUpdated(row, col);
-
- System.out.println("表格新数据:");
- printDebugData();
-
- }
-
-
-
-
-
- private void printDebugData() {
- int numRows = getRowCount();
- int numCols = getColumnCount();
-
- for (int i=0; i < numRows; i++) {
- System.out.print(" 行 " + i + ":");
- for (int j=0; j < numCols; j++) {
- System.out.print(" " + data[i][j]);
- }
- System.out.println();
- }
- System.out.println("--------------------------");
- }
- }
-
-
-
-
-
- public static void main(String[] args) {
- JFrame.setDefaultLookAndFeelDecorated(true);
- MyTableDemo frame = new MyTableDemo();
- frame.pack();
- frame.setVisible(true);
- }
- }
package test25; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import javax.swing.JScrollPane; import javax.swing.JFrame; import java.awt.*; import java.awt.event.*; /** * Title: 自己定义的表格 * Description: 继承AbstractTableModel类,实现自己的表格 * Flename: MyTableDemo.java */ public class MyTableDemo extends JFrame { private static final long serialVersionUID = 1L; public MyTableDemo() { super("MyTableDemo"); //声明自己的表格,并添加到JTable中 MyTableModel myModel = new MyTableModel(); JTable table = new JTable(myModel); table.setPreferredScrollableViewportSize(new Dimension(500, 70)); //将表格添加到可滚动的面板 JScrollPane scrollPane = new JScrollPane(table); //将滚动面板添加到窗体 getContentPane().add(scrollPane, BorderLayout.CENTER); //添加监听 addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } /** * Title: 定义自己的表格模式 * Description: 通过继承AbstractTableModel类来定义自己的表格模式, * 这里使得第三个以后才可以编辑 */ class MyTableModel extends AbstractTableModel { private static final long serialVersionUID = 1L; //定义表头 final String[] columnNames = {"姓名", "性别", "学历", "年龄", "是否已婚"}; //初始化表数据 final Object[][] data = { {"张三", "男", "大本", new Integer(25), new Boolean(false)}, {"李四", "男", "大本", new Integer(33), new Boolean(true)}, {"王五", "男", "高中", new Integer(20), new Boolean(false)}, {"赵倩", "女", "大专", new Integer(26), new Boolean(true)}, {"周大", "男", "大本", new Integer(24), new Boolean(false)} }; /** *方法说明:继承AbstractTableModel必须实现的方法 *输入参数: *返回类型:int 列数 */ public int getColumnCount() { return columnNames.length; } /** *方法说明:继承AbstractTableModel必须实现的方法 *输入参数: *返回类型:int 列数 */ public int getRowCount() { return data.length; } /** *方法说明:继承AbstractTableModel必须实现的方法 *输入参数: *返回类型:String 列名 */ public String getColumnName(int col) { return columnNames[col]; } /** *方法说明:继承AbstractTableModel必须实现的方法,获取表格中的数据 *输入参数:int row 行数 *输入参数:int col 列数 *返回类型:Object 数据对象 */ public Object getValueAt(int row, int col) { return data[row][col]; } /** *方法说明:实现这个方法使得最后一列不是显示true和false。而是使用检查盒 *输入参数: *返回类型: */ @SuppressWarnings("unchecked") public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } /** *方法说明:这个方法不一定需要实现。这里是为了定义可编辑的列 *输入参数: *返回类型:boolean 是否可编辑 */ public boolean isCellEditable(int row, int col) { if (col < 2) { return false; } else { return true; } } /** *方法说明:实现此方法,获得编辑数据。 *输入参数: *返回类型: */ public void setValueAt(Object value, int row, int col) { System.out.println("修改数据位置: " + row + "," + col + " 新数据为: " + value); data[row][col] = value; fireTableCellUpdated(row, col); System.out.println("表格新数据:"); printDebugData(); } /** *方法说明:输出表格中的新数据 *输入参数: *返回类型: */ private void printDebugData() { int numRows = getRowCount(); int numCols = getColumnCount(); for (int i=0; i < numRows; i++) { System.out.print(" 行 " + i + ":"); for (int j=0; j < numCols; j++) { System.out.print(" " + data[i][j]); } System.out.println(); } System.out.println("--------------------------"); } } /** *方法说明:主方法 *输入参数: *返回类型: */ public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); MyTableDemo frame = new MyTableDemo(); frame.pack(); frame.setVisible(true); } }
- package test26;
-
- import java.awt.*;
- import javax.swing.*;
-
-
-
-
-
- public class Sample extends JFrame {
-
- private static final long serialVersionUID = 1L;
-
-
-
-
-
- public static void main(String[] args){
- Sample sl = new Sample();
- sl.update();
- }
-
-
-
-
-
- @SuppressWarnings("deprecation")
- Sample(){
- super("Sample");
- setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
- setSize(310,160);
- show();
- }
-
-
-
-
-
- public void update(){
- repaint();
- }
-
-
-
-
-
- public void paint(Graphics g) {
- int [] x={10,30,80,50,10};
- int [] y={90,140,120,100,90};
- g.setColor(Color.cyan);
-
- for (int i=0; i<=300; i+=10) {
- g.drawLine(i,0,i,150);
- }
-
- for (int i=0; i<=150; i+=10) {
- g.drawLine(0,i,300,i);
- }
- g.setColor(Color.black);
-
- g.drawRect(10,30,80,50);
-
- g.drawRoundRect(110,30,80,50,20,10);
-
- g.drawPolygon(x,y,5);
-
- g.drawOval(110,90,80,50);
-
- g.drawArc(210,30,80,50,0,90);
-
- g.fillArc(210,90,80,50,0,90);
- }
- }
package test26; import java.awt.*; import javax.swing.*; /** * Title: 基本图形的绘制 * Description: 本实例演示绘制四边型、圆角矩形、椭圆等基本的图形。 * Filename: Sample.java */ public class Sample extends JFrame { private static final long serialVersionUID = 1L; /** *方法说明:主方法 *输入参数: *返回类型: */ public static void main(String[] args){ Sample sl = new Sample(); sl.update(); } /** *方法说明:构造器,显示窗体 *输入参数: *返回类型: */ @SuppressWarnings("deprecation") Sample(){ super("Sample"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setSize(310,160); show(); } /** *方法说明:更新画面 *输入参数: *返回类型: */ public void update(){ repaint(); } /** *方法说明:绘制画面 *输入参数: *返回类型: */ public void paint(Graphics g) { int [] x={10,30,80,50,10}; int [] y={90,140,120,100,90}; g.setColor(Color.cyan); //绘制竖格线 for (int i=0; i<=300; i+=10) { g.drawLine(i,0,i,150); } //绘制横格线 for (int i=0; i<=150; i+=10) { g.drawLine(0,i,300,i); } g.setColor(Color.black); //有角矩形,起始点(10,30),宽80,高50 g.drawRect(10,30,80,50); //圆角矩形,起始点(110,30),宽80,高50,角(a=20,b=10) g.drawRoundRect(110,30,80,50,20,10); //多角边 g.drawPolygon(x,y,5); //椭圆,圆心(110,90)、a=80,b=50 g.drawOval(110,90,80,50); //一条弧,圆心(219,30)、a=80,b=50 角度在0-90之间 g.drawArc(210,30,80,50,0,90); //扇面,圆心(219,90)、a=80,b=50 角度在0-90之间 g.fillArc(210,90,80,50,0,90); } }
- package test27;
-
- import java.awt.*;
- import javax.swing.*;
-
- public class Func extends JFrame{
-
- private static final long serialVersionUID = 1L;
-
-
-
-
-
- public static void main(String[] args){
- Func db = new Func();
- db.update();
- }
-
-
-
-
-
- @SuppressWarnings("deprecation")
- Func(){
- super("Function");
- setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
- setSize(310,310);
- show();
- }
-
-
-
-
-
- public void update(){
- repaint();
- }
-
-
-
-
-
- double f(double x) {
- return (Math.sin(2*x)+Math.cos(3*x));
- }
-
-
-
-
-
- public void paint(Graphics g) {
- double x0,x1,y0,y1,xd,yd;
- double max=5.0;
- int w,h,hw,hh;
-
- w=getSize().width;
- h=getSize().height;
- hw=w/2; hh=h/2;
-
- g.drawString("Sin[2x]+Cos[3x]",10,40);
- g.setColor(Color.red);
- g.drawString("0",hw+5,hh+12);
- g.drawString(""+max,hw-20,40);
- g.drawString(""+max,w-20,hh+12);
-
- g.drawLine(0,hh,w,hh);
-
- g.drawLine(hw,0,hw,h);
- xd=2*max/w;
- yd=hh/max;
- g.setColor(Color.blue);
-
- for (int x=0 ; x<w-1; x++) {
- x0=-max+x*xd; y0=f(x0)*yd;
- x1=x0+xd; y1=f(x1)*yd;
- g.drawLine(x,(int)(hh-y0),x+1,(int)(hh-y1));
- }
- }
- }
package test27; import java.awt.*; import javax.swing.*; public class Func extends JFrame{ private static final long serialVersionUID = 1L; /** *方法说明:主方法 *输入参数: *返回类型: */ public static void main(String[] args){ Func db = new Func(); db.update(); } /** *方法说明:构造器,显示窗体 *输入参数: *返回类型: */ @SuppressWarnings("deprecation") Func(){ super("Function"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setSize(310,310); show(); } /** *方法说明:更新画面 *输入参数: *返回类型: */ public void update(){ repaint(); } /** *方法说明:转换坐标点 *输入参数: *返回类型: */ double f(double x) { return (Math.sin(2*x)+Math.cos(3*x)); } /** *方法说明:绘制坐标图 *输入参数: *返回类型: */ public void paint(Graphics g) { double x0,x1,y0,y1,xd,yd; double max=5.0; int w,h,hw,hh; //获取屏幕的尺寸 w=getSize().width; h=getSize().height; hw=w/2; hh=h/2; //在屏幕上输出字符 g.drawString("Sin[2x]+Cos[3x]",10,40); g.setColor(Color.red); g.drawString("0",hw+5,hh+12); g.drawString(""+max,hw-20,40); g.drawString(""+max,w-20,hh+12); //绘制X轴坐标 g.drawLine(0,hh,w,hh); //绘制Y轴坐标 g.drawLine(hw,0,hw,h); xd=2*max/w;//计算X增量 yd=hh/max; //计算y增量 g.setColor(Color.blue); //使用增量绘制一小段线,最终组成曲线图形。 for (int x=0 ; x<w-1; x++) { x0=-max+x*xd; y0=f(x0)*yd; x1=x0+xd; y1=f(x1)*yd; g.drawLine(x,(int)(hh-y0),x+1,(int)(hh-y1)); } } } //end
- package test28;
-
- import javax.swing.*;
- import java.awt.*;
-
-
-
-
-
- class ImgDemo extends JFrame {
-
- private static final long serialVersionUID = 1L;
- Image image;
-
-
-
-
-
- @SuppressWarnings("deprecation")
- ImgDemo(String filename) {
- setTitle("drawImage Example");
- try {
- image = getToolkit().getImage(filename);
- setIconImage(image);
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- setSize(600, 250);
- setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
- show();
- }
-
-
-
-
-
- public void paint(Graphics g) {
- Insets insets = getInsets();
- int x = insets.left, y = insets.top;
-
- int w = image.getWidth(this);
- int h = image.getHeight(this);
-
- g.drawImage(image, x, y, this);
-
- g.drawRect(x, y, w/4+1, h/4+1);
- g.drawImage(image, x+1, y+1, w/4, h/4, this);
-
- g.drawImage(image, x+w, y, x+2*w, y+h, w, 0, 0, h, this);
- }
-
-
-
-
-
- public static void main(String[] args) {
- if (args.length == 1) {
- new ImgDemo(args[0]);
- } else {
- System.err.println("usage: java ImgDemo images-name ");
- }
- }
- }
package test28; import javax.swing.*; import java.awt.*; /** * Title: 图片的处理, * Description: 将图片放大和翻转显示 * Filename: ImgDemo.java */ class ImgDemo extends JFrame { private static final long serialVersionUID = 1L; Image image; /** *方法说明:构造器,显示窗体 *输入参数: *返回类型: */ @SuppressWarnings("deprecation") ImgDemo(String filename) { setTitle("drawImage Example"); try { image = getToolkit().getImage(filename); setIconImage(image); } catch (Exception e) { e.printStackTrace(); } setSize(600, 250); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); show(); } /** *方法说明:绘制图像 *输入参数: *返回类型: */ public void paint(Graphics g) { Insets insets = getInsets(); int x = insets.left, y = insets.top; //获取图片尺寸 int w = image.getWidth(this); int h = image.getHeight(this); //正常显示图片 g.drawImage(image, x, y, this); //缩小图形 g.drawRect(x, y, w/4+1, h/4+1);//画一个框 g.drawImage(image, x+1, y+1, w/4, h/4, this); //水平翻转 g.drawImage(image, x+w, y, x+2*w, y+h, w, 0, 0, h, this); } /** *方法说明:主方法,接受参数 *输入参数: *返回类型: */ public static void main(String[] args) { if (args.length == 1) { new ImgDemo(args[0]); } else { System.err.println("usage: java ImgDemo images-name "); } } }
- package test29;
-
- import java.awt.*;
- import java.awt.event.*;
- import java.util.*;
- import javax.swing.*;
- import javax.swing.Timer;
-
-
-
-
-
- public class Clock extends JFrame implements ActionListener{
-
- private static final long serialVersionUID = 1L;
- Timer timer;
- int x,y,old_X,old_Y, r,x0,y0,w,h,ang;
- int sdo,mdo,hdo,old_M,old_H;
- TimeZone tz =TimeZone.getTimeZone("JST");
- final double RAD=Math.PI/180.0;
-
- public static void main(String[] args){
- @SuppressWarnings("unused")
- Clock cl = new Clock();
- }
-
-
-
-
-
- public void actionPerformed(ActionEvent e) {
- timer.restart();
- }
-
-
-
-
-
- @SuppressWarnings("deprecation")
- Clock(){
- super("Clock");
- setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
- setBackground(new Color(0,0,192));
- setSize(300,300);
- show();
- int delay = 1000;
-
- ActionListener taskPerformer = new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- repaint();
- }
- };
- new Timer(delay, taskPerformer).start();
- }
-
-
-
-
-
- public void paint( Graphics g ) {
- Insets insets = getInsets();
- int L0 = (insets.left)/2, T0 = (insets.top)/2;
- int hh,mm,ss;
- String st;
- h=getSize().height;
-
- g.setColor(Color.white);
- g.drawOval(L0+30,T0+30,h-60,h-60);
- g.drawOval(L0+32,T0+32,h-64,h-64);
- r=h/2-30;
- x0=30+r-5+L0;
- y0=30+r-5-T0;
- ang=60;
- for (int i=1; i<=12; i++) {
- x=(int)((r+10)*Math.cos(RAD*ang)+x0);
- y=(int)((r+10)*Math.sin(RAD*ang)+y0);
- g.drawString(""+i,x,h-y);
- ang-=30;
- }
- x0=30+r+L0; y0=30+r+T0;
-
- Calendar now=Calendar.getInstance();
- hh=now.get(Calendar.HOUR_OF_DAY);
- mm=now.get(Calendar.MINUTE);
- ss=now.get(Calendar.SECOND);
- g.setColor(Color.pink);
- g.fillRect(L0,T0,60,28);
- g.setColor(Color.blue);
- if (hh < 10) st="0"+hh; else st=""+hh;
- if (mm < 10) st=st+":0"+mm; else st=st+":"+mm;
- if (ss < 10) st=st+":0"+ss; else st=st+":"+ss;
- g.drawString(st,L0,T0+25);
-
- sdo=90-ss*6;
- mdo=90-mm*6;
- hdo=90-hh*30-mm/2;
-
- if (old_X > 0) {
- g.setColor(getBackground());
- g.drawLine(x0,y0,old_X,(h-old_Y));
- } else {
- old_M=mdo;
- old_H=hdo;
- }
-
- g.setColor(Color.yellow);
- x=(int)((r-8)*Math.cos(RAD*sdo)+x0);
- y=(int)((r-8)*Math.sin(RAD*sdo)+y0)-2*T0;
- g.drawLine(x0,y0,x,(h-y));
-
- old_X=x;
- old_Y=y;
-
- if (mdo != old_M) {
- line(g,old_M,(int)(r*0.7),getBackground());
- old_M=mdo;
- }
- if (hdo != old_H) {
- line(g,old_H,(int)(r*0.5),getBackground());
- old_H=hdo;
- }
-
- line(g,mdo,(int)(r*0.7),Color.green);
-
- line(g,hdo,(int)(r*0.5),Color.red);
- }
-
-
-
-
-
- public void line(Graphics g, int t, int n, Color c) {
- int [] xp = new int[4];
- int [] yp = new int[4];
- xp[0]=x0;
- yp[0]=y0;
- xp[1]= (int)((n-10)*Math.cos(RAD*(t-4))+x0);
- yp[1]=h-(int)((n-10)*Math.sin(RAD*(t-4))+y0);
- xp[2]= (int)( n *Math.cos(RAD* t )+x0);
- yp[2]=h-(int)( n *Math.sin(RAD* t )+y0);
- xp[3]= (int)((n-10)*Math.cos(RAD*(t+4))+x0);
- yp[3]=h-(int)((n-10)*Math.sin(RAD*(t+4))+y0);
- g.setColor(c);
- g.fillPolygon(xp,yp,4);
- }
- }
package test29; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.Timer; /** * Title: 时钟 * Description: 本实例演示使用图形绘制一个图形时钟 * Filename: Clock.java */ public class Clock extends JFrame implements ActionListener{ private static final long serialVersionUID = 1L; Timer timer; int x,y,old_X,old_Y, r,x0,y0,w,h,ang; int sdo,mdo,hdo,old_M,old_H; TimeZone tz =TimeZone.getTimeZone("JST"); final double RAD=Math.PI/180.0; public static void main(String[] args){ @SuppressWarnings("unused") Clock cl = new Clock(); } /** *方法说明:实现ActionListener类必须过载的方法 *输入参数: *返回类型: */ public void actionPerformed(ActionEvent e) { timer.restart(); } /** *方法说明:构造器,显示窗体,并添加了一个秒表 *输入参数: *返回类型: */ @SuppressWarnings("deprecation") Clock(){ super("Clock"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBackground(new Color(0,0,192)); setSize(300,300); show(); int delay = 1000; //窗体添加事件监听,监听秒表的触发 ActionListener taskPerformer = new ActionListener() { public void actionPerformed(ActionEvent evt) { repaint(); } }; new Timer(delay, taskPerformer).start(); } /** *方法说明:绘制图形 *输入参数: *返回类型: */ public void paint( Graphics g ) { Insets insets = getInsets(); int L0 = (insets.left)/2, T0 = (insets.top)/2; int hh,mm,ss; String st; h=getSize().height; //绘制圆形 g.setColor(Color.white); g.drawOval(L0+30,T0+30,h-60,h-60); g.drawOval(L0+32,T0+32,h-64,h-64); r=h/2-30; x0=30+r-5+L0; y0=30+r-5-T0; ang=60; for (int i=1; i<=12; i++) { x=(int)((r+10)*Math.cos(RAD*ang)+x0); y=(int)((r+10)*Math.sin(RAD*ang)+y0); g.drawString(""+i,x,h-y); ang-=30; } x0=30+r+L0; y0=30+r+T0; //获取时间 Calendar now=Calendar.getInstance(); hh=now.get(Calendar.HOUR_OF_DAY);//小时 mm=now.get(Calendar.MINUTE);//分钟 ss=now.get(Calendar.SECOND);// 秒 g.setColor(Color.pink); g.fillRect(L0,T0,60,28);//填充的矩形 g.setColor(Color.blue); if (hh < 10) st="0"+hh; else st=""+hh; if (mm < 10) st=st+":0"+mm; else st=st+":"+mm; if (ss < 10) st=st+":0"+ss; else st=st+":"+ss; g.drawString(st,L0,T0+25); //计算时间和图形的关系 sdo=90-ss*6; mdo=90-mm*6; hdo=90-hh*30-mm/2; //擦除秒针 if (old_X > 0) { g.setColor(getBackground()); g.drawLine(x0,y0,old_X,(h-old_Y)); } else { old_M=mdo; old_H=hdo; } //绘制秒针 g.setColor(Color.yellow); x=(int)((r-8)*Math.cos(RAD*sdo)+x0); y=(int)((r-8)*Math.sin(RAD*sdo)+y0)-2*T0; g.drawLine(x0,y0,x,(h-y)); old_X=x; old_Y=y; //擦除分针和时针 if (mdo != old_M) { line(g,old_M,(int)(r*0.7),getBackground()); old_M=mdo; } if (hdo != old_H) { line(g,old_H,(int)(r*0.5),getBackground()); old_H=hdo; } //绘制分针 line(g,mdo,(int)(r*0.7),Color.green); //绘制时针 line(g,hdo,(int)(r*0.5),Color.red); } // end paint /** *方法说明:绘制线,用于绘制时针和分针 *输入参数: *返回类型: */ public void line(Graphics g, int t, int n, Color c) { int [] xp = new int[4]; int [] yp = new int[4]; xp[0]=x0; yp[0]=y0; xp[1]= (int)((n-10)*Math.cos(RAD*(t-4))+x0); yp[1]=h-(int)((n-10)*Math.sin(RAD*(t-4))+y0); xp[2]= (int)( n *Math.cos(RAD* t )+x0); yp[2]=h-(int)( n *Math.sin(RAD* t )+y0); xp[3]= (int)((n-10)*Math.cos(RAD*(t+4))+x0); yp[3]=h-(int)((n-10)*Math.sin(RAD*(t+4))+y0); g.setColor(c); g.fillPolygon(xp,yp,4); } }
- package test30;
-
-
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
-
-
-
-
-
- public class Gr3d1m extends JFrame
- implements MouseListener,MouseMotionListener {
- int doX,doY;
- int angX=30,angY=30;
- Cube data = new Cube();
- Color [] Col={Color.gray,Color.cyan,Color.green,
- Color.red,Color.white,Color.orange,
- Color.magenta,Color.pink};
-
-
-
-
-
- public static void main(String[] args){
- Gr3d1m G3 = new Gr3d1m();
- }
-
-
-
-
-
- public Gr3d1m() {
- setTitle("3D cube Frame");
- setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
- addMouseListener(this);
- addMouseMotionListener(this);
- setBackground(new Color(128,128,255));
- setSize(350,350);
- show();
- }
-
-
-
-
-
- public void mousePressed(MouseEvent e) {
- doX=e.getX();
- doY=e.getY();
- }
-
-
-
-
-
- public void mouseDragged(MouseEvent e) {
- angX=angX+e.getY()-doY;
- angY=angY+e.getX()-doX;
- doX=e.getX(); doY=e.getY();
- repaint();
- }
-
- public void mouseReleased(MouseEvent e) { }
- public void mouseClicked(MouseEvent e) { }
- public void mouseEntered(MouseEvent e) { }
- public void mouseExited(MouseEvent e) { }
- public void mouseMoved(MouseEvent e) { }
-
-
-
-
-
- public void paint( Graphics g ) {
- delDeaw(g);
- for (int i=0; i<data.x.length; i++) {
- drawPG(g, data.x[i], data.y[i], data.z[i],
- 150,150,Col[i]);
- }
- g.setColor(Color.yellow);
- g.drawString("X="+angX%360+" Y="+angY%360,
- 10,getSize().height-30);
- }
-
-
-
-
-
- public void delDeaw(Graphics g){
- Insets insets = getInsets();
- int L0 = insets.left, T0 = insets.top;
- g.setColor(new Color(128,128,255));
- g.fillRect(L0,T0,L0+350,T0+350);
- }
-
-
-
-
-
- public void drawPG(Graphics g,double []x,double []y,
- double []z,int xp,int yp,Color co) {
- double x1,y1,z0;
- int len=x.length;
- int [] xx=new int [len];
- int [] yy=new int [len];
- final double RAD=Math.PI/180.0;
- double a=angX*RAD;
- double b=angY*RAD;
- double sinA=Math.sin(a),sinB=Math.sin(b);
- double cosA=Math.cos(a),cosB=Math.cos(b);
- for (int i=0; i<len; i++) {
- x1= x[i]*cosB+z[i]*sinB;
- z0=-x[i]*sinB+z[i]*cosB;
- y1= y[i]*cosA- z0*sinA;
- xx[i]=xp+(int)Math.rint(x1);
- yy[i]=yp-(int)Math.rint(y1);
- }
- g.setColor(co);
- g.drawPolygon(xx,yy,len);
- }
- }