介绍
java swing是java的一种图形化工具包,跨平台
语法介绍
库函数
import javax.swing.*;
主函数扩展
public class CalcMain extends JFrame
控件定义
区块
private final JPanel JP_North = new JPanel();
输入框
private final JTextArea Input_Text = new JTextArea(2,1);
按钮
private final JButton C_Btn = new JButton(“AC”);
Jframe设置方法
设置宽度,高度
this.setSize(Frame_width,Frame_height);
int Frame_width=850;//程序宽
int Frame_height=400;//程序高
获取屏幕宽度
int Screen_Width=Toolkit.getDefaultToolkit().getScreenSize().width;
获取屏幕高度
int Screen_Height=Toolkit.getDefaultToolkit().getScreenSize().height;
设置中心点X坐标
int Frame_X=(Screen_Width-Frame_width)/2;
设置中心点Y坐标
int Frame_Y=(Screen_Height-Frame_height)/2;
设置中心点位置
this.setLocation(Frame_X,Frame_Y);
设置程序标题
String TitleName=”Double calculator——-By B20031110″;
this.setTitle(TitleName);
设置边框布局
this.setLayout(new BorderLayout());
不可拉伸
this.setResizable(false);
退出窗口就退出程序,不然会后台运行的
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
所有的布局方式
SWING – 布局 (w3schools.cn)
控件&区域设置
设置大小
Input_Text.setPreferredSize(new Dimension(335,30));
设置选中文字颜色
Input_Text.setSelectedTextColor(Color.BLUE);
设置字体颜色
Input_Text.setForeground(new Color(255,255,255));
设置字体大小样式
Input_Text.setFont(new Font(“粗体”,Font.BOLD,25));
设置背景颜色
Input_Text.setBackground(new Color(1,1,1));
设置边框颜色宽度
Input_Text.setBorder(BorderFactory.createLineBorder(Color.white,0));
添加到面板
北部区域添加输入框
JP_North.add(Input_Text);
北部添加到BorderLayout布局北部
this.add(JP_North, BorderLayout.NORTH);
针对输出框设置
自动换行
Input_Text.setLineWrap(true);
Input_Text.setWrapStyleWord(true);
获取值
FirstInputEast=Input_Text2.getText();
设置值
Input_Text2.setText(“”);
常见布局方式
GridLayout网格式
列,行,边框宽度
this.JP_West.setLayout(new GridLayout(6,3,0,0));
BorderLayout布局
监听器生成
this类监听
主函数扩展
implements ActionListener
添加监听器
btn.addActionListener(this);
创建类
public void AddCenterComponent(){
}
自定义监听
实例化
SimpleListener EastListener=new SimpleListener();
添加监听器
btn.addActionListener(EastListener);
创建类
public class SimpleListener implements ActionListener{
public void actionPerformed(ActionEvent e){
}
}
监听器操作
获取点击
String clickStr=e.getActionCommand();
主函数实例化swing
实例化
CalcMain calcMain=new CalcMain();
可视化,设为true就可以看到了
calcMain.setVisible(true);
原文地址:http://www.cnblogs.com/rabbitmind/p/16849412.html