+92 332 4229 857 99ProjectIdeas@Gmail.com

JButton Properties (Java)




The following code demonstrates the most common properties that we used on button, like setting size , displaying button name, clicking on it , pressing key etc..


Code


Displaying JButton Name: 

       // "Show" is a text displays on button
            JButton btnDisplay = new JButton("Show");

Setting JButton Size:
       // Setting Size Of Button Explicitly
            btnDisplay.setPreferredSize(new Dimension(100,50));

Clicking On JButton:

      // If user click on button then display some message
      // Using anonymous inner class
            btnDisplay.addActionListener(new ActionListener() {
                          
                  public void actionPerformed(ActionEvent ae) {
                          
                      JOptionPane.showMessageDialog(null, "Pressed Show Button");
                  }
           });

Pressing Key On JButton:
      // If user pressed key on button suppose it press "Enter Key"
           btnDisplay.addKeyListener(new KeyAdapter() {
                      
                  public void keyPressed(KeyEvent ke) {
                                 
                        if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
              
                            JOptionPane.showMessageDialog(null, "Hello World!!!");
                       }
                  }
           });

Changing JButton Font:
      // Changing Font Style, Making It bold and specifying font size
          btnDisplay.setFont(new Font("Comic Sans", Font.BOLD, 13));

Changing JButton Background Color:

     // Changing Button Background color
          btnDisplay.setBackground(Color.cyan);

0 comments: