简体   繁体   English

JPanel和JButton

[英]JPanel and JButton

I'm doing a little program for me, with NetBeans. 我正在使用NetBeans为我编写一个小程序。 I need no create many JButtons on a JPanel but i can't do it. 我不需要在JPanel上创建许多JButton,但是我做不到。 The JPanel has been generated by the NetBeans editor on a JFrame (also made it by the NetBeans editor) JPanel由NetBeans编辑器在JFrame上生成(也由NetBeans编辑器生成)

This is the code: 这是代码:

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);
    }

I managed to get a single Button to pop up, maybe start with this first, then try to get several, then get your loop working 我设法弹出了一个按钮,也许首先从这个开始,然后尝试获取几个,然后使循环工作

// 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();

It only works when you set a size, just checked in Netbeans. 仅在设置大小(仅在Netbeans中检入)时才有效。 You can also specify the location, using 您也可以使用

b1.setLocation(100, 100);

btw, whole frame is in gridbag layout 顺便说一句,整个框架在网格袋布局

you need to add all elements to the panel and then call the setVisible method. 您需要将所有元素添加到面板中,然后调用setVisible方法。

Additions after calling the setVisible method are not per se taking into account. 本身不考虑调用setVisible方法之后的添加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM