如何解决无法垂直添加按钮
我正在编写一个程序,其中以垂直方式将JButton动态添加到JPanel。 (这些按钮存储在arraylist中)我通过将JPanel设置为gridbaglayout来尝试以下代码。
for(int i = 0; i<listofButtons.size();i++) {
c.gridx=0;
c.gridy=i;
leftButtonPanel.add(listofButtons.get(i));
}
结果如下
并添加按钮后
我还尝试将JPanel设置为gridlayout
leftButtonPanel.setLayout(new GridLayout(listofButtons.size(),1));
for(int i = 0; i<listofButtons.size();i++) {
leftButtonPanel.add(listofButtons.get(i));
}
按钮“查看全部”和“添加”都在同一listofButtons数组列表中。将按钮添加到面板的唯一方法是通过该forloop。由于某些原因,按钮仍会水平启动。
解决方法
对于GridBagLayout
,请不要忘记,您还需要提供GridBagConstraints
,否则它的作用很像FlowLayout
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SoTest {
public static void main(String[] args) {
new SoTest();
}
public SoTest() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
List<JButton> listOfButtons = new ArrayList<>(5);
for (int i = 0; i < 10; i++) {
listOfButtons.add(new JButton(Integer.toString(i)));
}
for (int i = 0; i < listOfButtons.size(); i++) {
add(listOfButtons.get(i),gbc);
}
}
}
}
在这一点上,我很好奇您是否应该考虑使用JList
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。