【问题标题】:JPanel and JButtonJPanel 和 JButton
【发布时间】:2016-01-20 23:23:02
【问题描述】:

我正在使用 NetBeans 为我做一个小程序。我不需要在 JPanel 上创建许多 JButton,但我做不到。 JPanel 已由 NetBeans 编辑器在 JFrame 上生成(也由 NetBeans 编辑器生成)

这是代码:

public static ArrayList<Account> accounts = Account.accounts;
public verCuenta() {
    initComponents();
    panel.setVisible(true);
    Account ac;
    JButton button;

    int size= accounts.size();

    for(int i=0;i<size;i++){
        button = new JButton(accounts.get(i).getName());
        button.setVisible(true);
        button.addActionListener(null);
        button.setPreferredSize(new Dimension(50,30));
        panel.add(button);
    }

【问题讨论】:

  • 更改布局管理器,查看Laying Out Components Within a Container了解更多详情
  • 即使有这个帮助我也无法解决问题...我的意思是... JButton 不能打印在 JPanel 上?
  • 好吧,我假设 panel 已添加到您要显示它的任何容器中。考虑提供一个runnable example 来证明您的问题。这不是代码转储,而是您正在做的事情的一个例子,它突出了您遇到的问题。这将减少混乱并获得更好的响应

标签: java jpanel jbutton


【解决方案1】:

我设法让一个按钮弹出, 也许先从这个开始,然后尝试获得几个,然后让你的循环工作

// Create a new button:
JButton b1 = new JButton("ok");
// Set the location and size of the button:
b1.setSize(100, 26);
// Add the button to the window:
jPanel1.add(b1);
//Repaint the Panel to make visible
jPanel1.repaint();

它仅在您设置大小时有效,只需在 Netbeans 中检查。 您还可以指定位置,使用

b1.setLocation(100, 100);

顺便说一句,整个框架都是网格包布局

【讨论】:

    【解决方案2】:

    您需要将所有元素添加到面板中,然后调用setVisible 方法。

    调用setVisible 方法后的添加本身并未考虑在内。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-29
      • 2011-05-06
      • 2013-05-04
      • 2016-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多