在基础教程1中,我们简单介绍了Gui的设计,这里,我们进行进一步学习.
java.awt(抽象窗口工具包)是利用了操作系统提供的图形库向我们提供界面开发的方法,所以运行较快,因为其要具有平台无关性,所以awt显然只能提供不同操作系统图形库的交集功能。相比之下,swing是基于awt的,他利用awt提供的接口方法,通过模拟的方式实现了更丰富的界面。我们将awt控件称为重量级控件,将swing控件称之为轻量级控件。(不依赖本地代码的是轻量级,依赖本地代码的是重量级)在java中,所有swing控件都是大写字母J开头的。类图如下:
现在,我们展示基础的界面代码
import java.awt.Button; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; public class TestGui { public static void main(String[] args) { //创建frame JFrame frame = new JFrame("welcome!!"); //调整frame的大小和初始位置 frame.setSize(400, 400); frame.setLocation(100, 100); //新建5个Button Button button1 = new Button("hello1"); Button button2 = new Button("hello2"); Button button3 = new Button("hello3"); Button button4 = new Button("hello4"); Button button5 = new Button("hello5"); //将5个Button添加到frame中 frame.add(button1,"East"); frame.add(button2,"West"); frame.add(button3,"South"); frame.add(button4,"Center"); frame.add(button5,"North"); //增加窗口监听事件,使用内部类方法,并用监听器的默认适配器 frame.addWindowListener(new WindowAdapter(){ //重写窗口关闭事件 @Override public void windowClosing(WindowEvent arg0) { System.exit(0); } }); //显示窗体 frame.setVisible(true); } }
下面展示向上述代码中添加绘图代码(使用java2D)
import java.awt.BorderLayout; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.*; public class TestGui extends JFrame{ private myPanel p; public TestGui(String name){ super(); //继承父类的构造方法 setTitle(name); //名字 setBounds(0,0,300,300); //大小 BorderLayout bl = new BorderLayout(); bl.setHgap(20); bl.setVgap(20); getContentPane().setLayout(bl);//布局管理 p = new myPanel("jarvischu"); p.setBounds(0, 0, 150, 150); getContentPane().add(p,bl.CENTER); this.setDefaultCloseOperation(EXIT_ON_CLOSE);//设置默认关闭操作 } public static void main(String args[]){ TestGui frame = new TestGui("JarvisChu"); frame.setVisible(true); } } class myPanel extends JPanel{ private String m_Name; public myPanel(String name){ m_Name = name; } public void paint(Graphics g){ Graphics2D g2d = (Graphics2D)g; GradientPaint grdp = new GradientPaint(0,0,Color.blue,100,50,Color.RED); //创建一个渐变填充的对象 g2d.setPaint(grdp); //选中该Paint对象 g2d.fillRect(0, 0, 200, 200); } }
最后,让我们设计一个完整的读取数据,并进行用户界面交互的程序,利用jfreechart进行绘图
package DataShow; import java.awt.CardLayout; import java.awt.FlowLayout; import java.awt.Color; import java.awt.Font; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import javax.swing.*; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import org.jfree.chart.*; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PiePlot3D; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.title.TextTitle; import org.jfree.data.general.DefaultPieDataset; import org.jfree.data.general.PieDataset; import org.jfree.data.category.DefaultCategoryDataset; public class DataShow extends JFrame implements ItemListener{ JCheckBox zhuzhuangtu; JCheckBox bingzhuangtu; CardLayout cLayout; JPanel chartPanel; static int[] data = new int[4]; //加载jdbc static{ try{ Class.forName ( "org.gjt.mm.mysql.Driver" ); System.out.println ( "success loading mysql Driver...." ); } catch ( Exception e ){ System.out.println ( "Error loading mysql Driver....." ); e.printStackTrace ( ); } } public DataShow(){ super(); //继承父类的构造方法 setTitle("ShowData"); //名字 setBounds(0,0,300,300); //大小 FlowLayout layout = new FlowLayout(); setLayout(layout); JLabel label1 = new JLabel("选择绘制方式"); add(label1); zhuzhuangtu = new JCheckBox("条形图"); bingzhuangtu = new JCheckBox("饼状图"); add(zhuzhuangtu); add(bingzhuangtu); zhuzhuangtu.addItemListener(this); bingzhuangtu.addItemListener(this); cLayout = new CardLayout(); chartPanel = new JPanel(cLayout); //绘制饼状图 PieDataset dataset1 = createDataset1(); JFreeChart bingzhuangtuChart = createPieChart(dataset1, "各季度生产情况"); ChartPanel bingzhuangtuChartPanel = new ChartPanel(bingzhuangtuChart); bingzhuangtuChartPanel.setPreferredSize(new java.awt.Dimension(500, 400));//设置组件尺寸 //绘制柱状图 DefaultCategoryDataset dataset2 = createDataset2(); JFreeChart zhuzhuangtuChart = ChartFactory.createBarChart("各季度生产情况",null,null,dataset2,PlotOrientation.HORIZONTAL,true,false,false); TextTitle textTitle = zhuzhuangtuChart.getTitle(); textTitle.setFont(new Font("黑体",Font.PLAIN,20)); CategoryPlot categoryplot = (CategoryPlot)zhuzhuangtuChart.getPlot(); categoryplot.getRenderer().setSeriesPaint(0,new Color(228,109,10)); NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis(); CategoryAxis domainAxis = categoryplot.getDomainAxis(); //设置X轴坐标上的字体样式 domainAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 11)); //设置X轴的标题字体样式 domainAxis.setLabelFont(new Font("宋体", Font.PLAIN, 12)); //设置Y轴坐标上的字体样式 numberaxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 12)); //设置Y轴的标题字体样式 numberaxis.setLabelFont(new Font("黑体", Font.PLAIN, 12)); //设置图片最底部字体样式 if(zhuzhuangtuChart.getLegend()!=null){ zhuzhuangtuChart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12)); } ChartPanel zhuzhuangtuChartPanel = new ChartPanel(zhuzhuangtuChart); zhuzhuangtuChartPanel.setPreferredSize(new java.awt.Dimension(300, 200));//设置组件尺寸 chartPanel.add(bingzhuangtuChartPanel,"bingzhuangtutuChartPanel"); chartPanel.add(zhuzhuangtuChartPanel,"zhuzhuangtutuChartPanel"); add(chartPanel); setDefaultCloseOperation(EXIT_ON_CLOSE);//设置默认关闭操作 setVisible(true); bingzhuangtu.setSelected(true); } public static void main(String args[]){ //读取数据库中的数据 try{ String url = "jdbc:mysql://localhost/sandbox"; //建立连接 Connection con = DriverManager.getConnection ( url, "root", "gaodaliang" ); //建立发送SQL命令的Statement对象 Statement stmt = con.createStatement ( ); //返回查询结果 ResultSet rs = stmt.executeQuery ( "select * from product_info" ); ResultSetMetaData md = rs.getMetaData ( ); //读取表头 int col = md.getColumnCount ( ); for ( int i = 1; i <= col; i++ ){ System.out.println ( md.getColumnName ( i ) + "/t" ); } //读取数据 int temp = 0; while ( rs.next ( ) ){ String strData = ""; for ( int i = 1; i <= col; i++ ){ strData = strData + rs.getString ( i ) + "/t"; if(i==3){ data[temp]=i=Integer.parseInt(rs.getString ( i )); } } System.out.println ( strData ); temp++; } //断开Connection连接 rs.close(); stmt.close(); con.close ( ); } catch ( SQLException e ){ e.printStackTrace ( ); } DataShow frame = new DataShow(); frame.pack(); } @Override public void itemStateChanged(ItemEvent e) { Object source = e.getItemSelectable(); if ( source == bingzhuangtu){ if(e.getStateChange()==ItemEvent.SELECTED){ zhuzhuangtu.setSelected(false); //显示饼状图 cLayout.show(chartPanel,"bingzhuangtutuChartPanel"); } } if ( source == zhuzhuangtu){ if(e.getStateChange()==ItemEvent.SELECTED){ bingzhuangtu.setSelected(false); //绘制柱状图 cLayout.show(chartPanel,"zhuzhuangtutuChartPanel"); } } } private PieDataset createDataset1() { DefaultPieDataset result = new DefaultPieDataset();//创建一个DefaultPieDataset实例,Dataset是图表的容器 result.setValue("第一季度", data[0]);//Sets the data value for a key and result.setValue("第二季度", data[1]);//sends a DatasetChangeEvent to all registered listeners. result.setValue("第三季度", data[2]);//以上注释请自己翻译 result.setValue("第四季度", data[3]); return result;//返回DefaultPieDataset对象 } private DefaultCategoryDataset createDataset2() { DefaultCategoryDataset result = new DefaultCategoryDataset();//创建一个DefaultPieDataset实例,Dataset是图表的容器 result.addValue(data[0],"生产数","第一季度"); result.addValue(data[1],"生产数","第二季度"); result.addValue(data[2],"生产数","第三季度"); result.addValue(data[3],"生产数","第四季度"); return result;//返回DefaultPieDataset对象 } private JFreeChart createPieChart(PieDataset dataset, String title) { JFreeChart chart = ChartFactory.createPieChart3D(title, dataset, true, true, false);//创建一个3D饼图 TextTitle textTitle = chart.getTitle();//获取图表的标题 textTitle.setFont(new Font("黑体", Font.PLAIN, 20));//设置图表的标题字体,避免产生乱码 chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));//设置项目字体,避免产生乱码 PiePlot3D plot = (PiePlot3D) chart.getPlot();//获取图表区域对象 plot.setStartAngle(-30);//设置开始角度,默认的是90° plot.setLabelFont(new Font("黑体", Font.PLAIN, 20));//设置标签字体,避免乱码 return chart;//返回JFreeChart对象 } }