Java 在JFrame中的特定位置设置自定义JPanel

Java 在JFrame中的特定位置设置自定义JPanel,java,swing,user-interface,jpanel,netbeans-7,Java,Swing,User Interface,Jpanel,Netbeans 7,我在netbeans的GUI设计器中设计了一个GV框架,它有1个文本区域、2个文本框和1个JButton,位于框架的右侧。现在我想在这些组件左侧的GV框架中添加一个自定义JPanel。像这样: 直接在类内部构造的主网格面板 可以看出,我试图通过GUI编辑器通过自动生成的initComponents方法添加它,但它从未被添加,更不用说被放置在我想要的区域了。我不知道 我得到以下输出: 如果这是一个愚蠢的问题,请原谅,因为我是java的初学者。我无法通过在项目中创建一个扩展JPanel的类并初始化变

我在netbeans的GUI设计器中设计了一个GV框架,它有1个文本区域、2个文本框和1个JButton,位于框架的右侧。现在我想在这些组件左侧的GV框架中添加一个自定义JPanel。像这样:

直接在类内部构造的主网格面板

可以看出,我试图通过GUI编辑器通过自动生成的initComponents方法添加它,但它从未被添加,更不用说被放置在我想要的区域了。我不知道

我得到以下输出:


如果这是一个愚蠢的问题,请原谅,因为我是java的初学者。

我无法通过在项目中创建一个扩展JPanel的类并初始化变量来添加面板。原因是,我认为,我无法布置面板,因为我对布局-s知之甚少

所以,为了找到满足我的需要的方法,我为面板创建了一个类,然后将其添加到调色板管理器中,并从调色板设计了我的UI。这一次,我并不是在面板上画骰子。代码如下: GridPanel.java


现在它完成了。感谢所有帮助您的人。

提供一个指向您的屏幕截图的链接,我们将能够将其插入您的问题中。我看到您使用的是GroupLayout,它是为计算机生成的代码而构建的,非常有用,但很难手动使用。如果您正在创建手动布局,您通常会使用一个更易于使用的核心Java布局管理器或下载MigLayout。实际上,我主要是从这里和那里复制代码,而不知道如何适应我的面板,我对布局一无所知:但其余的不是复制。永远不要盲目复制代码,而是从代码中复制想法。我给你的建议是阅读。另外,请给我们一个链接,指向你上传到某处的图像,而不是HTML页面。我将阅读它,但由于我进行了大量测试,我认为当我试图通过GV.addmyGrid添加它时,我的面板的paintComponent从未被调用。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javafx.scene.shape.Circle;
import javax.swing.JPanel;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

    public class GV extends javax.swing.JFrame {
        boolean drawCircle = false;
        Circle circle;

        class Circle {
            Color c_color;
            int x, y, r;

            public Circle(int x, int y, int r, Color c_color) {
                this.x = x;
                this.y = y;
                this.r = r;
                this.c_color = c_color;
            }
        }

        JPanel myGrid = new JPanel(){
            public void paintComponent(Graphics g) {
                System.out.println("paint method called");
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D) g;
                if(!drawCircle){
                    g2.setPaint(Color.GRAY);
                    height = getSize().height;
                    width = getSize().width;
                    radius = (int) (Math.sqrt(height * width / 64) / 2);

                    for (int i = 1; i < 8; i++) {
                        int x = i * (height / 8);
                        g2.drawLine(x, 0, x, height);
                    }
                    for (int i = 1; i < 8; i++) {
                        int y = i * (width / 8);
                        g2.drawLine(0, y, width, y);
                    }
                }else{
                    g2.setColor(circle.c_color);
                    g2.fillOval(circle.x,circle.y,circle.r,circle.r);
                    System.err.println("Drawn @"+circle.c_color.toString()+"@"+circle.x+","+circle.y);
                    drawCircle=false;
                }
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(480, 480);
            }
        };

        Game game;
        DiceType[][] board;
        int height, width, radius;
        //List<Rectangle> Cells;

        /**
         * Creates new form GV
         */
        public void drawDices(){
            board = game.board.boardGrid;
            for(int i=0;i<8;i++){
                for(int j=0;j<8;j++){
                    if(board[i][j]!=DiceType.noDice){
                        drawDice(i+1, j+1, board[i][j]);
                    }
                }
            }
        }

        public void drawDice(int i, int j, DiceType dType){
            int x = (2*i-1)*(width/8)/2, y = (2*j-1)*(height/8)/2;;
            if(dType==DiceType.blackDice){
                circle = new Circle(x, y, radius, Color.BLACK);
            }else{
                circle = new Circle(x, y, radius, Color.WHITE);    
            }
            drawCircle=true;
            myGrid.revalidate();
            myGrid.repaint();
        }


        public void updateMovePanel(Player player){
            String moveStr="";
            for(Move move : player.Moves){
                moveStr+="["+move.xIndex+", "+move.yIndex+"]\n";
            }
            validMoveTextArea.setText(moveStr);
        }

        public GV() {

            //myGrid = new GridPanel();
            initComponents();

            //this.pack();
            game = new Game();
            drawDices();
            game.blackPlayer.findValidMoves();
            updateMovePanel(game.blackPlayer);
        }

        /**
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {

            xIndexField = new javax.swing.JTextField();
            yIndexField = new javax.swing.JTextField();
            chooseInputasMoveButton = new javax.swing.JButton();
            legalMoves = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            validMoveTextArea = new javax.swing.JTextArea();

            setLayout(new BorderLayout());
            //myGrid.setLayout(new BoxLayout(container, BoxLayout.X_AXIS));
            this.add(myGrid, BorderLayout.CENTER);
            xIndexLabel = new javax.swing.JLabel();
            yIndexLabel = new javax.swing.JLabel();

            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

            xIndexField.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    xIndexFieldActionPerformed(evt);
                }
            });

            chooseInputasMoveButton.setText("Choose Move");
            chooseInputasMoveButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    chooseInputasMoveButtonActionPerformed(evt);
                }
            });

            legalMoves.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            legalMoves.setText("Possible Moves");

            validMoveTextArea.setEditable(false);
            validMoveTextArea.setColumns(20);
            validMoveTextArea.setRows(5);
            validMoveTextArea.setEnabled(false);
            jScrollPane1.setViewportView(validMoveTextArea);

            xIndexLabel.setText("X(a-h):");

            yIndexLabel.setText("Y(1-8):");

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(416, 416, 416)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(0, 0, Short.MAX_VALUE)
                            .addComponent(xIndexLabel)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(xIndexField, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(yIndexLabel)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(yIndexField, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jScrollPane1)
                        .addComponent(legalMoves, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(chooseInputasMoveButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(legalMoves, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 340, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(yIndexField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(xIndexField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(xIndexLabel)
                        .addComponent(yIndexLabel))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(chooseInputasMoveButton)
                    .addContainerGap())
            );

            pack();
        }// </editor-fold>                        

        private void chooseInputasMoveButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                        
            // TODO add your handling code here:

            game.takeMove(Integer.getInteger(xIndexField.getText()), Integer.getInteger(yIndexField.getText()), game.blackPlayer);
        }                                                       

        private void xIndexFieldActionPerformed(java.awt.event.ActionEvent evt) {                                            
            // TODO add your handling code here:
        }                                           

        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(GV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(GV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(GV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(GV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>

            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new GV().setVisible(true);
                }
            });
        }

        // Variables declaration - do not modify                     
        private javax.swing.JButton chooseInputasMoveButton;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JLabel legalMoves;
        private javax.swing.JTextArea validMoveTextArea;
        private javax.swing.JTextField xIndexField;
        private javax.swing.JLabel xIndexLabel;
        private javax.swing.JTextField yIndexField;
        private javax.swing.JLabel yIndexLabel;
        // End of variables declaration                   
    }
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Shape;
import javax.swing.JPanel;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author fs71gh
 */

public class GridPanel extends JPanel{

    public void paintComponent(Graphics g) {

        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setPaint(Color.GRAY);
        for (int i = 1; i < 8; i++) {
            int x = i * (getHeight() / 8);
            g2.drawLine(x, 0, x, getHeight());
        }
        for (int i = 1; i < 8; i++) {
            int y = i * (getWidth() / 8);
            g2.drawLine(0, y, getWidth(), y);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(400, 400);
    }
}