How to create Jbutton in "square" format?

Asked

Viewed 1,293 times

5

It is possible to create JButton in a "square" format, without the rounded corners when they are already in the JFrame? Does anyone have an example? I don’t use any specific laf, but the netbeans default. The JButtons is nothing different, are like in the image (I don’t know if it helps much). I tried to take JPanel, but it doesn’t change anything. There are some events in Jbuttons like mouse clicked, for example. The components are already in Jframe, I use no code for creation, as in the examples cited here.

inserir a descrição da imagem aqui

      package view;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 *
 * @author Rodrigo
 */
public class Empresa extends javax.swing.JFrame {

    /**
     * Creates new form Empresa
     */
    public Empresa() {
        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() {

        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                   
}
  • Would you be able to show how you’re doing it? Are you using any look and Feel or is the standard (metal)? You need this in some look and Feel specific? Have as you have, but in some cases the "square" button is already standard. Show a mcve so that we can reproduce.

  • Hello, thanks for the interest, I edited the question to see if I become clearer.

  • Man, I still don’t understand. The example of this question in Soen generates several buttons in a panel. Is there any way to post the code that generates the screen of this image you included? The buttons must be decorated (or are images), so you need to see the code it generates to help you.

  • I understand, follow the form code.

2 answers

5


The rounded edge of the button is due to the look and Feel that you are using. See the Techo of 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 called Nimbus (class javax.swing.plaf.nimbus.NimbusLookAndFeel) and if you think it will be used, if it will not be used the look and Feel pattern Metal (class javax.swing.plaf.metal.MetalLookAndFeel).

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

Botão Nimbus Original

As we already have why your buttons have the rounded appearance, we have some alternatives to change it as you need. They are:

  • use the look and Feel default, then you can comment/remove this snippet from your code:
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 use the standard aspect, which is the Metal, and the screen we are using as an example will look like this:

Botão Metal

  • use the look and Feel of the system. For this, replace the quoted section (which seeks the Nimbus) above by this:
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());

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

Botão Sistema

  • change the appearance of buttons on look and Feel Nimbus, configuring button properties with a new 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);
    }

}

Done this now we have to change the default properties of look and Feel which refer to the bottom of the buttons. I will change globally, so we will do this after the Nimbus is configured (after UIManager.setLookAndFeel(info.getClassName());), by changing the button properties they have backgroundPainter. The section was 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 simple screen example was like this:

Botão Nimbus Alterado

For more properties, check the document of components of Nimbus. Also, as you probably need a more stylized button, I suggest looking AbstractRegionPainter and also search for javax.swing.plaf.nimbus.ButtonPainter in its environment, which is a concrete implementation of AbstractRegionPainter, to make a Painter however you need to.

  • Oops, a lot of information, I’m going to work now, but I’ll see it as soon as I can, thank you very much.

  • It worked, I just had to remove the "Static modifier" in the Customnimbuspainter class and create an empty constructor. Is there a problem doing this? Another thing, to apply the effects of mouse Hover, pressed can I work in this same class ? What about other components like Jcombobox?

  • @Rodrigo not, can remove the static, the example I did in the same file, so the reason I did so, I’ll change it. You can use the same painer, just note that you may have different effects, so you may need to maintain some additional status (check the Painter original, it does something similar). As for other components, look at the link at the end that includes, it has the properties for all other components, including JComboBox (started with ComboBox)

-1

I think if I create Button in Jbutton ves it comes comic.

Goes below:

Button button = new Button("stack over");
button.setBounds(63, 167, 70, 22);
getContentPane().add(button);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.