【问题标题】:Do button have a placement in Applet java?按钮在 Applet java 中有位置吗?
【发布时间】:2014-05-24 14:44:57
【问题描述】:

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

我的代码:

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() 不起作用..

【问题讨论】:

  • 你想把按钮放在哪里?
  • 尝试做button1.setLocation(x,y); 然后也做button1.setBounds(x,y,button1.getWidth(),button1.getHeight()); x 和 y 值应该是一样的
  • @3kings 在您意识到自己的建议不可行之前,请不要提供有关 Java GUI 的建议。

标签: java button layout applet awt


【解决方案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);

【讨论】:

  • 是的,但我想把按钮放在某个地方,例如:s12.postimg.org/n26vn20dp/1111.png
  • 好的,让我改一下答案。
  • 抱歉,img 是什么?
  • 根据您的快照,您有一个图像和按钮。这里 img 代表一个具有图标集的标签。
猜你喜欢
  • 2012-06-07
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 2015-08-06
  • 2021-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多