有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用GridBagLayout的带按钮的java填充框架

我试图建立一个匹配的游戏,每个按钮上都有图标。虽然,这还没有接近完成,但我在用按钮填充面板时遇到了一个问题

通过这个代码,我得到了一个灰色的框架。如果我在“//execution”下注释掉我使用的3种方法,面板将全部为黑色(这就是我测试按钮是否填充空间的方式)

因为某些原因,我的按钮没有被填充到面板上
我需要一些帮助!!!我哪里做错了

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MemoryMainFrame extends JFrame implements ActionListener {

    JButton button[] = new JButton[16];
    private static final int SIXTEEN_BUTTONS = 16;
    JPanel mainPanel = new JPanel();
    double dim = Math.sqrt(SIXTEEN_BUTTONS);
    int numOfColumns = (int) (dim);
    int numOfRows = (int) (dim);

    public static void main(String[] args) {
        new MemoryMainFrame();
    }

    public MemoryMainFrame() {

        this.setTitle("MemoryGame!!!");
        this.setSize(400, 400);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setVisible(true);

        mainPanel.setBackground(Color.BLACK);
        mainPanel.setLayout(new GridBagLayout());

        // execution
        FillButtonArray(SIXTEEN_BUTTONS);
        AddButtonListener(SIXTEEN_BUTTONS);
        ButtonToPanel(SIXTEEN_BUTTONS);

        this.add(mainPanel);
    }

    public void FillButtonArray(int numOfButtons) {
        int i = 0;

        while (i < numOfButtons) {
            button[i] = new JButton("asdf");
        }
    }

    public void AddButtonListener(int numOfButtons) {
        int i = 0;

        while (i < numOfButtons) {
            button[i].addActionListener(this);
        }
    }

    public void ButtonToPanel(int numOfButtons) {
        int n = 0;
        GridBagConstraints gbc = new GridBagConstraints();

        for (int i = 0; i < numOfColumns; i++) {
            for (int j = 0; j < numOfRows; j++) {

                gbc.gridx = i;
                gbc.gridy = j;
                n++;

                button[n].setBorder(BorderFactory.createLineBorder(
                        Color.DARK_GRAY, 2));
                mainPanel.add(button[n]);
            }
        }
    }

    public void actionPerformed(ActionEvent arg0) {

        JFrame j = new JFrame();
        j.setSize(300, 300);
        j.setVisible(true);
    }
}

我使用“asdf”作为测试,看看按钮是否也能正常工作

此外,执行的操作也是一项测试。这部分代码是不相关的


共 (1) 个答案

  1. # 1 楼答案

    您正在创建GridBagConstraints,但没有使用它们

    更改此项:

    mainPanel.add(button[n]);
    

    为此:

    // passes both the component and the GBC into the container
    mainPanel.add(button[n], gbc); 
    

    编辑
    这里还有一个永无止境的循环:

      while (i < numOfButtons) {
         button[i] = new JButton("asdf");
      }
    

    对于AddButtonListener(...)方法也是如此

    您需要通过使用for循环或在循环中更改i来修复此问题

    同样根据Andrew Thompson的评论,在添加所有组件之前,您将JFrame设置为可见太早了

    另外,使用Math.sqrt然后将结果强制转换为int是非常危险的,可能会得到意外的结果。如果需要,只需将边长声明为8并将整数平方即可

    有关GridBagLayout的示例,请查看:

    import java.awt.Color;
    import java.awt.Component;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    
    @SuppressWarnings("serial")  // avoid extending JFrame if possible
    public class MemoryMainPanel extends JPanel {
       private static final int ROWS = 8;
       private static final Color BACKGROUND = Color.black;
       private static final int I_GAP = 5;
       private static final Insets BTN_INSETS = new Insets(I_GAP, I_GAP, I_GAP, I_GAP);
       private JButton[][] buttons = new JButton[ROWS][ROWS];
    
    
       public MemoryMainPanel() {
          setBackground(BACKGROUND);
          setLayout(new GridBagLayout());
          for (int row = 0; row < buttons.length; row++) {
             for (int col = 0; col < buttons[row].length; col++) {
                JButton btn = new JButton(new ButtonAction(row, col));
                add(btn, createGbc(row, col));
                buttons[row][col] = btn;
             }
          }
       }
    
       private GridBagConstraints createGbc(int y, int x) {
          GridBagConstraints gbc = new GridBagConstraints();
          gbc.gridx = x;
          gbc.gridy = y;
          gbc.weightx = 1.0;
          gbc.weighty = 1.0;
          gbc.insets = BTN_INSETS;
          return gbc;
       }
    
       private class ButtonAction extends AbstractAction {
          private int row;
          private int col;
    
          public ButtonAction(int row, int col) {
             super("asdf");
             this.row = row;
             this.col = col;
          }
    
          @Override
          public void actionPerformed(ActionEvent e) {
             String text = String.format("Column, Row: [%d, %d]", col + 1, row + 1);
             Component parentComponent = MemoryMainPanel.this;
             String message = text;
             String title = "Button Pressed";
             int messageType = JOptionPane.PLAIN_MESSAGE;
             Icon icon = null;
             JOptionPane.showMessageDialog(parentComponent, message, title, messageType, icon);
          }
       }
    
       private static void createAndShowGui() {
          MemoryMainPanel mainPanel = new MemoryMainPanel();
    
          JFrame frame = new JFrame("MemoryMainPanel");
          frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }