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

标签 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 类的实例,它有 2 个方法:

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 按钮的大小并重新定位)。第一个方法中的 JLabels 在第一次单击时更新,但只有在第二次单击时 posBar 按钮才会调整大小和重新定位。

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

我不知道这是否有帮助,但 JLabels 和 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
}

最佳答案

您的问题是您忽略了布局管理器以及它们对组件大小调整的作用。您的 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 调整大小时,它们不会调整组件的大小,它们是增强或维护的皇家女巫,放置在滚动 Pane 中时它们完全失败,在所有平台或与原始分辨率不同的屏幕分辨率上查看时,它们看起来非常糟糕.

<小时/>

所以底线,

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

关于Java swing,JButton 在第一次按下按钮时不会重新调整大小,但会在第二次按下时重新调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49578311/

相关文章:

java - 带有自定义边框的 JFrame 不显示控件

java - 捕获 Java 生成的 JFrame 弹出窗口

java - 开发在线多人游戏的方法?

java - Java 中的自定义绘画 - 将 UI 元素绘制到 JPanel 上

java - 我怎样才能将数据从一个 JPanel 传递到另一个...?

java - Swing Java 如何制作多个按钮,在单击时执行不同的任务

java - 新 JSONObject 中添加的 nameValuePair 键

java - 如何让一个被 ControllerAdvice 注解的类来处理不同类型的异常?

java - 使用 Mockito 根据参数从 void 方法抛出异常

java - 在不执行新 JFrame 的情况下刷新 JFrame Java