How to create JButton in "square" format?

5

Is it possible to create JButton in a "square" format, without the rounded corners when they are already in JFrame ? Does anyone have an example? I do not use any specific laf, but the netbeans default. The JButtons is nothing different, they are like the image (I do not know if it helps a lot). I tried to remove JPanel , but it does not change anything. There are some events in JButtons like clicked mouse, for example. The components are already in JFrame, I do not use any code for creation, as in the examples above here .

packageview;importjava.awt.Graphics;importjava.awt.Image;importjava.awt.Toolkit;importjavax.swing.JOptionPane;importjavax.swing.JPanel;/****@authorRodrigo*/publicclassEmpresaextendsjavax.swing.JFrame{/***CreatesnewformEmpresa*/publicEmpresa(){initComponents();}/***Thismethodiscalledfromwithintheconstructortoinitializetheform.*WARNING:DoNOTmodifythiscode.Thecontentofthismethodisalways*regeneratedbytheFormEditor.*/@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel5 = 
        new JPanel(){
            public void paintComponent (Graphics g){
                Image img =Toolkit.getDefaultToolkit().getImage(
                    Principal.class.getResource("/images/ws_abstract_gray_bar.png"));
                g.drawImage(img, 0,0, this.getWidth(),this.getHeight(),this);
            }
        };
        jLBuscarRegistro = new javax.swing.JLabel();
        jTBuscarRegistro = new javax.swing.JTextField();
        jBLimpar = new javax.swing.JButton();
        jBusacarRegistro = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel5.setBackground(new java.awt.Color(153, 153, 153));
        jPanel5.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(0, 153, 153), null));
        jPanel5.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLBuscarRegistro.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        jLBuscarRegistro.setForeground(new java.awt.Color(255, 255, 255));
        jLBuscarRegistro.setText("Buscar:");
        jLBuscarRegistro.setPreferredSize(new java.awt.Dimension(20, 15));
        jPanel5.add(jLBuscarRegistro, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 10, 111, 36));

        jTBuscarRegistro.setToolTipText("Insira qualquer infromação ");
        jTBuscarRegistro.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 102, 102)));
        jPanel5.add(jTBuscarRegistro, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 10, 111, 36));

        jBLimpar.setForeground(new java.awt.Color(0, 102, 102));
        jBLimpar.setText("Limpar");
        jBLimpar.setBorder(null);
        jBLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBLimparActionPerformed(evt);
            }
        });
        jPanel5.add(jBLimpar, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 10, 111, 36));

        jBusacarRegistro.setForeground(new java.awt.Color(0, 102, 102));
        jBusacarRegistro.setIcon(new javax.swing.ImageIcon("D:\NetBeansProjects\SGInf\src\main\resources\images\help.png")); // NOI18N
        jBusacarRegistro.setBorder(null);
        jBusacarRegistro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBusacarRegistroActionPerformed(evt);
            }
        });
        jPanel5.add(jBusacarRegistro, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 10, 111, 36));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 492, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, 472, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(117, 117, 117)
                    .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, 65, Short.MAX_VALUE)
                    .addGap(118, 118, 118)))
        );

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

    private void jBLimparActionPerformed(java.awt.event.ActionEvent evt) {                                         
        jTBuscarRegistro.setText("");
    }                                        

    private void jBusacarRegistroActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        JOptionPane.showMessageDialog(null, "Insira informações");
    }                                                

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

    // Variables declaration - do not modify                     
    private javax.swing.JButton jBLimpar;
    private javax.swing.JButton jBusacarRegistro;
    private javax.swing.JLabel jLBuscarRegistro;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JTextField jTBuscarRegistro;
    // End of variables declaration                   
}
    
asked by anonymous 07.09.2015 / 16:20

2 answers

5

The rounded border of the button is due to the look and feel that you are using. See your code:

for (final javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
    if ("Nimbus".equals(info.getName())) {
        javax.swing.UIManager.setLookAndFeel(info.getClassName());
        break;
    }
}

Your program is looking for look and feel named Nimbus (class javax.swing.plaf.nimbus.NimbusLookAndFeel ) and if it finds it it will be used, if look and feel will not be used default Metal (class javax.swing.plaf.metal.MetalLookAndFeel ).

To illustrate how to change the behavior of the buttons in Nimbus I will use a screen that has only one button and use it as look and feel . The example is this:

Aswealreadyhavethewhyofyourbuttonsyouhavetheaspectleveled,wehavesomealternativestochangeitasyouneed.Theseare:

  • usedefaultlookandfeel,thenyoucancomment/removethissnippetfromyourcode:
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(Empresa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Empresa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Empresa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Empresa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); }

This will cause the default aspect, which is Metal , to be used, and the screen we are using as an example will look like this:

  • usethelookandfeelsystem.Todothis,replacethequotedpassage(whichlooksfortheNimbus)abovebythis:
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());

This will make it look like the look and feel of the system your application is running on, not a custom one. In my case, using Windows 10 this is the button face:

  • ChangetheappearanceofthebuttonsinthelookandfeelNimbus,settingthebuttonpropertieswithanew Painter . Here we will use a simple, like this:
public class CustomNimbusPainter implements Painter<JButton> {

    private final Color light = Color.WHITE;
    private final Color dark = Color.GRAY;
    private GradientPaint gradPaint;

    @Override
    public void paint(final Graphics2D g, final JButton button, final int width, final int height) {
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        this.gradPaint = new GradientPaint(width / 2.0f, 0, this.light, width / 2.0f, height / 2.0f, this.dark, true);
        g.setPaint(this.gradPaint);
        g.fillRect(2, 2, width - 5, height - 5);

        final Color outline = Color.BLACK;
        g.setColor(outline);
        g.drawRect(2, 2, width - 5, height - 5);
        final Color trans = new Color(outline.getRed(), outline.getGreen(), outline.getBlue(), 100);
        g.setColor(trans);
        g.drawRect(1, 1, width - 3, height - 3);
    }

}

Now we have to change the default look and feel properties that refer to the background of the buttons. I'm going to change globally, so let's do this after Nimbus is set (after UIManager.setLookAndFeel(info.getClassName()); ), changing the button properties that have backgroundPainter . The excerpt looks like this:

for (final UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
    if ("Nimbus".equals(info.getName())) {
        UIManager.setLookAndFeel(info.getClassName());
        final Painter<JButton> painter = new CustomNimbusPainter(Color.YELLOW, Color.RED);
        UIManager.getLookAndFeelDefaults().put("Button[Default+Focused+MouseOver].backgroundPainter", painter);
        UIManager.getLookAndFeelDefaults().put("Button[Default+Focused+Pressed].backgroundPainter", painter);
        UIManager.getLookAndFeelDefaults().put("Button[Default+Focused].backgroundPainter", painter);
        UIManager.getLookAndFeelDefaults().put("Button[Default+MouseOver].backgroundPainter", painter);
        UIManager.getLookAndFeelDefaults().put("Button[Default+Pressed].backgroundPainter", painter);
        UIManager.getLookAndFeelDefaults().put("Button[Default].backgroundPainter", painter);
        UIManager.getLookAndFeelDefaults().put("Button[Disabled].backgroundPainter", painter);
        UIManager.getLookAndFeelDefaults().put("Button[Enabled].backgroundPainter", painter);
        UIManager.getLookAndFeelDefaults().put("Button[Focused+MouseOver].backgroundPainter", painter);
        UIManager.getLookAndFeelDefaults().put("Button[Focused+Pressed].backgroundPainter", painter);
        UIManager.getLookAndFeelDefaults().put("Button[Focused].backgroundPainter", painter);
        UIManager.getLookAndFeelDefaults().put("Button[MouseOver].backgroundPainter", painter);
        UIManager.getLookAndFeelDefaults().put("Button[Pressed].backgroundPainter", painter);
        break;
    }
}

And that same example of a simple screen looks like this:

Formoreproperties,checkthe components file for Nimbus . Also, since you probably need a more stylized button, I suggest looking at AbstractRegionPainter "and also search for javax.swing.plaf.nimbus.ButtonPainter in your environment, which is a concrete implementation of AbstractRegionPainter , so you can do a Painter in any way you need.

    
07.09.2015 / 22:15
-1

I think if you create Button instead of JButton it comes in a square.

Follow below:

Button button = new Button("stack over");
button.setBounds(63, 167, 70, 22);
getContentPane().add(button);
    
22.09.2015 / 12:41