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

时间:2018-03-30 16:56:35

标签: java swing jframe 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 个答案:

答案 0 :(得分:1)

您的问题是您忽略了布局管理器以及它们为组件大小调整所做的工作。您的JButton保存在一个使用GroupLayout的容器中,并按照该布局及其规则进行调整。如果您坚持进行绝对大小调整和定位,则必须将其保存在使用null布局的容器中。如果你不移动它,这可以是一个包装容器/ 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并使用更多程序员友好的布局。

另请注意,null布局和setBounds()在使用时会造成严重困难。当GUI调整大小时,他们不会调整组件的大小,他们是增强或维护的皇室女巫,当他们放置在滚动窗格中时,他们完全失败,当他们在所有平台或屏幕分辨率不同时看起来很糟糕原来的。

如此底线,

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

答案 1 :(得分:0)

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