单击JFrame中的按钮后,在JPanel中添加板

时间:2019-07-14 04:35:44

标签: java swing

我是Swing的新手,并且正在玩intellij-我想在单击按钮后Add Board

将板/网格添加到JPanel中

我认为我了解JFrame,并添加了它们,但由于JPanel在JFrame内,我对如何在JPanel内部 渲染板非常迷惑。此刻,我将其渲染,但改为使用2个不同的JFrames:(

任何帮助将不胜感激!

I want the board to go inside the panel under Board

代码:

import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;

public class MainForm extends JPanel {

    private JPanel checkers;
    private JButton addboard;
    private JToolBar commands;
    private JPanel board;
    private JPanel stats;

    public MainForm() {

        addboard.addActionListener(e -> {

        });
    }

    @Override
    public void paint(Graphics g){

        g.fillRect(100, 100, 400, 400);
        for(int i = 100; i <= 400; i+=100){
            for(int j = 100; j <= 400; j+=100){
                g.clearRect(i, j, 50, 50);
            }
        }

        for(int i = 150; i <= 450; i+=100){
            for(int j = 150; j <= 450; j+=100){
                g.clearRect(i, j, 50, 50);
            }
        }
    }

    public static void main(String[] args){

        JFrame frame = new JFrame("checkers");
        frame.setLocationRelativeTo(null);
        frame.setContentPane(new MainForm().checkers);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.pack();
        frame.setVisible(true);
        frame.setResizable(false);

        JFrame frame2 = new JFrame();
        frame2.setSize(600,600);
        frame2.getContentPane().add(new MainForm());
        frame2.setLocationRelativeTo(null);
        frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame2.setVisible(true);

    }
}

0 个答案:

没有答案