📄 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 + -