简体   繁体   中英

JFrame, JPanel, and Gridlayout Issues

As a quick overview, my project involves taking a .txt file and converting that into a 2d array, then drawing it into a JFrame. As I was testing, I used JButtons instead of a custom class that will be built later. I have ran into two bugs that I don't know how to solve. For these pictures, this is all based on a Gridlayout that is 2 Rows and 16 Columes. When I add JButtons to the panel, it looks like this .

When I add them to the JFrame, it looks like this .

Here is my code for creating the JFrame and JPanel and rendering it:

    /**
 * This method creates a JFrame, JPanel, and then renders
 * all of the level in the JFrame
 */
public void render()
{
    JFrame frame = new JFrame("<Insert Title>");

    //Make it full screen for any computer monitor
    frame.setSize(JFrame.MAXIMIZED_HORIZ, JFrame.MAXIMIZED_HORIZ);
    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setUndecorated(true);
    frame.setVisible(true);


    JPanel panel = new JPanel(grid);
    frame.setLayout(grid);
    frame.add(panel);

    panel.getInputMap(IFW).put(KeyStroke.getKeyStroke("ESCAPE"), "quit");
    panel.getActionMap().put("quit", quit);

    //Draw!
    for(int row = 0; row < drawStuff.length; row++)
    {
        for(int col = 0; col < drawStuff[row].length; col++)
        {
            //Either panel.add or frame.add here
            panel.add(new JButton("Row :"+row+" Col: "+col));
        }
    }
    panel.revalidate();
    panel.repaint();
}

Anything that I am doing wrong here?

Thanks!

Remove frame.setLayout(grid); - this will allow the panel to occupy the entire content area of the frame, instead of been one row of one column

frame.setSize(JFrame.MAXIMIZED_HORIZ, JFrame.MAXIMIZED_HORIZ) really isn't doing what you think it is, not unless you want a frame which is 2x4

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