简体   繁体   中英

Position JPanel on JFrame

I have a problem with JPanel location. I started the creating a small game... I created 2 panels in design (on a JFrame ). All worked good and the panels were on the correct places. In my game I have to use 2 graphic tables so I use 2 panels and I add every one of them panel set layout ( new Grid Layout(10,10) ).

After that I run the project to see how it works and I discover my panels in other places and with another size. I found the way that helps my to change back the size but I cannot found the way to change back the location or a way to give my own location...

I tried to add pictures that can show you what I see but the site blocked the pictures...

The code is:

public class GameFrame extends javax.swing.JFrame {
int [][]p1;
int [][]p1Attac;
int [][]p2;
int [][]p2Attac;
static int size=10;
int player;
JPanel [][]b1;
JPanel [][]b2;
int w=1100,h=900;

/**
 * Creates new form GameFrame
 * @param player1
 * @param player2
 */
public GameFrame(int [][]player1, int [][]player2) {
    initComponents();
   // setSize(w, h);
    setVisible(true);
  //  size=10;
    p1=new int[size][size];
    p1Attac=new int[size][size];
    p2=new int[size][size];
    p2Attac=new int[size][size];
    b1=new JPanel[size][size];
    b2=new JPanel[size][size];
    init(player1, player2);
    leftBoard.setBackground(Color.red);
    rightBoard.setBackground(Color.blue);
    GridLayout gl=new GridLayout(size, size);
    leftBoard.setLayout(gl);
    rightBoard.setLayout(gl);
    for(int i=0;i<size;i++){
        for(int j=0;j<size;j++){
            b1[i][j]=new JPanel();
            b1[i][j].setBorder(BorderFactory.createLineBorder(Color.black));
            b1[i][j].setBackground(Color.red);
            b2[i][j]=new JPanel();
            b2[i][j].setBorder(BorderFactory.createLineBorder(Color.black));
            b2[i][j].setBackground(Color.blue);
            leftBoard.add(b1[i][j]);
            rightBoard.add(b2[i][j]);
        }
    }
    leftBoard.setPreferredSize(new Dimension(w/2-50, h/2));
    rightBoard.setPreferredSize(new Dimension(w/2-50, h/2));
  //  leftBoard.setIgnoreRepaint(true);
 //   leftBoard.setLocation(0, h/5);
}
public void init(int [][]player1,int [][]player2){
    for(int i=0;i<size;i++){
        for(int j=0;j<size;j++){
            p1[i][j]=player1[i][j];
            p2[i][j]=player2[i][j];
            p1Attac[i][j]=0;
            p2Attac[i][j]=0;
        }
    }
}
/**
 * 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() {

    leftBoard = new javax.swing.JPanel();
    rightBoard = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    javax.swing.GroupLayout leftBoardLayout = new javax.swing.GroupLayout(leftBoard);
    leftBoard.setLayout(leftBoardLayout);
    leftBoardLayout.setHorizontalGroup(
        leftBoardLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 523, Short.MAX_VALUE)
    );
    leftBoardLayout.setVerticalGroup(
        leftBoardLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 498, Short.MAX_VALUE)
    );

    javax.swing.GroupLayout rightBoardLayout = new javax.swing.GroupLayout(rightBoard);
    rightBoard.setLayout(rightBoardLayout);
    rightBoardLayout.setHorizontalGroup(
        rightBoardLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 547, Short.MAX_VALUE)
    );
    rightBoardLayout.setVerticalGroup(
        rightBoardLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 498, Short.MAX_VALUE)
    );

    jLabel1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
    jLabel1.setText("Enemy Attacs:");

    jLabel2.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
    jLabel2.setText("Your Attacs:");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(57, 57, 57)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addComponent(leftBoard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(118, 118, 118)
                    .addComponent(rightBoard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addGap(193, 193, 193)
                    .addComponent(jLabel2)))
            .addContainerGap(43, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addGap(15, 15, 15)
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(3, 3, 3)
            .addComponent(leftBoard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addGap(22, 22, 22)
            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(rightBoard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(65, 65, 65))
    );

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

/**
 * @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(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>
    /*int [][]p1=new int[size][size];
    int [][]p2=new int[size][size];
    for(int i=0;i<size;i++)
        for(int j=0;j<size;j++){
            p1[i][j]=0;
            p2[i][j]=0;
        }
    p1[0][0]=p1[1][0]=p1[2][0]=p1[3][0]=4;
    p1[0][3]=p1[1][3]=p1[2][3]=3;
    p1[5][3]=p1[6][3]=p1[7][3]=3;
    p1[0][3]=p1[1][3]=2;*/
    int [][]p1={
        {4,4,4,4,0,1,0,0,0,0},
        {0,0,0,0,0,0,0,1,0,0},
        {3,3,3,0,3,0,0,0,0,0},
        {0,0,0,0,3,0,0,0,0,0},
        {2,2,0,0,3,0,0,1,0,0},
        {0,0,0,0,0,1,0,0,0,0},
        {0,0,0,0,0,0,0,2,2,0},
        {0,0,0,5,0,0,0,0,0,0},
        {0,0,0,0,0,0,5,0,2,2},
        {0,0,0,0,0,0,0,0,0,0}
    };
    int [][]p2={
        {0,1,0,0,1,0,0,2,2,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,1,0,1,0,2,2,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,5,0,0,3,0,0,2,0,0},
        {0,0,0,0,3,0,0,2,0,0},
        {0,0,0,0,3,0,0,0,0,0},
        {0,0,0,0,0,0,4,4,4,4},
        {0,3,3,3,0,0,0,0,0,0},
        {0,0,0,0,0,0,5,0,0,0}
    };
    new GameFrame(p1, p2);
    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
          //  new GameFrame().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel leftBoard;
private javax.swing.JPanel rightBoard;
// End of variables declaration                   
}

Thanks to @AndrewThompson for giving important ideas for this problem (GridLayout, Titled Borders). I've waited about 30 minutes to see if he'd post his own answer. He didn't, so I decided to post my own - I hope no-one is mad at me.


Don't use Grouplayout for this, IMO it just makes things complicated and user-unfriendly (at least in this case). Instead you can achieve everything with simple GridLayouts. (with much less code, resizeable) I've created an example that shows you how:

import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;

public class GameFrame {

    JPanel[][] arrayL = new JPanel[10][10];
    JPanel[][] arrayR = new JPanel[10][10];

    public GameFrame() {

        JFrame frame = new JFrame();
        frame.getContentPane().setLayout(new GridLayout(1, 2));

        JPanel left = new JPanel(new GridLayout(10, 10, 1, 1));
        left.setBorder(BorderFactory.createTitledBorder(new EmptyBorder(0, 0,
                0, 0), "Enemy"));
        ((TitledBorder) left.getBorder()).setTitleFont(new Font("Arial", Font.BOLD, 20));
        addCells(left, arrayL, Color.RED);

        JPanel right = new JPanel(new GridLayout(10, 10, 1, 1));
        right.setBorder(BorderFactory.createTitledBorder(new EmptyBorder(0, 0,
                0, 0), "You"));
        ((TitledBorder) right.getBorder()).setTitleFont(new Font("Arial", Font.BOLD, 20));
        addCells(right, arrayR, Color.BLUE);

        JPanel leftPanel = new JPanel();
        leftPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        leftPanel.setLayout(new GridLayout(1, 1));
        leftPanel.add(left);

        JPanel rightPanel = new JPanel();
        rightPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        rightPanel.setLayout(new GridLayout(1, 1));
        rightPanel.add(right);

        frame.getContentPane().add(leftPanel);
        frame.getContentPane().add(rightPanel);

        frame.setSize(500, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

    }

    public void addCells(JPanel panel, JPanel[][] array, Color color) {

        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {

                JPanel p = new JPanel();
                p.setBackground(color);
                p.setBorder(BorderFactory.createLineBorder(Color.BLACK));

                array[j][i] = p;

                panel.add(p);

            }
        }

    }

    public static void main(String[] args) {

        new GameFrame();

    }

}

One issue is that the initComponents() generated by the Netbeans GUI builder has layout which is being messed up by the code run later in the constructor. The way to fix this is using the Customize Code .. right-click menu option in the designer. Putting your code there will allow you to keep the outer design set by the Gui Builder and add internal custom components. After that you can comment out all the code in the constructor.

代码定制程序的屏幕截图

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