Do按钮在Applet java中有位置吗?

时间:2014-04-10 18:08:59

标签: java button layout applet awt

如何将按钮放在正确的位置?

我的代码:

import java.applet.*;
import java.awt.*;

public class Banner extends Applet {

int x, y;

Button button1 = new Button("Try!");

public void init() {
    setSize(1200, 500);
    setLayout(new BorderLayout());  //also I tried FlowLayout..

            //button1.setBounds(500, 250, 25, 50); // not worked..

    add("East", button1); 

    button1.addActionListener(this);
}

public void start() {
}

public void paint(Graphics g) {
}

}

例如,我的Applet中有很少的标签和图像。我想把按钮放在某个地方.. 而且我想设置按钮的大小,但方法setSize()和方法setBounds()没有工作..

1 个答案:

答案 0 :(得分:1)

你试过吗?

add(button1,BorderLayout.EAST);

如果有多个组件,您可以尝试GridBagLayout

    setLayout(new GridBagLayout());
    GridBagConstraints gc = new GridBagConstraints();

    gc.gridy = 0;
    gc.anchor = GridBagConstraints.NORTH;

    Image image = ImageIO.read(new File("resources/Tulips.jpg"));
    JLabel label = new JLabel(new ImageIcon(image));
    JButton button1 = new JButton("Try!");

    gc.gridx = 0;
    gc.insets = new Insets(5, 5, 5, 5);
    add(label, gc);

    gc.insets = new Insets(50, 5, 5, 50);
    gc.gridx = 1;
    add(button1, gc);

您只需在新BorderLayout

中添加按钮,即可使用JPanel进行尝试
    Image image = ImageIO.read(new File("resources/Tulips.jpg"));
    JLabel label = new JLabel(new ImageIcon(image));

    setLayout(new BorderLayout(10,10));
    add(label, BorderLayout.CENTER);

    JPanel panel=new JPanel(new FlowLayout(FlowLayout.CENTER,50,10));
    JButton button1 = new JButton("Try!");
    panel.add(button1);
    add(panel, BorderLayout.EAST);