我修改了我的paint的for循环方法,该方法将JPanels方块绘制到与新添加的JPanels有关的所有内容都不像以前那样在for循环中,而是在它自己的称为addBlock(..)的方法中。在我这样做之后,JPanels 不再出现。
基本上我试图用这个程序做的是能够按需添加和删除 JPanel(由 60x60 块表示)。这就是我使用 ArrayList 的原因......所以我所要做的就是在之后调用 paint() 方法,它会根据我的 ArrayList 中有多少元素重新绘制。这是早期阶段,我还是新手,所以我什至不确定是否有更有效的方法。现在我只想展示一些东西。
这是我的代码:
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
class TestApp extends JFrame{
JFrame frame = new JFrame();
ArrayList<JPanel> grid = new ArrayList<JPanel>();
private static int amount = 10;
private void paint()
{
for(int i = 0, x = 0, y = 0; i < amount; i++, x += 62)
{
addBlock(i, x, y);
}
}
//Adds a block
private void addBlock(int index, int x, int y){
int height = 60;
int width = 60;
grid.add(new JPanel());
frame.add(grid.get(index));
(grid.get(index)).setVisible(true);
(grid.get(index)).setBounds(x, y, width, height);
}
//Removes a block
private void removeFrame(int index){
frame.remove(grid.get(index));
grid.remove(index);
}
//Default Constructor (sets up JFrame)
TestApp(){
frame.setLayout(null);
frame.setPreferredSize(new Dimension(600, 300));
frame.setTitle("Test Program");
frame.setBackground(Color.WHITE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setAlwaysOnTop(rootPaneCheckingEnabled);
frame.setResizable(true);
frame.setVisible(true);
}
public static void main(String [] args) {
TestApp program = new TestApp();
program.paint();
}
}
有什么想法或建议吗?
编辑:这是固定和改进的代码。我还没有实施其他建议的事情,因为我还没有做足够的研究。
package my;
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.LineBorder;
class TestApp extends JFrame{
JFrame frame = new JFrame();
ArrayList<JButton> grid = new ArrayList<JButton>();
private static int amount = 46;
private static int counter = 0;
private void paintGrid()
{
for(int i = 0, y = 4; i < ((amount / 10) + (amount % 10)); i++, y += 104)
{
for(int j = 0, x = 4; j < 10 && (counter < amount); j++, x += 84)
{
addBlock(counter, x, y);
counter++;
}
}
}
//Adds a block
private void addBlock(int index, int x, int y){
int height = 100;
int width = 80;
grid.add(new JButton());
(grid.get(index)).setBackground(Color.YELLOW);
(grid.get(index)).setBorder(new LineBorder(Color.BLACK));
(grid.get(index)).setVisible(true);
(grid.get(index)).setBounds(x, y, width, height);
frame.add(grid.get(index));
}
//Removes a block
private void removeBlock(int index){
frame.remove(grid.get(index));
grid.remove(index);
}
//Default Constructor (sets up JFrame)
TestApp(){
frame.setLayout(null);
frame.setPreferredSize(new Dimension(850, 600));
frame.setTitle("Test Program");
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setAlwaysOnTop(rootPaneCheckingEnabled);
frame.setResizable(false);
frame.setVisible(true);
}
public static void main(String [] args) {
TestApp program = new TestApp();
program.paintGrid();
}
}