1、第一個(gè)Swing程序——JFrame窗體
創(chuàng)新互聯(lián)主營類烏齊網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,App定制開發(fā),類烏齊h5微信小程序搭建,類烏齊網(wǎng)站營銷推廣歡迎類烏齊等地區(qū)企業(yè)咨詢
需要注意的是 JFrame窗體在初始設(shè)置的時(shí)候存在幾個(gè)問題:
1 窗體默認(rèn)不可見,需要設(shè)置成為可見
2 窗體默認(rèn)沒有大小,需要設(shè)置其大小
3 窗體默認(rèn)不能關(guān)閉,需要設(shè)置關(guān)閉方式
2、JFrame中添加面板、布局方式與控件
計(jì)算器:import java.awt.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.TextField;
import java.awt.Rectangle;
import java.awt.Button;
import java.awt.Label;public class suanfa extends JFrame {private static final long serialVersionUID = 1L;private JPanel jContentPane = null;private TextField textField = null;private TextField textField1 = null;private Button button = null;private Button button1 = null;private Button button2 = null;private Button button3 = null;private Label label = null;
double awn;
/**
* This is the default constructor
*/
public suanfa() {
super();
initialize();
}/**
* This method initializes this
*
* @return void
*/
private void initialize() {
this.setSize(300, 250);
this.setContentPane(getJContentPane());
this.setTitle("JFrame");
}/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
label = new Label();
label.setBounds(new Rectangle(12, 129, 90, 27));
label.setText(String.format("%.6f",awn));
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(getTextField(), null);
jContentPane.add(getTextField1(), null);
jContentPane.add(getButton(), null);
jContentPane.add(getButton1(), null);
jContentPane.add(getButton2(), null);
jContentPane.add(getButton3(), null);
jContentPane.add(label, null);
}
return jContentPane;
}/**
* This method initializes textField
*
* @return java.awt.TextField
*/
private TextField getTextField() {
if (textField == null) {
textField = new TextField();
textField.setBounds(new Rectangle(11, 20, 75, 32));
}
return textField;
}/**
* This method initializes textField1
*
* @return java.awt.TextField
*/
private TextField getTextField1() {
if (textField1 == null) {
textField1 = new TextField();
textField1.setBounds(new Rectangle(11, 67, 75, 32));
}
return textField1;
}/**
* This method initializes button
*
* @return java.awt.Button
*/
private Button getButton() {
if (button == null) {
button = new Button("加");
button.setBounds(new Rectangle(134, 17, 71, 29));
button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try{
awn=Double.valueOf(textField.getText()) + Double.valueOf(textField1.getText());
label.setText(String.format("%.6f",awn));
}
catch(Exception ex){
return;
}
}
});
}
return button;
}/**
* This method initializes button1
*
* @return java.awt.Button
*/
private Button getButton1() {
if (button1 == null) {
button1 = new Button("減");
button1.setBounds(new Rectangle(134, 52, 71, 29));
button1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try{
awn=Double.valueOf(textField.getText()) - Double.valueOf(textField1.getText());
label.setText(String.format("%.6f",awn));
}
catch(Exception ex){
return;
}}
});
}
return button1;
}/**
* This method initializes button2
*
* @return java.awt.Button
*/
private Button getButton2() {
if (button2 == null) {
button2 = new Button("乘");
button2.setBounds(new Rectangle(134, 91, 71, 29));
button2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try{
awn=Double.valueOf(textField.getText()) * Double.valueOf(textField1.getText());
label.setText(String.format("%.6f",awn));
}
catch(Exception ex){
return;
}}
});
}
return button2;
}/**
* This method initializes button3
*
* @return java.awt.Button
*/
private Button getButton3() {
if (button3 == null) {
button3 = new Button("除");
button3.setBounds(new Rectangle(134, 133, 71, 29));
button3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try{
awn=Double.valueOf(textField.getText()) / Double.valueOf(textField1.getText());
label.setText(String.format("%.6f",awn));
}
catch(Exception ex){
return;
}}
});
}
return button3;
}
public static void main(String[] args)
{
new suanfa().setVisible(true);
}
}
代碼缺一行:
。。。
authorTextArea.setPreferredSize(new Dimension(40, 80));
authorFrame.add(authorTextArea);
。。。
以上完了后,需要加一個(gè)
authorFrame.setVisible(true);
至于這個(gè)框的大小,你再調(diào)調(diào)哈,相互學(xué)習(xí)~,三年沒做過了~
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyMenu extends JFrame{
JMenuBar jmbar=new JMenuBar();
JMenu jmenu=new JMenu("顏色");
JMenuItem jmt1=new JMenuItem("紅色"),
jmt2=new JMenuItem("黃色"),
jmt3=new JMenuItem("藍(lán)色");
JPanel jp=new JPanel();
MyMenu(){
setTitle("菜單測試");
setSize(400,300);
setJMenuBar(jmbar);
jmbar.add(jmenu);
jmenu.add(jmt1);
jmenu.add(jmt2);
jmenu.add(jmt3);
add(jp);
jmt1.addActionListener(new MenuAction(this));
jmt2.addActionListener(new MenuAction(this));
jmt3.addActionListener(new MenuAction(this));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new MyMenu();
}
}
class MenuAction implements ActionListener{
MyMenu m;
MenuAction(MyMenu m){
this.m=m;
}
public void actionPerformed(ActionEvent e){
String color=e.getActionCommand();
if(color=="紅色")m.jp.setBackground(Color.red);
else if(color=="黃色")m.jp.setBackground(Color.yellow);
else if(color=="藍(lán)色")m.jp.setBackground(Color.blue);
}
}
不知道你要什么事件代碼,我寫了個(gè)比較簡單的你看適合不。
以windows系統(tǒng)中的記事本為例,菜單欄中的【文件】,【編輯】等全部叫一個(gè)菜單條;在Java中用JMenuBar表示;
菜單條中每一個(gè)具體的項(xiàng)叫做一個(gè)菜單,在Java中用JMenu表示;
菜單中的每一項(xiàng)叫做菜單項(xiàng),Java中用JMenuItem表示;
我們在窗體中創(chuàng)建菜單欄,首先需要?jiǎng)?chuàng)建菜單條,先聲明,然后在構(gòu)造方法中初始化;代碼為:JMenuBar bar = new JMenuBar();
然后創(chuàng)建菜單,也菜單條一樣,也是先聲明,再new;代碼為:JMenu menu = new JMenu("文件");
接下來創(chuàng)建菜單項(xiàng),和上面的一樣,先聲明,再new;代碼為:JMenuItem item = new JMenuItem("新建");
創(chuàng)建好每一個(gè)部分之后,我們需要將菜單項(xiàng)添加到菜單中,然后將菜單添加到菜單條中;代碼為:
menu.add(item);
bar.add(menu);
然后將整個(gè)菜單條添加到窗體中,代碼為:
this.setJMenuBar(bar);
這樣就可以實(shí)現(xiàn)在窗體中添加菜單條了,看一下效果吧。
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.awt.datatransfer.*;
class MyMenuBar extends MenuBar{
public MyMenuBar(Frame parent){
parent.setMenuBar(this);
}
public void addMenus(String [] menus){
for(int i=0;imenus.length;i++)
add(new Menu(menus[i]));
}
public void addMenuItems(int menuNumber,String[] items){
for(int i=0;iitems.length;i++){
if(items[i]!=null)
getMenu(menuNumber).add(new MenuItem(items[i]));
else getMenu(menuNumber).addSeparator();
}
}
public void addActionListener(ActionListener al){
for(int i=0;igetMenuCount();i++)
for(int j=0;jgetMenu(i).getItemCount();j++)
getMenu(i).getItem(j).addActionListener(al);
}
}
class MyFile{
private FileDialog fDlg;
public MyFile(Frame parent){
fDlg=new FileDialog(parent,"",FileDialog.LOAD);
}
private String getPath(){
return fDlg.getDirectory()+"\\"+fDlg.getFile();
}
public String getData() throws IOException{
fDlg.setTitle("打開");
fDlg.setMode(FileDialog.LOAD);
fDlg.setVisible(true);
BufferedReader br=new BufferedReader(new FileReader(getPath()));
StringBuffer sb=new StringBuffer();
String aline;
while((aline=br.readLine())!=null)
sb.append(aline+'\n');
br.close();
return sb.toString();
}
public void setData(String data) throws IOException{
fDlg.setTitle("保存");
fDlg.setMode(FileDialog.SAVE);
fDlg.setVisible(true);
BufferedWriter bw=new BufferedWriter(new FileWriter(getPath()));
bw.write(data);
bw.close();
}
}
class MyClipboard{
private Clipboard cb;
public MyClipboard(){
cb=Toolkit.getDefaultToolkit().getSystemClipboard();
}
public void setData(String data){
cb.setContents(new StringSelection(data),null);
}
public String getData(){
Transferable content=cb.getContents(null);
try{
return (String) content.getTransferData(DataFlavor.stringFlavor);
//DataFlavor.stringFlavor會(huì)將剪貼板中的字符串轉(zhuǎn)換成Unicode碼形式的String對象。
//DataFlavor類是與存儲(chǔ)在剪貼板上的數(shù)據(jù)的形式有關(guān)的類。
}catch(Exception ue){}
return null;
}
}
class MyFindDialog extends Dialog implements ActionListener{
private Label lFind=new Label("查找字符串");
private Label lReplace=new Label("替換字符串");
private TextField tFind=new TextField(10);
private TextField tReplace=new TextField(10);
private Button bFind=new Button("查找");
private Button bReplace=new Button("替換");
private TextArea ta;
public MyFindDialog(Frame owner,TextArea ta){
super(owner,"查找",false);
this.ta=ta;
setLayout(null);
lFind.setBounds(10,30,80,20);
lReplace.setBounds(10,70,80,20);
tFind.setBounds(90,30,90,20);
tReplace.setBounds(90,70,90,20);
bFind.setBounds(190,30,80,20);
bReplace.setBounds(190,70,80,20);
add(lFind);
add(tFind);
add(bFind);
add(lReplace);
add(tReplace);
add(bReplace);
setResizable(false);
bFind.addActionListener(this);
bReplace.addActionListener(this);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
MyFindDialog.this.dispose();
}
});
}//構(gòu)造函數(shù)結(jié)束
public void showFind(){
setTitle("查找");
setSize(280,60);
setVisible(true);
}
public void showReplace(){
setTitle("查找替換");
setSize(280,110);
setVisible(true);
}
private void find(){
String text=ta.getText();
String str=tFind.getText();
int end=text.length();
int len=str.length();
int start=ta.getSelectionEnd();
if(start==end) start=0;
for(;start=end-len;start++){
if(text.substring(start,start+len).equals(str)){
ta.setSelectionStart(start);
ta.setSelectionEnd(start+len);
return;
}
}
//若找不到待查字符串,則將光標(biāo)置于末尾
ta.setSelectionStart(end);
ta.setSelectionEnd(end);
}
public Button getBFind() {
return bFind;
}
private void replace(){
String str=tReplace.getText();
if(ta.getSelectedText().equals(tFind.getText()))
ta.replaceRange(str,ta.getSelectionStart(),ta.getSelectionEnd());
else find();
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==bFind)
find();
else if(e.getSource()==bReplace)
replace();
}
}
public class MyMemo extends Frame implements ActionListener{
private TextArea editor=new TextArea(); //可編輯的TextArea
private MyFile mf=new MyFile(this);//MyFile對象
private MyClipboard cb=new MyClipboard();
private MyFindDialog findDlg=new MyFindDialog(this,editor);
public MyMemo(String title){ //構(gòu)造函數(shù)
super(title);
MyMenuBar mb=new MyMenuBar(this);
//添加需要的菜單及菜單項(xiàng)
mb.addMenus(new String[]{"文件","編輯","查找","幫助"});
mb.addMenuItems(0,new String[]{"新建","打開","保存",null,"全選"});
mb.addMenuItems(1,new String[]{"剪貼","復(fù)制","粘貼","清除",null,"全選"});
mb.addMenuItems(2,new String[]{"查找",null,"查找替換"});
mb.addMenuItems(3,new String[]{"我的記事本信息"});
add(editor); //為菜單項(xiàng)注冊動(dòng)作時(shí)間監(jiān)聽器
mb.addActionListener(this);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
MyMemo.this.dispose();
}
}); //分號不能忘了
} //構(gòu)造函數(shù)完
public void actionPerformed(ActionEvent e){
String selected=e.getActionCommand(); //獲取菜單項(xiàng)標(biāo)題
if(selected.equals("新建"))
editor.setText("");
else if(selected.equals("打開")){
try{
editor.setText(mf.getData());
}catch(IOException ie){}
}
else if(selected.equals("保存")){
try{
mf.setData(editor.getText());
}catch(IOException ie){}
}
else if(selected.equals("退出")){
dispose();
}
else if(selected.equals("剪貼")){
//將選中的字符串復(fù)制到剪貼板中并清除字符串
cb.setData(editor.getSelectedText());
editor.replaceRange("",editor.getSelectionStart(),editor.getSelectionEnd());
}
else if(selected.equals("復(fù)制")){
cb.setData(editor.getSelectedText());
}
else if(selected.equals("粘貼")){
String str=cb.getData();
editor.replaceRange(str,editor.getSelectionStart(),editor.getSelectionEnd());
//粘貼在光標(biāo)位置
}
else if(selected.equals("清除")){
editor.replaceRange("",editor.getSelectionStart(),editor.getSelectionEnd());
}
else if(selected.equals("全選")){
editor.setSelectionStart(0);
editor.setSelectionEnd(editor.getText().length());
}
else if(selected.equals("查找")){
findDlg.showFind();
}
else if(selected.equals("查找替換")){
findDlg.showReplace();
}
}
public static void main(String[] args){
MyMemo memo=new MyMemo("記事本");
memo.setSize(650,450);
memo.setVisible(true);
}
}