Customize the JOptionPane layout with updated color and image in Java

Java 8Object Oriented ProgrammingProgramming

Customize the layout by changing the look and feel of the panel in which you added the component −

ImageIcon icon = new ImageIcon(new URL("http −//www.tutorialspoint.com/images/C-PLUS.png"));
JLabel label = new JLabel(icon);
JPanel panel = new JPanel(new GridBagLayout());
panel.add(label);
panel.setOpaque(true);
panel.setBackground(Color.ORANGE);

Above, we have added an image and even updated the background color of the panel.

Now, set it for the text panel −

JPanel textPanel = new JPanel(new GridLayout(10, 5)); textPanel.setBackground(Color.Magenta);

The following is an example to customize the JOptionPane layout −

Example

package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      ImageIcon icon = new ImageIcon(new URL("http −//www.tutorialspoint.com/images/C-PLUS.png"));
      JLabel label = new JLabel(icon);
      JPanel panel = new JPanel(new GridBagLayout());
      panel.add(label);
      panel.setOpaque(true); panel.setBackground(Color.ORANGE);
      JPanel textPanel = new JPanel(new GridLayout(10, 5)); textPanel.setBackground(Color.MAGENTA);
      for (int i = 0; i < 20; i++) {
         textPanel.add(new JLabel("Learn C++"));
      }
      JPanel panel2 = new JPanel(new BorderLayout());
      panel2.add(textPanel);
      panel2.add(panel, BorderLayout.EAST);
      JOptionPane.showMessageDialog(null, panel2, "Course",JOptionPane.DEFAULT_OPTION);
   }
}

Output

raja
Published on 04-Jun-2019 11:46:26
Advertisements