简体   繁体   中英

Java Swing 13 GridLayout does not exist?

I can't seem to get a swing GridLayout to work in java 13. The error is that GridLayout cannot be resolved to a type in the following code:

import javax.swing.*;
public class GameFrame extends JFrame {
    public static final void NewFrame() {
        new GameFrame();
    }
    public GameFrame() {
        this.setSize(1600, 800);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("The Game");
        this.setVisible(true);
        this.setResizable(false);
        JPanel MainPanel = new JPanel();
        MainPanel.setLayout(new GridLayout());
    }
}

The issue is caused by the class not being imported.

import java.awt.GridLayout;

Since it is not in the swing package it doesn't get imported with the star import. Also it is better to use explicit imports.

This might be related to the fact that panel is empty. Try running this code and it should work.

public class GridLayoutTest {

private static JButton[] arrayBtn;

public static void main(String[] args) {

    // the frame that contains the components
    JFrame frame = new JFrame("GridLayoutTest from JCG");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // set the size of the frame
    frame.setSize(350, 350);

    // set the rows and cols of the grid, as well the distances between them
    GridLayout grid = new GridLayout(5, 3, 10, 10);
    // what layout we want to use for our frame
    frame.setLayout(grid);

    // add a text field with a specified text to the frame
    JTextArea text = new JTextArea();
    text.setText("Result");
    text.setEditable(false);
    frame.add(text);

    // add buttons to the frame
    frame.add(new JButton("+"));
    frame.add(new JButton("="));

    arrayBtn = new JButton[10];
    // add JButtons dynamically
    for(int i=0; i < arrayBtn.length; i++) {
        arrayBtn[i] = new JButton(Integer.toString(i));
        frame.add(arrayBtn[i]);
    }

    frame.setVisible(true);

}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM