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

标签 java swing user-interface jpanel netbeans-7

我在netbeans的GUI设计器中设计了一个GV框架,它有1个textArea、2个textBoxes和1个jButtons,它们位于框架内的右侧。现在我想在这些组件左侧的 GV 框架中添加一个自定义 JPanel。像这样:http://s25.postimg.org/3lggsdusf/Othe.png

enter image description here

主网格面板(直接在类内部构建

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                   
    }

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

我得到这个输出:http://s25.postimg.org/vmui6302n/problem_Figure.jpg

enter image description here

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

最佳答案

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

因此,为了找到一种方法来满足我的需求,我为面板创建了一个类,然后将其添加到调色板管理器并从调色板设计了我的 UI。这次,我不再通过面板来画骰子。这是代码: GridPanel.java

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);
    }
}

现在已经完成了。感谢所有提供帮助的人。

关于java - 在 JFrame 中的特定位置设置自定义 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26832615/

相关文章:

java - 分析 Java 应用程序 : Cumulative times for methods recursively

java - mongodb 中的多对多使用 spring 配置(首选注释)

java - GAE 实体组/事务

java - 如何制作六角形 JButton

user-interface - GUI和游戏程序流与Web程序相比如何

java - 为什么启动 GUI 时会出现 NullPointerException?

java - 如何保存 JTextArea 文本?

java - 如何将JDialog存储在JOptionPane创建的JDialog对象中

java - 防止 JPanel 在 repaint() 调用时重绘背景

javascript - slim 的路线给了我 404