ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java – Jframe执行时尺寸不正确,有什么原因吗?

2019-09-28 05:03:44  阅读:164  来源: 互联网

标签:java swing netbeans jframe layout-manager


我正在制作一个游戏,但每当我运行第二个jFrame时,我必须调整它以便为第二个jFrame获得正确的大小,任何人都知道为什么?

这是第一个jFrame类中打开第二个方法的方法:

  private void playButtonMouseClicked(java.awt.event.MouseEvent evt) {                                        
        if (playerOneNameText.getText().equals(""))
        {
        }

        if (playerTwoNameText.getText().equals(""))
        {
        }
        else{
        pOneName = playerOneNameText.getText();
        pTwoName = playerTwoNameText.getText();

        ChessBoardUI class1 = new ChessBoardUI(); // Creating object of Class1
        class1.setVisible(true);

        this.setVisible(false);
        }
    } 

这是第二个jFrame类,我必须调整大小才能使ge tit正确:

package chess;

public class ChessBoardUI extends javax.swing.JFrame {

    public ChessBoardUI() {
        initComponents();
    }

    /**
     * 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() {

        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        blackTeamName = new javax.swing.JLabel();
        whiteTeamName = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(null);
        getContentPane().add(jLabel2);
        jLabel2.setBounds(21, 49, 0, 0);

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/chess/board.jpg"))); // NOI18N
        getContentPane().add(jLabel3);
        jLabel3.setBounds(0, 30, 400, 400);

        jLabel1.setText("Black:");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(400, 100, 34, 16);

        jLabel4.setText("White:");
        getContentPane().add(jLabel4);
        jLabel4.setBounds(400, 150, 38, 16);

        blackTeamName.setText("jLabel5");
        getContentPane().add(blackTeamName);
        blackTeamName.setBounds(400, 120, 41, 16);

        whiteTeamName.setText("jLabel5");
        getContentPane().add(whiteTeamName);
        whiteTeamName.setBounds(400, 170, 41, 16);

        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(ChessBoardUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ChessBoardUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ChessBoardUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ChessBoardUI.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 ChessBoardUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JLabel blackTeamName;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel whiteTeamName;
    // End of variables declaration
}

解决方法:

我很快就读到了寻找特定方法的内容.

那种方法是:

pack();

JFrame中的这个方法非常有用但也很难处理,你需要很好地理解如何设置每个组件的正确大小.使用“null”布局也可以轻而易举地完成所有工作.

我的建议是忘记使用

setLayout(null)

因为根据我的经验,它提供的结果很少比其他布局更好.

我可以告诉你的最好的事情是使用BoxLayout.使用此布局,您可以精确设置每个组件的位置和大小.诀窍还在于你可以使用rigidArea和Glue.

你的代码可以是:

// This is a BoxLayout with top to bottom orientation, the trick is to nest many JPanel
// with BoxLayout in both the direction to have all working
// What I want to achieve is:
//
//     1. Having a main box top to bottom where I will put:
//           - Top margin (a rigid area with dimension (0,MARGIN)
//           - Main JPanel with BoxLayout and LINE_AXIS (left to right) orientation
//           - Bottom margin (a rigid area like top margin)
//
//     2. In the main panel I will put:
//           - Left Margin (a rigid area with dimensions (MARGIN,0)
//           - A JPanel (leftPanel) Boxed top to bottom containing the things on the left that actually are jLabel3 and jLabel2
//           - A little separator between the two panel, a rigid area (10,0) i.e.
//           - A JPanel (rightPanel) Boxed top to bottom containing the remaining 4 JLabels
//           - Right Margin (as left)
//
//     3. In rightPanel JPanel (BoxLayout.PAGE_AXIS, top to bottom) I will have:
//           - a rigid area space to match the position that I want
//           - the first label
//           - a rigid area.. etc so on
//     
//     For each JLabel I must set all:
//           - setPreferredSize(dimension)
//           - setMinimumSize(dimension)
//           - setMaximumSize(dimension)
//
//     Then, if you specify also the JFrame is better, but you can try to pack().
//     BoxLayout take care of sizes, not exceeding maximum and not making it smaller than minimum. Yust try it and you will love it.

getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS);

JPanel main = new JPanel();
main.setLayout(new BoxLayout(main, BoxLayout.LINE_AXIS));

this.add(Box.createRigidArea(new Dimension(0,20))); // VERTICAL SPACE (top margin)
this.add(main);
this.add(Box.createRigidArea(new Dimension(0,20))); // VERTICAL SPACE (bottom margin)

JPanel rightPanel = new JPanel();
rightPanel.setLayout( new BoxLayout(rightPanel, BoxLayout.PAGE_AXIS));
JPanel leftPanel = new JPanel();
leftPanel.setLayout( new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS));

main.add(Box.createRigidArea(new Dimension(20,0))); // HORIZONTAL SPACE (left margin)
main.add(leftPanel);
main.add(Box.createRigidArea(new Dimension(10,0))); // HORIZONTAL SPACE (between the two)
main.add(rightPanel);
main.add(Box.createRigidArea(new Dimension(20,0))); // HORIZONTAL SPACE (right margin)

// now you should have understood how it works, just try to fill the right and left panel with your labels. Remember to set preferredm, maximum and minimum sizes.

我希望这对你有用
编辑,我想念一些“)”

标签:java,swing,netbeans,jframe,layout-manager
来源: https://codeday.me/bug/20190928/1826186.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有