有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java swing,JButton在第一次按下按钮时不会调整大小,但在第二次按下按钮时会调整大小

下面是一个演示完全相同问题的小项目(仅2行):https://www.dropbox.com/s/fpgkrr7a4z1zdai/JButton%20problem.zip?dl=0

我在JFrame类中有一个按钮,代码如下:

correlation.performCalculations(numOfRows, corrResult)
correlation.displayGraph(posBar);

correlation是一个名为correlation的类的实例,它有两种方法:

public void performCalculations(JLabel numOfRows, JLabel corrResult) {
    numOfRows.setText("Number of records showing: " + filteredCars.size());
    //
    // some calculation code
    //
    correlationResult = (double) (topPartOfEquation / bottomPartOfEquation);
    corrResult.setText("Correlation: " + String.format("%.4f", correlationResult));
}


public void displayGraph(JButton posBar) {
    System.out.println("I am here");
    posBar.setSize(posBar.getWidth(), 92);
    posBar.setLocation(posBar.getLocation().x, (posBar.getLocation().y - 92));
}

所以我的问题是,当我第一次按下JFrame中的按钮时,它在输出中显示“我在这里”,但它不会重新调整按钮的大小或重新定位它,但是如果我再次按下它,它就会这样做(调整posBar按钮的大小并重新定位)。第一个方法中的jlabel在第一次单击中得到更新,但只有在第二次单击中posBar按钮才会调整大小并重新定位

在第一次和第二次按下按钮时,我会收到消息“我在这里”,但在第二次按下按钮时,它会在第二种方法中设置按钮的大小和位置。在第一次按下时,它不会对posBar按钮做任何操作

我不知道这是否有帮助,但jlabel和posBar按钮位于不同的面板中

任何帮助都将不胜感激。如果你有任何问题,请问我

public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        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">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jLabel1.setText("jLabel1");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addComponent(jLabel1)
                .addContainerGap(32, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addComponent(jLabel1)
                .addContainerGap(47, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jButton1.setText("posBar");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jButton1)
                .addContainerGap(23, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addComponent(jButton1)
                .addContainerGap(37, Short.MAX_VALUE))
        );

        jButton2.setText("Press Me (Twice)");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        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(51, 51, 51)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 55, Short.MAX_VALUE)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(43, 43, 43))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 83, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(51, 51, 51))
            .addGroup(layout.createSequentialGroup()
                .addGap(68, 68, 68)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        jLabel1.setText("Test");

        jButton1.setSize(20, 20);
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    // End of variables declaration//GEN-END:variables
}

共 (2) 个答案

  1. # 1 楼答案

    尝试使用JFrame.revalidate()JFrame.repaint()刷新界面,看看它是否有效

  2. # 2 楼答案

    你的问题是你忽略了布局管理器,以及它们对组件大小的影响。您的JButton保存在一个使用GroupLayout的容器中,并根据该布局及其规则调整大小。如果您坚持要进行绝对大小调整和定位,则必须将其保存在使用空布局的容器中。如果你不移动它,这可以是一个包装容器/JPanel

    例如:

    jButton1.setText("posBar");
    jButton1.setSize(jButton1.getPreferredSize()); // required if using null layout
    JPanel jButton1Panel = new JPanel(); // added
    jButton1Panel.setLayout(null); // generally frowned upon
    jButton1Panel.setPreferredSize(jButton1.getPreferredSize()); // so wrapper is same size as JButton
    jButton1Panel.add(jButton1); // add button to wrapper
    
    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addGap(22, 22, 22)
            .addComponent(jButton1Panel)  // ******* note change!! *******
            .addContainerGap(23, Short.MAX_VALUE))
    );
    jPanel2Layout.setVerticalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addGap(38, 38, 38)
            .addComponent(jButton1Panel)  // ******* note change!! *******
            .addContainerGap(37, Short.MAX_VALUE))
    );
    

    这只有在你把按钮变小的情况下才有效。对于更详细、更大的更改,您将希望避免使用GroupLayout,并使用更为程序员友好的布局

    还要注意的是,空布局和setBounds()在使用它们时会造成严重的困难。当GUI调整大小时,它们不会调整您的组件的大小,它们是一个需要增强或维护的皇家女巫,它们在滚动窗格中完全失败,在所有平台或屏幕分辨率与原始分辨率不同的情况下查看时,它们看起来非常糟糕


    所以底线是

    1. 为了使setSize(...)setLocation(...)(或组合为setBounds(...))工作,需要将组件放入使用null布局的容器中
    2. 但是话说回来,null布局是有问题的,因此如果可能的话,尝试寻找并使用更好的解决方案,确切的解决方案取决于GUI的确切要求