java 图形界面
1、创建一个窗口框架
/** * java 用户界面框架 * 2016/5/10 */ package org.windows; import javax.swing.*; public class MyJFrame { public static void main(String[] args) { JFrame frame = new JFrame("MyJFrame"); //创建一个有标题的框架 frame.setSize(400,300); //设置宽度 frame.setLocationRelativeTo(null); //窗口居中显示 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //窗口关闭时结束程序 frame.setVisible(true); //这句之后窗口才会显示 } }
2、向窗口中添加一个按钮
/** * java 用户界面框架 * 2016/5/10 */ package org.windows; import javax.swing.*; public class MyJFrame { public static void main(String[] args) { JFrame frame = new JFrame("MyJFrame"); //创建一个有标题的框架 JButton jbtOK = new JButton("OK"); //新建一个按钮 frame.add(jbtOK); //将按钮添加到窗口中 frame.setSize(400,300); //设置宽度 frame.setLocationRelativeTo(null); //窗口居中显示 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //窗口关闭时结束程序 frame.setVisible(true); //这句之后窗口才会显示 } }
3、布局管理器
1) FlowLayout :按照组件的添加顺序从左到右排列在容器中,当放满一行就开始新的一行
向一个窗口添加3个标签和文本域
1 /** 2 * java 布局管理器 FlowLayout 3 * 2016/5/10 4 **/ 5 6 package org.windows; 7 8 import javax.swing.*; 9 10 import java.awt.FlowLayout; 11 12 public class MyFlowLayout extends JFrame{ 13 public MyFlowLayout(){ 14 setLayout(new FlowLayout(FlowLayout.RIGHT,10,20)); //设置右靠齐 15 16 add(new JLabel("First Name")); //添加标签 17 add(new JTextField(8)); //添加文本域,长度为8 18 add(new JLabel("MI")); 19 add(new JTextField(1)); 20 add(new JLabel("Last Name")); 21 add(new JTextField(8)); 22 } 23 public static void main(String[] args) { 24 MyFlowLayout frame = new MyFlowLayout(); 25 frame.setTitle("MyFlowLayout"); 26 frame.setSize(250,200); 27 frame.setLocationRelativeTo(null); 28 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 29 frame.setVisible(true); 30 31 } 32 33 }
2)GridLayout :以 网格的形式管理组件,组件按照它们添加的顺序从左到右排列。
向一个窗口添加3个标签和文本域
1 /** 2 * java b布局管理器 GridLayout 3 * 2016/5/10 4 **/ 5 package org.windows; 6 7 import javax.swing.*; 8 import java.awt.GridLayout; 9 public class MyGridLayout extends JFrame{ 10 public MyGridLayout(){ 11 setLayout(new GridLayout(3, 2, 25, 25)); //设置: 行数(rows):3 列数(columns):2 水平间隔(hgap):5 垂直间隔(vgap):5 12 13 add(new JLabel("First Name")); //标签 14 add(new JTextField(8)); //文本域 15 add(new JLabel("MI")); 16 add(new JTextField(1)); 17 add(new JLabel("Last Name")); 18 add(new JTextField(8)); 19 } 20 21 public static void main(String[] args) { 22 MyGridLayout frame = new MyGridLayout(); 23 frame.setSize(200,125); 24 frame.setLocationRelativeTo(null); 25 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 26 frame.setVisible(true); 27 } 28 }
3)BorderLayout: BorderLayout管理器将容器分为5个区域,东区,南区,西区,,北区,中央。
1 /** 2 * java 布局管理器 BorderLayout 3 * 2016/5/10 4 **/ 5 package org.windows; 6 7 import java.awt.BorderLayout; 8 import javax.swing.*; 9 10 public class MyBorderLayout extends JFrame { 11 public MyBorderLayout(){ 12 setLayout(new BorderLayout(5,10)); 13 14 add(new JButton("East"),BorderLayout.EAST); 15 add(new JButton("South"),BorderLayout.SOUTH); 16 add(new JButton("West"),BorderLayout.WEST); 17 add(new JButton("North"),BorderLayout.NORTH); 18 add(new JButton("Center"),BorderLayout.CENTER); 19 } 20 public static void main(String[] args) { 21 MyBorderLayout frame = new MyBorderLayout(); 22 23 frame.setTitle("MyBorderLayout"); 24 frame.setSize(300,200); 25 frame.setLocationRelativeTo(null); 26 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 27 frame.setVisible(true); 28 29 } 30 31 }
4)综合布局实验
1 /** 2 * java 布局管理器,小试牛刀 3 * 2016/5/10 4 **/ 5 package org.windows; 6 7 import javax.swing.*; 8 import java.awt.*; 9 public class TestPanels extends JFrame { 10 public TestPanels(){ 11 JPanel p1 = new JPanel(); 12 p1.setLayout(new GridLayout(4,3)); //网格布局管理器 13 for(int i = 1; i <= 9; i++){ 14 p1.add(new JButton(""+i)); 15 } 16 p1.add(new JButton(""+0)); 17 p1.add(new JButton("Start")); 18 p1.add(new JButton("Stop")); 19 20 JPanel p2 = new JPanel(new BorderLayout()); 21 p2.add(new JTextField("Time to be displany here!!"),BorderLayout.NORTH); //5个区域的布局管理器 22 p2.add(p1,BorderLayout.CENTER); 23 24 add(p2,BorderLayout.EAST); 25 add(new JButton("Food to be placed here"),BorderLayout.CENTER); 26 27 28 } 29 public static void main(String[] args) { 30 TestPanels frame = new TestPanels(); 31 frame.setTitle("TestPanels"); 32 frame.setSize(400,250); 33 frame.setLocationRelativeTo(null); 34 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 35 frame.setVisible(true); 36 } 37 }
运行效果:
4、Swing GUI 属性的使用
1 /** 2 * java Swing GUI 组件的公共特性 3 * 2016/5/10 4 **/ 5 package org.windows; 6 7 import javax.swing.*; 8 import javax.swing.border.*; 9 import java.awt.*; 10 11 public class TestSwingAttribute extends JFrame{ 12 public TestSwingAttribute(){ 13 JPanel p1 = new JPanel(new FlowLayout(FlowLayout.LEFT,2,2)); 14 JButton jbtLeft = new JButton("Left"); 15 JButton jbtCenter = new JButton("Center"); 16 JButton jbtRight = new JButton("Right"); 17 jbtLeft.setBackground(Color.WHITE); //设置背景色为白色 18 jbtCenter.setForeground(Color.GREEN); //设置前景色、 19 jbtRight.setToolTipText("This is the Right button"); //鼠标放在按钮上会显示提示文本 20 p1.add(jbtLeft); 21 p1.add(jbtCenter); 22 p1.add(jbtRight); 23 p1.setBorder(new TitledBorder("Three Buttons")); //设置标题边界 24 25 Font largeFont = new Font("TimesRoman",Font.BOLD,20); //字体属性 26 Border lineBorder = new LineBorder(Color.BLACK,2); //设置线边界 27 28 JPanel p2 = new JPanel(new GridLayout(1, 2, 5, 5)); 29 JLabel jlblRed = new JLabel("Red"); 30 JLabel jlblOrange = new JLabel("Orange"); 31 jlblRed.setForeground(Color.RED); //设置背景色 32 jlblOrange.setForeground(Color.ORANGE); 33 jlblRed.setFont(largeFont); //设置字体 34 jlblOrange.setFont(largeFont); 35 jlblRed.setBorder(lineBorder); //设置线边界 36 jlblOrange.setBorder(lineBorder); 37 p2.add(jlblRed); 38 p2.add(jlblOrange); 39 p2.setBorder(new TitledBorder("Two Labels")); //设置标题边界 40 setLayout(new GridLayout(2, 1, 5, 5)); 41 add(p1); 42 add(p2); 43 44 } 45 46 public static void main(String[] args) { 47 JFrame frame = new TestSwingAttribute(); 48 frame.setTitle("TestSwingAttribute"); 49 frame.setSize(300,150); 50 frame.setLocationRelativeTo(null); 51 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 52 frame.setVisible(true); 53 54 } 55 56 }
运行效果:
5、FigurePanel实例类
1 /** 2 * java Graphics类的使用 在面板上话图形 3 * 2016/5/10 4 **/ 5 package org.windows; 6 import java.awt.*; 7 import javax.swing.*; 8 9 10 public class TestFigurePanel extends JFrame { 11 public TestFigurePanel(){ 12 setLayout(new GridLayout(2, 3, 5, 5)); //建立2行3列的布局 13 add(new FigurePanel(FigurePanel.LINE));//调用FigurePanel 14 add(new FigurePanel(FigurePanel.RECTANGLE)); 15 add(new FigurePanel(FigurePanel.ROUND_RECTANGLE)); 16 add(new FigurePanel(FigurePanel.OVAL)); 17 add(new FigurePanel(FigurePanel.RECTANGLE, true)); 18 add(new FigurePanel(FigurePanel.ROUND_RECTANGLE, true)); 19 } 20 21 public static void main(String[]args){ 22 TestFigurePanel frame = new TestFigurePanel(); 23 frame.setSize(400, 200); 24 frame.setTitle("TestFigurePanel"); 25 frame.setLocationRelativeTo(null); // Center the frame 26 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 27 frame.setVisible(true); 28 } 29 }
1 /** 2 * java Graphics类的使用 在面板上话图形 3 * 2016/5/10 4 **/ 5 package org.windows; 6 import javax.swing.*; 7 import java.awt.*; 8 public class FigurePanel extends JPanel { 9 public static final int LINE = 1; 10 public static final int RECTANGLE = 2; 11 public static final int ROUND_RECTANGLE = 3; 12 public static final int OVAL = 4; 13 14 private int type = 1; 15 private boolean filled; 16 17 public FigurePanel() { 18 } 19 20 public FigurePanel(int type) { 21 this.type = type; 22 } 23 24 public FigurePanel(int type, boolean filled) { 25 this.type = type; 26 this.filled = filled; 27 } 28 29 public void paintComponent(Graphics g) { 30 super.paintComponent(g); 31 int width = getSize().width; 32 int height = getSize().height; 33 34 35 switch (type) { 36 case LINE: 37 g.setColor(Color.BLACK); 38 g.drawLine(10, 10, width - 10, height - 10); 39 g.drawLine(width - 10, 10, 10, height - 10); 40 break; 41 case RECTANGLE: 42 g.setColor(Color.BLUE); 43 if(filled) 44 g.fillRect((int) (0.1 * width), (int) (0.1 * height), 45 (int) (0.8 * width), (int) 0.8 * height); 46 else 47 g.drawRect((int)(0.1*width), (int)(0.1*height), (int)(0.8*width),(int)(0.8*height)); 48 break; 49 case ROUND_RECTANGLE: 50 g.setColor(Color.RED); 51 if(filled){ 52 g.fillRoundRect((int)(0.1*width),(int)(0.1*height),(int)(0.8*width),(int)(0.8*height),20, 20); 53 } 54 else 55 g.drawRoundRect((int)(0.1*width),(int)(0.1*height),(int)(0.8*width),(int)(0.8*height),20, 20); 56 break; 57 58 case OVAL: 59 g.setColor(Color.BLACK); 60 if(filled) 61 g.fillOval((int)(0.1*width),(int)(0.1*height),(int)(0.8*width),(int)(0.8*height)); 62 else 63 g.drawOval((int)(0.1*width),(int)(0.1*height),(int)(0.8*width),(int)(height*0.8)); 64 break; 65 } 66 } 67 public void setType(int type){ 68 this.type = type; 69 repaint(); //刷新视图区域 70 } 71 public int getType(){ 72 return type; 73 } 74 75 public void setFilled(boolean filled){ 76 this.filled = filled; 77 } 78 public boolean getFilled(){ 79 return filled; 80 } 81 public Dimension getPreferredSise(){ 82 return new Dimension(80, 80); 83 } 84 85 }
运行效果:
其中有一个显示不出来,弄了好久也没有弄明白为什么,待解决。
6、绘制弧形
fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)
用于弧形的填充
- 参数:
x
- 要填充弧的左上角的 x 坐标。y
- 要填充弧的左上角的 y 坐标。width
- 要填充弧的宽度。height
- 要填充弧的高度。startAngle
- 开始角度。arcAngle
- 相对于开始角度而言,弧跨越的角度。-
1 /** 2 * java 面板绘制弧形 3 * 2016/5/10 4 **/ 5 package org.windows; 6 7 import javax.swing.*; 8 import java.awt.*; 9 public class DrawArcs extends JFrame { 10 DrawArcs(){ 11 setTitle("DrawArcs"); 12 add(new ArcsPanel()); 13 } 14 public static void main(String[] args) { 15 DrawArcs frame = new DrawArcs(); 16 frame.setSize(300,300); 17 frame.setLocationRelativeTo(null); 18 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 19 frame.setVisible(true); 20 } 21 } 22 23 class ArcsPanel extends JPanel{ 24 protected void paintComponent(Graphics g){ 25 super.paintComponent(g); 26 27 int xCenter = getWidth() / 2; 28 int yCenter = getHeight() /2; 29 int radius = (int)(Math.min(getWidth(),getHeight()) * 0.4); 30 31 int x = xCenter - radius; 32 int y = yCenter - radius; 33 34 g.fillArc(x, y, 2*radius, 2*radius, 0, 30); //填充弧形 35 g.fillArc(x, y, 2*radius, 2*radius, 90, 30); 36 g.fillArc(x, y, 2*radius, 2*radius, 180,30); 37 g.fillArc(x, y, 2*radius, 2*radius, 270, 30); 38 } 39 }
运行结果:
7、绘制当前时间的时钟
这个程序分为两个部分,一个控制主窗口,一个用于绘制时钟。
1)绘制时钟类:
1 /** 2 * java 在面板上显示时钟 3 * 2016/5/11 4 **/ 5 package org.windows; 6 7 import javax.swing.*; 8 import java.awt.*; 9 import java.util.*; 10 11 public class StillClock extends JPanel{ 12 private int hour; 13 private int minute; 14 private int second; 15 16 public StillClock(){ 17 setCurrentTime(); 18 } 19 20 public StillClock(int hour, int minute, int second){ 21 this.hour = hour; 22 this.minute = minute; 23 this.second = second; 24 } 25 26 public int getHour() { 27 return hour; 28 } 29 30 public void setHour(int hour) { 31 this.hour = hour; 32 repaint(); //这个方法会引起JVM调用paintComponent() 33 } 34 35 public int getMinute() { 36 return minute; 37 } 38 39 public void setMinute(int minute) { 40 this.minute = minute; 41 repaint(); 42 } 43 44 public int getSecond() { 45 return second; 46 } 47 48 public void setSecond(int second) { 49 this.second = second; 50 repaint(); 51 } 52 53 protected void paintComponent(Graphics g){ //绘制图形 54 super.paintComponent(g); //为了确保视图域在显示新图之前被清除 55 56 int clockRadius = (int)(Math.min(getWidth(), getHeight()) * 0.8 *0.5); 57 int xCenter = getWidth() / 2; 58 int yCenter = getHeight() / 2; 59 60 g.setColor(Color.BLACK); 61 g.drawOval(xCenter - clockRadius, yCenter - clockRadius, 2 * clockRadius, 2 * clockRadius); 62 g.drawString("12", xCenter - 5, yCenter - clockRadius + 12); //绘制12时间刻度 63 g.drawString("9", xCenter - clockRadius + 3, yCenter + 5); 64 g.drawString("3", xCenter + clockRadius - 10, yCenter + 3); 65 g.drawString("6", xCenter - 3, yCenter + clockRadius - 3); 66 67 //秒针 68 int sLength = (int)(clockRadius * 0.8); 69 int xSecond = (int)(xCenter + sLength * Math.sin(second * (2 * Math.PI / 60))); 70 int ySecond = (int)(yCenter - sLength * Math.cos(second * (2 * Math.PI / 60))); 71 g.setColor(Color.red); //设置秒针颜色 72 g.drawLine(xCenter, yCenter, xSecond, ySecond); //绘制秒针 73 74 //分针 75 int mLength = (int)(clockRadius * 0.65); 76 int xMinute = (int)(xCenter + mLength * Math.sin(minute * (2 * Math.PI / 60))); 77 int yMinute = (int)(yCenter - mLength * Math.cos(minute * (2 * Math.PI / 60))); 78 g.setColor(Color.blue); 79 g.drawLine(xCenter, yCenter, xMinute, yMinute); 80 81 //时针 82 int hLength = (int)(clockRadius * 0.5); 83 int xHour = (int)(xCenter + hLength * Math.sin((hour % 12 + minute / 60.0) * (2 * Math.PI / 12))); 84 int yHour = (int)(yCenter - hLength * Math.cos((hour % 12 + minute / 60.0) * (2 * Math.PI / 12))); 85 g.setColor(Color.green); 86 g.drawLine(xCenter, yCenter, xHour, yHour); 87 } 88 89 public void setCurrentTime(){ 90 Calendar calendar = new GregorianCalendar(); 91 92 //设置小时,分钟,秒 93 this.hour = calendar.get(Calendar.HOUR_OF_DAY); 94 this.minute = calendar.get(Calendar.MINUTE); 95 this.second = calendar.get(Calendar.SECOND); 96 } 97 98 public Dimension getPrefreferredSize(){ 99 return new Dimension(200, 200); 100 } 101 102 }
2) 主窗口类:
1 /** 2 * java 在面板上显示时钟 3 * 2016/5/11 4 **/ 5 package org.windows; 6 7 import javax.swing.*; 8 import java.awt.*; 9 import java.text.SimpleDateFormat; 10 import java.util.Date; 11 public class DisPlayClock extends JFrame{ 12 public DisPlayClock(){ 13 StillClock clock = new StillClock(); 14 15 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 设置日期格式 16 JLabel jl = new JLabel(df.format(new Date()));//获取当前系统时间 17 18 add(clock); 19 add(jl, BorderLayout.SOUTH); 20 } 21 22 public static void main(String[] args) { 23 DisPlayClock frame = new DisPlayClock(); 24 frame.setTitle("DisPlauClock"); 25 frame.setSize(300, 350); 26 frame.setLocationRelativeTo(null); 27 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 28 frame.setVisible(true); 29 } 30 31 }
运行效果:
这个图只能静态的显示时间,不能一直刷新。
8、 改进时钟,使其可以动态显示时钟
时钟类不变,在主窗口类中增加监听:
主窗口改版后的代码:
1 /** 2 * java 在面板上动态显示时钟 3 * 2016/5/11 4 **/ 5 package org.windows; 6 7 import javax.swing.*; 8 9 10 import java.awt.*; 11 import java.awt.event.ActionEvent; 12 import java.awt.event.ActionListener; 13 import java.text.SimpleDateFormat; 14 import java.util.Calendar; 15 import java.util.Date; 16 import java.util.Timer; 17 import java.util.TimerTask; 18 19 public class DisPlayClock extends JFrame{ 20 21 private StillClock clock = new StillClock(); //图形时钟 22 23 private JLabel displayArea; //放置时间的标签 24 private String time; //记录时间 25 26 public DisPlayClock(){ 27 displayArea = new JLabel(); 28 29 add(clock); 30 add(displayArea, BorderLayout.SOUTH); 31 //安排任务,定期执行 32 Timer timer = new Timer(); 33 timer.scheduleAtFixedRate(new JLabelTimerTask(), new Date(), (long)1000); 34 } 35 36 //内部类监听 37 class JLabelTimerTask extends TimerTask{ 38 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 设置日期格式 39 public void run() { 40 //刷新图形时钟 41 clock.setCurrentTime(); 42 clock.repaint(); 43 44 //刷新文字时钟 45 time = df.format(Calendar.getInstance().getTime()); 46 displayArea.setText(time); 47 } 48 } 49 50 public static void main(String[] args) { 51 DisPlayClock frame = new DisPlayClock(); 52 frame.setTitle("DisPlauClock"); 53 frame.setSize(300, 350); 54 frame.setLocationRelativeTo(null); 55 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 56 frame.setVisible(true); 57 } 58 }
运行结果:
9、监听器,注册,处理
在面板上使用两个按钮来控制圆的大小
(1)使用内部类进行监听
代码:
1 /** 2 * java 圆控制 事件监听 3 * 2016/5/11 4 **/ 5 package org.windows; 6 7 import javax.swing.*; 8 import java.awt.*; 9 import java.awt.event.*; 10 public class ControlCircle extends JFrame{ 11 12 private JButton jbtEnlarge = new JButton("Enlatge"); 13 private JButton jbtShrink = new JButton("Shrink"); 14 private CirclePanel canvas = new CirclePanel(); 15 16 public ControlCircle(){ 17 JPanel panel = new JPanel(); 18 panel.add(jbtEnlarge); 19 panel.add(jbtShrink); 20 this.add(canvas, BorderLayout.CENTER); 21 this.add(panel, BorderLayout.SOUTH); 22 23 jbtEnlarge.addActionListener(new EnlargeListener()); //增加增大按钮的监听 24 jbtShrink.addActionListener(new ShrinkListener()); //增加减小按钮的监听 25 26 } 27 public static void main(String[] args) { 28 JFrame frame = new ControlCircle(); 29 frame.setTitle("ControlCircle"); 30 frame.setSize(200, 200); 31 frame.setLocationRelativeTo(null); 32 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 33 frame.setVisible(true); 34 } 35 36 //增大按钮的监听类 37 class EnlargeListener implements ActionListener { 38 public void actionPerformed(ActionEvent e){ 39 canvas.enlarge(); 40 } 41 } 42 43 //减小按钮的监听类 44 class ShrinkListener implements ActionListener { 45 public void actionPerformed(ActionEvent e){ 46 canvas.shrink(); 47 } 48 } 49 50 class CirclePanel extends JPanel{ 51 private int radius = 20;//圆的初始半径 52 53 //增大的响应方法 54 public void enlarge(){ 55 radius+=2; //将圆的半径增加2个像素 56 repaint(); 57 } 58 59 //减小的响应方法 60 public void shrink(){ 61 radius-=2; //将圆的半径减小2个像素 62 repaint(); 63 } 64 65 protected void paintComponent(Graphics g){ 66 super.paintComponent(g); 67 68 g.drawOval(getWidth() / 2 - radius, getHeight() / 2 - radius, 2 * radius, 2 * radius); 69 } 70 } 71 }
运行效果:
(2)使用匿名类进行监听
代码:
1 /** 2 * java 圆控制 事件监听 匿名类监听 3 * 2016/5/11 4 **/ 5 package org.windows; 6 7 import javax.swing.*; 8 import java.awt.*; 9 import java.awt.event.*; 10 public class ControlCircle_2 extends JFrame{ 11 12 private JButton jbtEnlarge = new JButton("Enlatge"); 13 private JButton jbtShrink = new JButton("Shrink"); 14 private CirclePanel canvas = new CirclePanel(); 15 16 public ControlCircle_2(){ 17 JPanel panel = new JPanel(); 18 panel.add(jbtEnlarge); 19 panel.add(jbtShrink); 20 this.add(canvas, BorderLayout.CENTER); 21 this.add(panel, BorderLayout.SOUTH); 22 23 // jbtEnlarge.addActionListener(new EnlargeListener()); //增加增大按钮的监听 24 jbtEnlarge.addActionListener(new ActionListener(){ 25 public void actionPerformed(ActionEvent e){ 26 canvas.enlarge(); 27 } 28 }); 29 //jbtShrink.addActionListener(new ShrinkListener()); //增加减小按钮的监听 30 jbtShrink.addActionListener(new ActionListener(){ 31 public void actionPerformed(ActionEvent e){ 32 canvas.shrink(); 33 } 34 }); 35 36 } 37 public static void main(String[] args) { 38 JFrame frame = new ControlCircle_2(); 39 frame.setTitle("ControlCircle"); 40 frame.setSize(200, 200); 41 frame.setLocationRelativeTo(null); 42 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 43 frame.setVisible(true); 44 } 45 /* 46 //增大按钮的监听类 47 class EnlargeListener implements ActionListener { 48 public void actionPerformed(ActionEvent e){ 49 canvas.enlarge(); 50 } 51 } 52 53 //减小按钮的监听类 54 class ShrinkListener implements ActionListener { 55 public void actionPerformed(ActionEvent e){ 56 canvas.shrink(); 57 } 58 } 59 */ 60 class CirclePanel extends JPanel{ 61 private int radius = 20;//圆的初始半径 62 63 //增大的响应方法 64 public void enlarge(){ 65 radius+=2; //将圆的半径增加2个像素 66 repaint(); 67 } 68 69 //减小的响应方法 70 public void shrink(){ 71 radius-=2; //将圆的半径减小2个像素 72 repaint(); 73 } 74 75 protected void paintComponent(Graphics g){ 76 super.paintComponent(g); 77 78 g.drawOval(getWidth() / 2 - radius, getHeight() / 2 - radius, 2 * radius, 2 * radius); 79 } 80 } 81 }
运行效果同上
10、小小计算器
从两个文本框中获取数据,点击按钮,将两个数的和显示在另一个文本域
1 /** 2 * java 图形计算器1.0版 3 * 2016/5/11 4 **/ 5 package org.windows; 6 7 import javax.swing.*; 8 import java.awt.*; 9 import java.awt.event.*; 10 public class Calculator_1 extends JFrame{ 11 12 private JTextField num_1 = new JTextField(8); 13 private JTextField num_2 = new JTextField(8); 14 private JTextField sum = new JTextField(8); 15 private JButton addNum = new JButton("ADD"); 16 17 public Calculator_1(){ 18 JPanel p1 = new JPanel(new GridLayout(2, 2, 5, 5)); 19 p1.add(new JLabel("NUM_1")); 20 p1.add(num_1); 21 p1.add(new JLabel("NUM_2")); 22 p1.add(num_2); 23 add(p1); 24 25 JPanel p2 = new JPanel(new BorderLayout()); 26 p2.add(addNum); 27 p2.add(sum,BorderLayout.SOUTH); 28 add(p2,BorderLayout.SOUTH); 29 30 //响应事件 31 addNum.addActionListener(new ActionListener(){ 32 public void actionPerformed(ActionEvent e) { 33 int num1 = Integer.parseInt(num_1.getText()); 34 int num2 = Integer.parseInt(num_2.getText()); 35 int sum_x = num1 + num2; 36 sum.setText(sum_x+""); 37 } 38 }); 39 } 40 41 public static void main(String[] args) { 42 JFrame frame = new Calculator_1(); 43 frame.pack(); 44 frame.setLocationRelativeTo(null); 45 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 46 frame.setVisible(true); 47 } 48 }
说明:代码没有进行输入检查,只是了解怎么在文本与读取数据。
运行结果:
11、鼠标拖动事件
在窗口类用鼠标拖动文本
1 /**java 鼠标响应事件 2 * 2016/5/11 3 **/ 4 package org.windows; 5 6 import javax.swing.*; 7 import java.awt.*; 8 import java.awt.event.*; 9 public class MouseEven extends JFrame{ 10 11 public MouseEven(){ 12 MouseEvenMove p = new MouseEvenMove("welcome to java~~"); 13 14 setLayout(new BorderLayout()); 15 add(p); 16 } 17 public static void main(String[] args) { 18 MouseEven frame = new MouseEven(); 19 frame.setSize(200, 100); 20 frame.setLocationRelativeTo(null); 21 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 22 frame.setVisible(true); 23 } 24 25 static class MouseEvenMove extends JPanel{ 26 private String message = "Welcome to Java"; 27 private int x = 20; 28 private int y = 20; 29 30 public MouseEvenMove(String str){ 31 message = str; 32 addMouseMotionListener(new MouseMotionAdapter(){ 33 public void mouseDragged(MouseEvent e){ 34 x = e.getX(); 35 y = e.getY(); 36 System.out.println("坐标:"+x+" "+y); 37 repaint(); 38 } 39 }); 40 } 41 42 protected void paintComponent(Graphics g){ 43 super.paintComponent(g); 44 g.drawString(message, x, y); 45 } 46 } 47 }
运行效果:
12、鼠标拖动事件二
通过拖动改变一个球形的大小
1 /**java 鼠标响应事件 2 * 2016/5/11 3 **/ 4 package org.windows; 5 6 import javax.swing.*; 7 import java.awt.*; 8 import java.awt.event.*; 9 public class CircleMove extends JFrame{ 10 private int radius = 20; 11 private int x = 20; 12 private int y = 20; 13 14 public CircleMove(){ 15 MouseEvenMove p = new MouseEvenMove(20); 16 17 setLayout(new BorderLayout()); 18 add(p); 19 } 20 public static void main(String[] args) { 21 CircleMove frame = new CircleMove(); 22 frame.setSize(500, 300); 23 frame.setLocationRelativeTo(null); 24 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 25 frame.setVisible(true); 26 } 27 28 class MouseEvenMove extends JPanel{ 29 30 public MouseEvenMove(int num){ 31 radius = num; 32 addMouseMotionListener(new MouseMotionAdapter(){ 33 public void mouseDragged(MouseEvent e){ 34 x = e.getX(); 35 y = e.getY(); 36 double str = Math.sqrt((x - (getWidth() / 2)) * (x - (getWidth() / 2)) + 37 (y - (getHeight() / 2)) * (y - (getHeight() / 2))); 38 radius = (int)str; 39 System.out.println("坐标:"+x+" "+y); 40 repaint(); 41 } 42 }); 43 } 44 45 protected void paintComponent(Graphics g){ 46 super.paintComponent(g); 47 g.drawOval(getWidth() / 2 - radius, getHeight() / 2 - radius, 2 * radius, 2 * radius); 48 g.drawOval(getWidth() / 2 - radius/2, getHeight() / 2 - radius, radius, 2 * radius); 49 g.drawOval(getWidth() / 2 - radius, getHeight() / 2 - radius/2, 2 * radius, radius); 50 } 51 } 52 }
运行效果:
13、鼠标拖动时间三
在鼠标拖动时间二的基础上增加年一个功能,当球体的半径改变时,点击刷新按钮就可以计算出球体半径,以及表面积和体积。
1 /**java 鼠标响应事件 2 * 2016/5/11 3 **/ 4 package org.windows; 5 6 import javax.swing.*; 7 import java.awt.*; 8 import java.awt.event.*; 9 10 public class CircleMove_1 extends JFrame { 11 protected int radius = 20; 12 private int x = 20; 13 private int y = 20; 14 15 public CircleMove_1() { 16 MouseEvenMove p = new MouseEvenMove(20); 17 CircleParameter p2 = new CircleParameter(); 18 19 setLayout(new BorderLayout()); 20 add(p); 21 add(p2.jp, BorderLayout.SOUTH); 22 23 addMouseMotionListener(new MouseMotionAdapter() { 24 public void mouseDragged(MouseEvent e) { 25 x = e.getX(); 26 y = e.getY(); 27 double str = Math.sqrt((x - (getWidth() / 2)) 28 * (x - (getWidth() / 2)) + (y - (getHeight() / 2)) 29 * (y - (getHeight() / 2))); 30 radius = (int) str; 31 System.out.println("坐标:" + x + " " + y); 32 repaint(); 33 } 34 }); 35 36 } 37 38 public static void main(String[] args) { 39 CircleMove_1 frame = new CircleMove_1(); 40 frame.setSize(500, 300); 41 frame.setLocationRelativeTo(null); 42 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 43 frame.setVisible(true); 44 } 45 46 class MouseEvenMove extends JPanel { 47 public MouseEvenMove(int num) { 48 radius = num; 49 } 50 51 protected void paintComponent(Graphics g) { 52 super.paintComponent(g); 53 g.drawOval(getWidth() / 2 - radius, getHeight() / 2 - radius, 54 2 * radius, 2 * radius); 55 g.drawOval(getWidth() / 2 - radius / 2, getHeight() / 2 - radius, 56 radius, 2 * radius); 57 g.drawOval(getWidth() / 2 - radius, getHeight() / 2 - radius / 2, 58 2 * radius, radius); 59 } 60 } 61 62 class CircleParameter extends JPanel { 63 private JLabel JLradius = new JLabel("radius "); 64 private JTextField JTradius = new JTextField(5); 65 66 private JLabel JLarea = new JLabel(" area "); 67 private JTextField JTarea = new JTextField(8); 68 69 private JLabel JLvolume = new JLabel("volume"); 70 private JTextField JTvolume = new JTextField(8); 71 72 private JButton jbt = new JButton("刷新"); 73 74 JPanel jp = new JPanel(); 75 76 public CircleParameter() { 77 jp.setPreferredSize(new Dimension(150, 40));// 设置面板大小 78 setLayout(new GridLayout(3, 2, 5, 5)); 79 jp.add(JLradius); 80 jp.add(JTradius); 81 jp.add(JLarea); 82 jp.add(JTarea); 83 jp.add(JLvolume); 84 jp.add(JTvolume); 85 jp.add(jbt); 86 87 // 响应事件 88 jbt.addActionListener(new ActionListener() { 89 public void actionPerformed(ActionEvent e) { 90 91 double num_1 = (double) (4 * Math.PI * radius * radius); 92 double num_1_1 = (double) (Math.round(num_1 * 100) / 100.0);// 保留两位小数 93 94 double num_2 = 4 / 3 * Math.PI * radius * radius; 95 double num_2_2 = (double) (Math.round(num_2 * 100) / 100.0);// 保留两位小数 96 JTradius.setText(radius + ""); 97 JTarea.setText(num_1_1 + ""); 98 JTvolume.setText(num_2_2 + ""); 99 } 100 }); 101 102 } 103 } 104 }
运行效果:
14、鼠标拖动事件四:
在鼠标拖动事件三的基础上除去刷新按钮,让程序自动监控图形的大小变化,然后将半径面积体积等信息同步更新在面板上。
1 /**java 鼠标响应事件 2 * 2016/5/11 3 **/ 4 package org.windows; 5 6 import javax.swing.*; 7 import java.awt.*; 8 import java.awt.event.*; 9 10 public class CircleMove_1 extends JFrame { 11 protected int radius = 20; 12 private int x = 20; 13 private int y = 20; 14 15 public CircleMove_1() { 16 MouseEvenMove p = new MouseEvenMove(20); 17 final CircleParameter p2 = new CircleParameter(); 18 19 setLayout(new BorderLayout()); 20 add(p); 21 add(p2.jp, BorderLayout.SOUTH); 22 23 addMouseMotionListener(new MouseMotionAdapter() { 24 public void mouseDragged(MouseEvent e) { 25 x = e.getX(); 26 y = e.getY(); 27 double str = Math.sqrt((x - (getWidth() / 2)) 28 * (x - (getWidth() / 2)) + (y - (getHeight() / 2)) 29 * (y - (getHeight() / 2))); 30 radius = (int) str; 31 System.out.println("坐标:" + x + " " + y); 32 repaint(); 33 p2.newText(); 34 } 35 }); 36 37 //更改响应事件 38 p2.JTradius.addActionListener(new ActionListener(){ 39 public void actionPerformed(ActionEvent e){ 40 System.out.println("你重新输入了一个字"); 41 String JTradius_x = p2.JTradius.getText(); 42 radius = Integer.parseInt(JTradius_x); 43 System.out.println("半径"+radius); 44 repaint(); 45 p2.newText(); 46 } 47 }); 48 49 50 } 51 52 public static void main(String[] args) { 53 CircleMove_1 frame = new CircleMove_1(); 54 frame.setSize(500, 300); 55 frame.setLocationRelativeTo(null); 56 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 57 frame.setVisible(true); 58 } 59 60 class MouseEvenMove extends JPanel { 61 public MouseEvenMove(int num) { 62 radius = num; 63 } 64 65 protected void paintComponent(Graphics g) { 66 super.paintComponent(g); 67 g.drawOval(getWidth() / 2 - radius, getHeight() / 2 - radius, 68 2 * radius, 2 * radius); 69 g.drawOval(getWidth() / 2 - radius / 2, getHeight() / 2 - radius, 70 radius, 2 * radius); 71 g.drawOval(getWidth() / 2 - radius, getHeight() / 2 - radius / 2, 72 2 * radius, radius); 73 } 74 } 75 76 class CircleParameter extends JPanel { 77 private JLabel JLradius = new JLabel("radius "); 78 private JTextField JTradius = new JTextField(5); 79 80 private JLabel JLarea = new JLabel(" area "); 81 private JTextField JTarea = new JTextField(8); 82 83 private JLabel JLvolume = new JLabel("volume"); 84 private JTextField JTvolume = new JTextField(8); 85 86 87 JPanel jp = new JPanel(); 88 89 public CircleParameter() { 90 jp.setPreferredSize(new Dimension(150, 40));// 设置面板大小 91 setLayout(new GridLayout(3, 2, 5, 5)); 92 jp.add(JLradius); 93 jp.add(JTradius); 94 jp.add(JLarea); 95 jp.add(JTarea); 96 jp.add(JLvolume); 97 jp.add(JTvolume); 98 } 99 protected void newText() { 100 double num_1 = (double) (4 * Math.PI * radius * radius); 101 double num_1_1 = (double) (Math.round(num_1 * 100) / 100.0);// 保留两位小数 102 double num_2 = 4 / 3 * Math.PI * radius * radius; 103 double num_2_2 = (double) (Math.round(num_2 * 100) / 100.0);// 保留两位小数 104 JTradius.setText(radius + ""); 105 JTarea.setText(num_1_1 + ""); 106 JTvolume.setText(num_2_2 + ""); 107 System.out.println("调用第二个面板的成功了"); 108 } 109 110 } 111 }
运行效果:
15、使用进度条
1 package cn.thread; 2 3 import java.awt.BorderLayout; 4 import java.awt.EventQueue; 5 import java.awt.event.ActionEvent; 6 import java.awt.event.ActionListener; 7 import java.beans.PropertyChangeEvent; 8 import java.beans.PropertyChangeListener; 9 import java.beans.PropertyChangeListenerProxy; 10 11 import javax.swing.JFrame; 12 import javax.swing.JPanel; 13 import javax.swing.border.EmptyBorder; 14 import javax.swing.JTextArea; 15 import javax.swing.JLabel; 16 import javax.swing.JTextField; 17 import javax.swing.SwingWorker; 18 import javax.swing.JButton; 19 import javax.swing.JProgressBar; 20 import javax.swing.JScrollBar; 21 import javax.swing.JScrollPane; 22 23 public class progressBarDemo extends JFrame { 24 25 private JPanel contentPane; 26 private JTextField jtfPrimeCount; 27 private JProgressBar jpb; 28 /** 29 * Launch the application. 30 */ 31 public static void main(String[] args) { 32 EventQueue.invokeLater(new Runnable() { 33 public void run() { 34 try { 35 progressBarDemo frame = new progressBarDemo(); 36 frame.setVisible(true); 37 } catch (Exception e) { 38 e.printStackTrace(); 39 } 40 } 41 }); 42 } 43 44 /** 45 * Create the frame. 46 */ 47 public progressBarDemo() { 48 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 49 setBounds(300, 200, 450, 300); 50 contentPane = new JPanel(); 51 contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 52 setContentPane(contentPane); 53 contentPane.setLayout(null); 54 55 JTextArea jtaResult = new JTextArea(); 56 jtaResult.setBounds(10, 10, 414, 163); 57 jtaResult.setWrapStyleWord(true); 58 jtaResult.setLineWrap(true); 59 60 JScrollPane scroll = new JScrollPane(jtaResult); 61 scroll.setVerticalScrollBarPolicy( 62 JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); 63 // contentPane.add(jtaResult); 64 scroll.setBounds(10, 10, 414, 163); 65 contentPane.add(scroll); 66 67 68 JLabel label = new JLabel("请输入要计算的素数的个数:"); 69 label.setBounds(20, 183, 169, 15); 70 contentPane.add(label); 71 72 jtfPrimeCount = new JTextField(); 73 jtfPrimeCount.setBounds(199, 183, 66, 21); 74 contentPane.add(jtfPrimeCount); 75 jtfPrimeCount.setColumns(10); 76 77 JButton button = new JButton("开始计算"); 78 button.setBounds(314, 183, 93, 23); 79 button.addActionListener(new ActionListener() { 80 public void actionPerformed(ActionEvent e) { 81 int text = Integer.parseInt(jtfPrimeCount.getText()); 82 ComputePrime task = new ComputePrime( 83 text,jtaResult); 84 task.addPropertyChangeListener(new PropertyChangeListener() { 85 86 @Override 87 public void propertyChange(PropertyChangeEvent evt) { 88 if("progress".equals(evt.getPropertyName())){ 89 jpb.setValue((Integer)evt.getNewValue()); 90 } 91 92 } 93 }); 94 task.execute(); 95 } 96 }); 97 contentPane.add(button); 98 99 jpb = new JProgressBar(); 100 jpb.setBounds(21, 225, 403, 14); 101 jpb.setStringPainted(true); 102 jpb.setValue(0); 103 jpb.setMaximum(100); 104 contentPane.add(jpb); 105 } 106 107 static class ComputePrime extends SwingWorker<Integer, Integer>{ 108 private int count; 109 private JTextArea result; 110 public ComputePrime(int count, JTextArea result){ 111 this.count = count; 112 this.result = result; 113 } 114 protected Integer doInBackground(){ 115 publishPrimeNumbers(count); 116 return 0; 117 } 118 protected void process(java.util.List<Integer>list) { 119 for(int i= 0; i < list.size(); i++){ 120 result.append(list.get(i) + " "); 121 } 122 } 123 private void publishPrimeNumbers(int n){ 124 int count = 0; //需要找到素数的个数 125 int number = 2; 126 while(count <= n){ 127 if(isPrime(number)){ 128 count++; 129 //上传进度 130 setProgress(100 * count / n); 131 publish(number); 132 } 133 //判断下一个数是否是素数 134 number ++; 135 } 136 } 137 //判断这个数是否是素数 138 private static boolean isPrime(int number) { 139 for(int divisor = 2; divisor <= number / 2; divisor++){ 140 if(number % divisor == 0) { 141 return false; 142 } 143 } 144 return true; 145 } 146 } 147 }