Java 如何在gridlayout中的特定位置添加或删除JButton?
我想使用actionListener删除gridLayout的JButton。我想在删除的JButton的空白处留下,然后用JLabel或其他东西填充该空间Java 如何在gridlayout中的特定位置添加或删除JButton?,java,swing,jframe,actionlistener,grid-layout,Java,Swing,Jframe,Actionlistener,Grid Layout,我想使用actionListener删除gridLayout的JButton。我想在删除的JButton的空白处留下,然后用JLabel或其他东西填充该空间 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class bottons extends JFrame implements ActionListener{ private JPanel test; private JButton[
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class bottons extends JFrame implements ActionListener{
private JPanel test;
private JButton[][] buttons;
private JuegoBuca(){
setVisible(true);
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Test");
setResizable(false);
buttons = new JButton[5][5];
test = new JPanel();
test.setLayout(new GridLayout(5,5));
for(int i = 0 ; i<5 ; i++){
for(int j = 0; j<5 ; j++){
test.add(buttons[i][j] = new JButton(Integer.toString(index++)));
buttons[i][j].addActionListener(this);
}
}
add(test, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
for(int i = 0; i<5 ; i++){
for(int j = 0 ; j<5; j++){
if(buttons[i][j] == o){
test.remove(buttons[i][j]);
}
}
}
}
在actionListener方法中,它去掉JButton,但移动其他按钮并填充空间。索引只是在按钮中添加一些内容,使更改可见。
谢谢 您可以将具有CardLayout的JPanel添加到单元格中,而不是直接将按钮添加到GridLayout中。这将允许您向单元格中添加多张“卡”,并在它们之间切换。如果你想让单元格看起来是空的,那么一张“卡片”甚至可以是空的。因此,根据您的文档中介绍的概念,你需要知道要删除的组件在容器中的位置
@Override
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
Component[] components = test.getComponents();
for (int i = 0; i < components.length; i++) {
if (components[i] == o) {
// Remove the button that was clicked.
test.remove(i);
// Add a blank label in place of the button.
test.add(new JLabel(), i);
}
}
// Force Swing to repaint the panel.
test.repaint();
}
幸运的是,GridLayout根据每个组件的添加顺序进行布局。这意味着您只需确定当前组件在容器中的位置,然后再将其移除并将新组件添加到原来的位置
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
for(int i = 0; i<5 ; i++){
for(int j = 0 ; j<5; j++){
if(buttons[i][j] == o){
// Find the position of the component within the container
int index = getComponentZOrder(buttons[i][j]);
// Remove the old component
test.remove(buttons[i][j]);
// Replace it with a new component at the same position
add(new JLabel("I was here"), index);
}
}
}
}
例如,请参见您的,我只会对所有内容使用JButton实例,而不使用JLabel。当按钮看起来像什么东西时,设置一个图标。当它看起来像“什么都没有”时,只需在按钮上设置一个空白的透明图像作为图标,而不是第一个图标。因此,如果你花时间阅读我在你屏幕上留下的答案,你会看到答案-1,是的,这是主题的第三个或第四个问题,看起来另一个问题已被删除。不要在论坛上重复问题,注意你已经收到的答案。话虽如此,我不会创建ArrayList来搜索按钮,而是使用Container.getComponents方法,这样您就不需要在两个位置跟踪按钮。您的Answare非常好,谢谢,但千万不要使用ArrayList。@Pony,但是千万不要使用ArrayList——我在上面给了你一种替代方法。索引可能不代表容器中的按钮位置,你对@MadProgrammer关于索引的看法是正确的。我重写了我的答案,我相信它能解决问题。