简体   繁体   中英

JPanel subclass with gridLayout in Java

I have subclass(MyPanel) of JPanel that I'm using to draw lines between buttons. Drawing the line works but the problem is that when I'm using MyPanel instead of JPanel the gridLayout doesn't work. What I want from the gridLayout is the spacing between buttons and the choice of how they should be arranged. I've managed to position them in a grid without the gridLayout but I can't get the spacing to work. So what I need help with is either to get he gridLayout to work or a way to fix the spacing between the buttons without the gridLayout. The buttons I have are all added to the gameBoardPanel.

Edit: This is what it currently looks like:

在此处输入图片说明

What I want is to increase the spacing between the buttons with 25 pixels or so.

    class MyPanel extends JPanel {//The subclass
    public MyPanel(GridLayout gridLayout) {
        setPreferredSize(new Dimension(400,400));              
    }

    @Override
    public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        if(!drawline)  
            super.paintComponent(g);        

        else{
             g2.setStroke(new BasicStroke(3));
             g2.draw(new Line2D.Float(c,c,c2,d2));                  
        }
    }

This is the panel that the buttons are added too.

    gameBoardPanel=new MyPanel(new GridLayout(yAxis,xAxis,25,25));//creation of a panel        using MyPanel

I have no problem using the GridLayout with gaps. I'm not sure where your problem is occurring , but here's an example. I'm using layout of 5,5 with 25 gaps.

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


public class MyPanel extends JPanel{

    public MyPanel() {
        setLayout(new GridLayout(5, 5, 25, 25));
        for (int i = 0; i < 25; i++) {
            add(new JButton(" "));
        }
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame();
        frame.add(new MyPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();

            }
        });
    }
}

I used the same GridLayout you attempted to use. So I'm not really seeing where the problem is

在此处输入图片说明

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