?? buttondemo.java
字號:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonDemo extends JFrame
implements ActionListener{
private JButton btnLeft;
private JButton btnRight;
private JButton btnUp;
private JButton btnDown;
private JTextField tfMove;
int x,y;//用于控制文本框的顯示位置
private JPanel movePanel;
private Container container = getContentPane();
public ButtonDemo() {
super("位圖按鈕");
setSize(260, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//創建向移動的圖格按鈕
Icon icLeft=new ImageIcon("left.gif");
btnLeft=new JButton(icLeft);
//注冊監聽器
btnLeft.addActionListener(this);
//設置提示字符串
btnLeft.setToolTipText("控制文本向左移動");
//設置向右移動的按鈕
Icon icRight=new ImageIcon("right.gif");
btnRight=new JButton(icRight);
btnRight.addActionListener(this);
btnRight.setToolTipText("控制文本向右移動");
//設置向上移動的按鈕
Icon icUp=new ImageIcon("Up.gif");
btnUp=new JButton(icUp);
btnUp.addActionListener(this);
btnUp.setToolTipText("控制文本框向上移動");
//設置向下移動的按鈕
Icon icDown=new ImageIcon("Down.gif");
btnDown=new JButton(icDown);
btnDown.addActionListener(this);
btnDown.setToolTipText("控制文本框向下移動");
tfMove=new JTextField("位圖按鈕示例");
movePanel=new JPanel();
}
public void setLayout(){
container.setLayout(new BorderLayout());
container.add(btnLeft,BorderLayout.WEST);
container.add(btnRight,BorderLayout.EAST);
container.add(btnUp,BorderLayout.NORTH);
container.add(btnDown,BorderLayout.SOUTH);
//設置移動面板的布局為null;
movePanel.setLayout(null);
movePanel.add(tfMove);
//設置文本框的顯示位置
x=0;
y=0;
tfMove.setBounds(x,y,80,20);
container.add(movePanel,BorderLayout.CENTER);
}
public static void main(String[] args) {
ButtonDemo frame = new ButtonDemo();
frame.setLayout();
frame.show();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() ==btnRight){
x+=2;//控制文本框在水平方向上向右移動
}
if (e.getSource()==btnLeft){
x-=2;//向左移動
}
if(e.getSource()==btnUp){
y-=2;//向上移動
}
if(e.getSource()==btnDown){
y+=2;//向下移動
}
//重新調整文本框的位置
tfMove.setBounds(x,y,80,20);
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -