【java】java swing初识:事件触发&登陆界面

来源:互联网 发布:淘宝内衣买家秀看不到 编辑:程序博客网 时间:2024/04/28 08:44
欢迎大家到我的个人主页点击打开链接,一起交流、学习,一起进步~
1.界面输出字符:hello world!
package vaniot.com;import javax.swing.*;public class HelloWorld {public static void createAndShow(){//好看的界面风格JFrame.setDefaultLookAndFeelDecorated(true);//创建及设置窗口JFrame frame=new JFrame("HelloWorld");//使JTable中关闭窗口后让后台程序也一起关闭,若缺少内存将会越占越满frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//窗口显示的内容JLabel label=new JLabel("hello world!");frame.getContentPane().add(label);//显示窗口frame.pack();frame.setVisible(true);}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stub//显示窗口javax.swing.SwingUtilities.invokeLater(new Runnable(){public void run(){createAndShow();}});}}
效果截图:

2.界面由按钮触发,输出字符:hello world!!
package vaniot.com;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JTextField;public class HelloWorld2 {public static void main(String[] args)throws Exception{NewFrame frame=new NewFrame();frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);frame.setVisible(true);}}class NewFrame extends JFrame{private JButton button;private JTextField text;public NewFrame(){super();this.setSize(300,300);//布局this.getContentPane().setLayout(null);//添加按钮this.add(this.getButton(),null);this.add(this.getText(),null);this.setTitle("hello world");}private JButton getButton() {// TODO Auto-generated method stubif(button==null){button=new JButton();button.setBounds(20,20,50,20);button.setText("hi");//添加监听类button.addActionListener(new HelloButton());}return button;} private JTextField getText(){ if(text==null){ text=new JTextField(); text.setBounds(20,50,100,20); } return text; }private class HelloButton implements ActionListener{public void actionPerformed(ActionEvent e){//System.out.println("hello world!!");text.setText("hello world!!");}}}
效果截图:

3.用户登录界面,输入用户名及密码
package vaniot.com;import javax.swing.*;public class LoginExample {public static void placeComponents(JPanel panel){//布局管理器panel.setLayout(null);//user:JLabel userlabel=new JLabel("User:");//设置组件位置,setBounds(x,y,width,height)userlabel.setBounds(10,20,80,25);panel.add(userlabel);//创建文本域用于用户输入JTextField usertext=new JTextField(20);usertext.setBounds(100,20,165,25);panel.add(usertext);//password:JLabel pwlabel=new JLabel("password:");pwlabel.setBounds(10,60,80,25);panel.add(pwlabel);//password输入域,输入以点号代替JPasswordField pwtext=new JPasswordField(20);pwtext.setBounds(100,60,165,25);panel.add(pwtext);//登录按钮JButton loginButton=new JButton("login");loginButton.setBounds(10,100,80,25);panel.add(loginButton);}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubJFrame frame=new JFrame("login example");//设置窗口大小frame.setSize(400,400);frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);//创建面板JPanel panel=new JPanel();frame.add(panel);placeComponents(panel);//界面可见frame.setVisible(true);}}
效果截图:
0 0
原创粉丝点击