📄 example11_4.java
字号:
/* 堆栈演示 */
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class StackApp extends Frame implements ActionListener
{
Button btnNew,btnPush,btnPop;
TextField txt0;
Panel p1,p2;
TextField txt[]=new TextField[7];
Stack theStack=new Stack();
int i=1,k=0;
String s[]=new String[7];
StackApp()
{
super("** 堆栈演示 **");
setSize(400,200);
show();
btnNew=new Button("建立堆栈");
btnPush=new Button("Push(入栈)");
btnPop=new Button("Pop(出栈)");
txt0=new TextField(10);
btnNew.addActionListener(this);
btnPush.addActionListener(this);
btnPop.addActionListener(this);
setLayout(new BorderLayout());
p1=new Panel();
p2=new Panel();
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.CENTER);
p1.setLayout(new FlowLayout());
p1.add(btnNew);
p1.add(btnPush);
p1.add(btnPop);
p1.add(txt0);
btnPush.enable(false);
btnPop.enable(false);
p2.setLayout(new GridLayout(6,3));
for (i=6; i>=1; i--)
{
txt[i]=new TextField(10);
p2.add(new Label());
p2.add(txt[i]);
p2.add(new Label());
}
validate();
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource()==btnNew)
{
s[1]="思维论坛";
s[2]="Java爱好者";
s[3]="百度";
for (i=1; i<=3; i++)
{
theStack.push(s[i]);
txt[i].setText(s[i]);
k=k+1;
}
btnPush.enable(true);
btnPop.enable(true);
}
else if (e.getSource()==btnPush)
{
if (txt0.getText()!=null)
{
k++;
s[k]=txt0.getText();
theStack.push(s[k]);
txt[k].setText(s[k]);
}
}
else if (e.getSource()==btnPop)
{
if (!theStack.empty())
{
txt0.setText(s[k]);
s[k]="";
theStack.pop();
txt[k].setText(s[k]);
k--;
}
else
{
txt0.setText("堆栈是空的");
}
}
}
}
public class Example11_4
{
public static void main(String[] args)
{
new StackApp();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -