一: 前言
java swing是一個(gè)用于開發(fā)java圖形界面應(yīng)用程序的開發(fā)工具包蛀序。它是以抽象窗口工具包(AWT)為基礎(chǔ)欢瞪,使跨平臺(tái)應(yīng)用程序可以使用任何可插拔的外觀風(fēng)格。swing開發(fā)人員通過使用少量的代碼徐裸,就可以利用swing包中豐富遣鼓、靈活的功能和模塊化組件類來開發(fā)出令人滿意的用戶界面了。接下來我們會(huì)用相關(guān)的例子來演示如何使用 java swing 開發(fā)圖形界面重贺。
二 :示例
1.0 ?如下圖 a 所示骑祟,制作一個(gè)計(jì)算器。
制作一個(gè)桌面的計(jì)算器气笙。
代碼如下:
package com.Swing.DeLongYang;
import javax.swing.*;
import java.awt.*;
//? 主要是布局嵌套
public class LayoutNesting extends JFrame {
//
public LayoutNesting(){
this.setBounds(50,50,250,250);
Container c=this.getContentPane();
JPanel panTop=new JPanel(new BorderLayout());
JPanel panMiddle= new JPanel(new GridLayout(4, 4, 10, 10));
JPanel panButtom= new JPanel(new FlowLayout(FlowLayout.CENTER));
// 布局頂部
panTop.add(new JTextField("計(jì)算結(jié)果"),BorderLayout.EAST);
panTop.add(new JButton("計(jì)算"),BorderLayout.WEST);
c.add(panTop, BorderLayout.NORTH);
// 布局中部
String []s="7,8,9,+,-,*,/,4,5,6,1,2,3,.".split(",");
for (int i=0; i<s.length;i++){
panMiddle.add(new JButton(s[i]));
}
c.add(panMiddle, BorderLayout.CENTER);
// 布局底部
panButtom.add(new JButton("關(guān)于產(chǎn)品"));
c.add(panButtom, BorderLayout.SOUTH);//
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args){
new LayoutNesting()
}
}
運(yùn)行就會(huì)出現(xiàn)這樣的 計(jì)算器界面次企。
2.0 ?制作一個(gè)簡(jiǎn)單的登錄界面
如下圖b 所示。
代碼如下潜圃。
package com.Swing.DeLongYang;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginFrame extends JFrame{
JLabel lable=new JLabel("用戶名");
JTextField userNameTextField=new JTextField();
JLabel passLable= new JLabel("密碼");
JTextField passTextField=new JTextField();
JButton loginBtn=new JButton("登錄");
JButton exitBtn=new JButton("關(guān)閉");
public LoginFrame(){
this.setBounds(50,50,250,150);
Container c=this.getContentPane();
c.setLayout(new GridLayout(3, 2, 10, 10));
c.add(lable);
c.add(userNameTextField);
c.add(passLable);
c.add(passTextField);
c.add(loginBtn);
c.add(exitBtn);
loginBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String name=userNameTextField.getText();
String pass=passTextField.getText();
if(name.equals("Tom")&&pass.equals("123")){
System.out.println("登錄成功");
}else{
System.out.println("用戶名或者密碼錯(cuò)誤");
}
}
});
exitBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.exit(0);
}
});
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args){
new LoginFrame();
}
}
運(yùn)行結(jié)果 想必 你已經(jīng)從代碼中看出來了缸棵。 如果輸入 Tom 和 123 就會(huì)有登錄成功輸出