我有以下代碼。如果我最大化applet的窗口,所有元素將在一行中排序。我想在一行上有一些元素,在另一行上有其他元素等等。我試圖創建面板,但它不起作用。爲了解決這個問題,我應該改變什麼?Java元素排列
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Numbers extends Applet implements ActionListener{
private Button b1,b2,b3;
private Label lb1,lb2,lb3;
private TextField tf1,tf2,tf3;
private Panel row1,row2,row3,row4,row5;
private Panel CreatePanel(LayoutManager layout_type)
{
Panel p=new Panel();
p.setLayout(layout_type);
return p;
}
public void init() {
setLayout(new FlowLayout(FlowLayout.LEFT,4,2));
row1=CreatePanel(new FlowLayout(FlowLayout.CENTER,4,2));
lb1=new Label("First number: ");
tf1=new TextField("",10);
row1.add(lb1);
row1.add(tf1);
add(row1);
row2=CreatePanel(new FlowLayout(FlowLayout.CENTER,2,2));
lb2=new Label("Second number: ");
row2.add(lb2);
tf2=new TextField("",10);
row2.add(tf2);
add(row2);
row3=CreatePanel(new FlowLayout(FlowLayout.CENTER,4,2));
b1=new Button("Multiply ");
b1.addActionListener(this);
row3.add(b1);
b2=new Button("Add");
b2.addActionListener(this);
row3.add(b2);
b3=new Button("Subtract");
b3.addActionListener(this);
row3.add(b3);
add(row3);
row4=CreatePanel(new FlowLayout(FlowLayout.CENTER,4,2));
row5=CreatePanel(new FlowLayout(FlowLayout.CENTER,5,2));
lb3=new Label("Result: ");
row5.add(lb3);
add(row5);
}
public void actionPerformed(ActionEvent e)
{
String txt1=tf1.getText();
String txt2=tf2.getText();
int n=Integer.parseInt(txt1);
int m=Integer.parseInt(txt2);
if(e.getSource()==b1)
lb3.setText("Result: "+n*m);
if(e.getSource()==b2)
lb3.setText("Result: "+(n+m));
if(e.getSource()==b3)
lb3.setText("Result: "+(n-m));
}
}
'FlowLayout'並排排列的組件側。如果沒有空間,則將組件移至下一行。這是'FlowLayout'的默認行爲。 – Braj
我應該使用什麼佈局管理器? – user3527276
在此處查找[佈局管理器視覺指南](http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html) – Braj