【发布时间】:2020-11-21 21:03:34
【问题描述】:
所以我试图在框架底部的网格中放置 10 个按钮(不使用布局管理器),由于某种原因,我无法弄清楚为什么这不起作用,我想知道是否有人可以提供帮助。
我可能应该解释一下代码:
基本上我刚刚创建了一个循环,其中存储了一个“while”,这个 while 在结束并返回循环之前重复了 3 次。一段时间结束后,Y 变化 85 为接下来的 3 个按钮开始一个新图层。循环重复 4 次以创建 4 个不同的层,每层 10 个按钮。
谢谢!
主要
public class Main {
private static JFrame frame = new JFrame();
private static JPanel panel = new JPanel();
public static void main(String[] args) {
Buttons.setButtons(frame, panel);
Window.setFrame(frame, panel);
}
}
按钮
public class Buttons {
private static JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9;
private static JButton equals;
private static JButton minus;
private static JButton plus;
private static int i = 0;
private static int x = 10;
private static int y = 140;
private static JButton buttons[] = {b0, b1, b2, b3, b4, b5, b6, b7, b8, b9};
public static void setButtons(JFrame frame, JPanel panel) {
for (int b = 0; b < 4; b++) {
while (i < 3) {
buttons[i] = new JButton(Integer.toString(i));
buttons[i].setBounds(x, y, 80, 80);
x = x + 85;
buttons[i].setFocusable(false);
buttons[i].setBackground(Color.GRAY);
panel.add(buttons[i]);
i++;
}
y = y + 85;
x = 10;
}
System.out.print(y);
frame.setVisible(true);
}
}
窗口
public class Window {
public static void setFrame(JFrame frame, JPanel panel) {
frame.setSize(370, 525);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
panel.setBounds(10, 140, 200, 200);
panel.setBackground(Color.DARK_GRAY);
frame.add(panel);
}
}
【问题讨论】:
-
在您的
while循环中,将i < 3替换为i < 10 && i < (i + 3)。
标签: java swing jpanel jbutton layout-manager