How to create a new JFrame with dynamic JLabels & JButtons without encountering NullPointerException?

How to create a new JFrame with dynamic JLabels & JButtons without encountering NullPointerException?

By : Rincy Raphael
Date : November 22 2020, 10:33 AM
Any of those help When you create an array, it creates n number of empty/uninitialised slots
So when you do something like...
code :
rLabels = new java.awt.Label[miniList1.size() + miniList2.size()];
for (int g=0;g<rLabels.length;g++)
    rLabels[g] = new JLabel();

Share : facebook icon twitter icon
Creating dynamic JLabels and JButtons

Creating dynamic JLabels and JButtons

By : Kpsl
Date : March 29 2020, 07:55 AM
Any of those help If you want to implement action listeners for your buttons, you can simply create and add a new ActionListener while creating the button.
Example :
code :
for (int i = 0; i < jLabel.length; i++) {
    final String str = jLabel[i];
    JLabel labels = new JLabel(str);
    JButton button = new JButton(jButton[i]);
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(panel, str);
Nullpointerexception when adding an array of JButtons to a JFrame

Nullpointerexception when adding an array of JButtons to a JFrame

By : Mendis Jhon
Date : March 29 2020, 07:55 AM
hop of those help? Well, you never initialize your gamescreen variable, so that's totally normal you get a NullPointerException at this line.
How to move JButtons and JLabels position in a JPanel, JFrame

How to move JButtons and JLabels position in a JPanel, JFrame

By : user2124860
Date : March 29 2020, 07:55 AM
To fix the issue you can do Instead of using a FlowLayout, which rearranges items automatically based on their sizes and the window size, you can use a BorderLayout or GridLayout. A BorderLayout basically splits the window into 5 areas, each border is a separate area identified with a cardinal direction (north, east, etc.), and the center is it's own area as well. A GridLayout allows you to specify if you want a particular number of rows/columns, while letting the other expand as necessary (n elements into 2 columns, for example).
From the look of your photoshopped desired outcome, you can use a BorderLayout for the main frame, with the buttons in the north, the number/results in the center, and the table in the south. Also remember that you can put a panel in a layout area, with that panel having its own layout, such as a GridLayout for the buttons in the north, or even better, for the table in the south. Hope that helps!
code :
JFrame frame = new JFrame("The Lottery");
JPanel mainPanel = new JPanel(new BorderLayout());

JPanel northPanel = new JPanel();
JButton play = new JButton("Play");
JButton exit = new JButton("Exit");
mainPanel.add(northPanel, BorderLayout.NORTH);
How to set a background color to a JFrame containing multiple JPanels, JButtons and JLabels?

How to set a background color to a JFrame containing multiple JPanels, JButtons and JLabels?

By : user3435255
Date : March 29 2020, 07:55 AM
help you fix your problem Set the main content pane JPanel's background to whatever color you desire, Color.BLUE. Make all other JPanels that is displayed in your main GUI non-opaque by calling setOpaque(false) on all of them (although I do find it hard that none of "the solutions proposed here" told you this. This will allow the background color of the contentPane to show through.
Also some side recommendations:
code :
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
//!! import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextPane;

public class Simplicity {

    public Simplicity() {


    public static void main(String[] args) {

        Body fen = new Body();



class Body extends JFrame{

   private static final long serialVersionUID = 1L;

   private static final int FRAME_WIDTH = 250;
   private static final int FRAME_HEIGHT = 400;

   private static JPanel niveauBase = new JPanel(); // Basic panel -> everything will go on it
   private static JPanel infosReseauxHeure = new JPanel(); // Panel fixed
   private JPanel panelChangeable = new JPanel(); // Scrolling panel

   // up of page info
   private static JTextPane infos = new JTextPane();

   // Creation of the different pages (panels)
   private Tutoriel tuto;

   public Body() {
   public void buildFrame() {
       this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
       this.getContentPane().setBackground(new Color(255, 105, 86));

       // toutes les dimensions sont en relatif par rapport à la taille de la JFrame. de fait, en changeant celle-ci, on peut adapter l'interface à différents écrans      

       // on met en place ce qui ne changera jamais d'un panel à l'autre --> les infos de base et le support
           // support
       niveauBase.setBackground(Color.blue); //!!

           // basic info
       infosReseauxHeure.setBounds(0, 0, this.getWidth(), (int)(0.12*this.getHeight()));
       infosReseauxHeure.setLayout(new GridLayout(0,1));

           // adding the text

       // defining the limits of the changing Panel, bc they are always the same
       // My first try of changing the background 
//     panelChangeable.setBackground(new Color(255, 105, 86));
       panelChangeable.setBounds(0, infosReseauxHeure.getHeight(), this.getWidth(), (int) (0.88*this.getHeight()));

       // the basic frame, which will never change, is ready.

   public void buildContentPane() {

       // Instantiation of the pages

       tuto = new Tutoriel(this);
       ac1 = new Accueil1(this);
       ac2 = new Accueil2(this);
       med1 = new Medias1(this);
       multimed1 = new Multimedias1(this);
       out1 = new Outils1(this);
       out2 = new Outils2(this);
       jeux1 = new Jeux1(this);
       jeux2 = new Jeux2(this);
       socInt1 = new SocialInternet1(this);
       socInt2 = new SocialInternet2(this);

       appeler = new Appeler(this);
       urgences = new Urgences(this);

       appelEnCours = new AppelEnCours(this);
       demarrageApp = new DemarrageApp(this);
       enConstruction = new EnConstruction(this);

       // Tutoriel is the first to be displayed

       // all the other panels have the same displaying characteristics
       // navigating panels

       // applications panels

       // diverse panels
   // fixating the same size and origins for all the panels
   public void CaractsPanelChangeant(JPanel a) {

       a.setBounds(0, 0, panelChangeable.getWidth(), panelChangeable.getHeight());
   // regroup the same actions for the panels : bounds, adding and invisible
   public void addPanels(JPanel a) {
        * I tried to change the background here too
       a.setBackground(new Color(255, 105, 86));

   // JPanel getters
   public static int getInfosReseauxHeureHeight() {
       return infosReseauxHeure.getHeight();
   public Accueil1 getAc1() {
       return ac1;
   public Accueil2 getAc2() {
       return ac2;
   public Medias1 getMed1() {
       return med1;
   public Multimedias1 getMultimed1() {
       return multimed1;
   public Outils1 getOut1() {
       return out1;
   public Outils2 getOut2() {
       return out2;
   public Jeux1 getJeux1() {
       return jeux1;
   public Jeux2 getJeux2() {
       return jeux2;
   public SocialInternet1 getSocInt1() {
       return socInt1;
   public SocialInternet2 getSocInt2() {
       return socInt2;

   public Appeler getAppeler() {
       return appeler;
   public Urgences getUrgences() {
       return urgences;
   public AppelEnCours getAppelEnCours() {
       return appelEnCours;
   public DemarrageApp getDemarrageApp() {
       return demarrageApp;
   public EnConstruction getEnConstruction() {
       return enConstruction;
   public Tutoriel getTuto() {
       return tuto;

   // other getters
   public static int getFrameWidth() {
       return FRAME_WIDTH;
   public static int getFrameHeight() {
       return FRAME_HEIGHT;
   public JPanel getPanelChangeable() {
       return panelChangeable;

   // setters
   public void setPanelChangeable(JPanel a) {
       this.panelChangeable = a;
   public void switchAccueil(){

class Tutoriel extends JPanel {

   private static final long serialVersionUID = 1L;

   private Body body;

   // panels
   private JPanel tout;
   private JPanel centre;
   private JPanel messageCentre1;
   private JPanel messageCentre2;

   // buttons
   private JButton ok1;
   private JButton ok2;

   private JLabel messageHaut;
   private JLabel tuto1;
   private JLabel FGauche;
   private JLabel FDroite;
   private JLabel tuto2;
   private JCheckBox tutoOff;

   //private Color fond = new Color(255, 105, 86);

   public Tutoriel(Body body) {
       this.body = body;
   public void buildTuto() {

       this.setLayout(new GridLayout(0,1));
       tout = new JPanel();
       tout.setOpaque(false); //!!
       tout.setLayout(new BorderLayout(0,0));

       // tutorial announce
       messageHaut = new JLabel("TUTORIEL");
       messageHaut.setForeground(new Color(0, 0, 0));
       messageHaut.setFont(new Font("Arial", Font.BOLD, 20));
       tout.add(messageHaut, BorderLayout.NORTH);

       // central panel, with the tutorial
       centre = new JPanel();
       tout.add(centre, BorderLayout.CENTER);

       // first tutorial
       messageCentre1 = new JPanel();
       messageCentre1.setBounds(0, 0, 250, 300);

       tuto1.setForeground(new Color(0, 0, 0));
       tuto1.setFont(new Font("Arial", Font.BOLD, 16));
       tuto1.setBounds(20, -10, 200, 150);

       // arrows
       FGauche = new JLabel("G");
       //!! FGauche.setIcon(new ImageIcon(getClass().getResource("/img/left-blue.png")));
       FGauche.setBackground(new Color(255, 153, 0));
       FGauche.setBounds(80, 150, 40, 40);

       FDroite = new JLabel("D");
       //!! FDroite.setIcon(new ImageIcon(getClass().getResource("/img/right-blue.png")));
       FDroite.setBackground(new Color(255, 153, 0));
       FDroite.setBounds(140, 150, 40, 40);

       // OK button, first tutorial
       ok1 = new JButton(new SelectAction(body));
       ok1.setMargin(new Insets(5, 5, 5, 5));
       ok1.setForeground(new Color(0, 0, 0));
       ok1.setBackground(new Color(255, 153, 0));
       ok1.setBounds(105, 230, 40, 40);

       // second tutorial
       messageCentre2 = new JPanel();
       messageCentre2.setBounds(0, 0, 250, 300);

       tuto2 = new JLabel("<html>POUR RETOURNER<br>A L'ACCUEIL, APPUYER<br>SUR LA TOUCHE G</html>");
       tuto2.setForeground(new Color(0, 0, 0));
       tuto2.setFont(new Font("Arial", Font.BOLD, 16));
       tuto2.setBounds(20, -10, 200, 150);

       // OK button, second tutorial
       ok2 = new JButton(new SelectAction(body));
       ok2.setMargin(new Insets(5, 5, 5, 5));
       ok2.setForeground(new Color(0, 0, 0));
       ok2.setBackground(new Color(255, 153, 0));
       ok2.setBounds(105, 230, 40, 40);

       // visibility of tutorial panels

       // deactivate the tutorial (and reach the main page)
       tutoOff = new JCheckBox(new SelectAction(body));
       tutoOff.setText("NE PLUS AFFICHER AU DÉMARRAGE");
       tutoOff.setForeground(new Color(0, 0, 0));
       tout.add(tutoOff, BorderLayout.SOUTH);
   public void paintComponent(Graphics g) {
       g.drawOval(0, 0, 50, 50);
   public JPanel getMessageCentre1() {
       return messageCentre1;
   public JPanel getMessageCentre2() {
       return messageCentre2;


// !! hadd to add this to get code to compile!
class SelectAction extends AbstractAction {
   private Body body;

   public SelectAction(Body body) {
      this.body = body;

   public void actionPerformed(ActionEvent evt) {
      // TODO put some junk in here!

How do I display JButtons and JLabels in a JFrame?

How do I display JButtons and JLabels in a JFrame?

By : Rajni Devi
Date : March 29 2020, 07:55 AM
Hope that helps I tried to use this code to display a labeled window, but it only displays a blank window. , Try calling setVisible last
Related Posts Related Posts :
  • Content autocomplete in spring tool suite 4
  • Super Noob Help ~ MouseEvent/Frame
  • Making one project with dependencies stand-alone in Eclipse (Java)
  • Jsoup- getting certain attributes from website
  • MongoDB, how to make a link between collections with JAVA code
  • Overriding an abstract method means class abstract class or not in java?
  • Bukkit teleport - nullPointerException
  • How to check if a Float variable is negative in java
  • Servlet: Cannot forward after response has been committed
  • sql query to select a specific cell in excel
  • How to make new picture when mouse dragged in java
  • Use Constants interface in GWT Project
  • Setting size of a JPanel in GroupLayout
  • Construct a map from two equal size arrays
  • Implementing Read-Write Locks with Double-Checked Locking
  • Disable NO_BUTTON from JOptionPane Java if a condition is true
  • UDP multiple socket
  • Android Threading: This Handler class should be static or leaks might occur
  • The type org.openqa.selenium.firefox.FirefoxDriver is not accessible
  • Limitations (drawbacks) of java programming language?
  • Error: ')' expected Error: illegal start of expression
  • TableRowSorter use LookAndFeel of TableHeader, but own Comparator
  • Difference between @GeneratedValue and @GenericGenerator
  • Design Scenario: Smartphone class and will have derived classes like IPhone,AndroidPhone,WindowsMobilePhone can be even
  • Java date parsing without separators?
  • how to map an array of custom type from postgres to java using hibernate
  • Why hibernate always call "update" statement after using "select" statement in MySQL?
  • An interview topic: What can go wrong with this code?
  • How do I regex remove whitespace and newlines from a text, except for when they are in a json's string?
  • How to turn off Preferences > Compiles > User External Build?
  • how to convert arraylist to string array with all items in double quote
  • PMD+Maven+JAVA Error:: Can't find resource rulesets/comments.xml. Make sure the resource is a valid file or URL or is on
  • How to extend AbstractScheduledService.Scheduler
  • Primefaces tabview: set Active Index after some counting
  • Need help in Regex to exclude splitting string within "
  • Get header from HttpUrlConnection object
  • encoding xlsx as base64 and send it as an attachment
  • How to acess HttpServletRequest in Jaas login module in Tomcat
  • How to implement a basic pointer
  • Java Swing Exit Icon?
  • Why onNext has no effect
  • IntelliJ Idea 2018.2 no option for importing gradle project
  • Remove a negative element from an array w/o array.copy
  • Could this prevent overflow in Java?
  • In Java Swing, can I receive Caret events in real time?
  • I need help not using brute force when using JFrames and DrawWindows
  • How do I refactor ArrayList<MyClass> into MyClassLIst?
  • My program keeps saying that the method cannot be resolved
  • BubbleSort -my code returns random addresses
  • JavaFX components inside HTML?
  • Character in Java game not responding
  • Working around access denied in a FileWalking Tree in Java7
  • How to avoid if/else when using multple suppliers?
  • How to pass object from table cell editor to Table Model?
  • Paypal Sandbox payment state pending
  • sejda-console.bat passing parameters with spaces
  • Multiple Consumers Spring Kafka
  • Bitbucket pipeline: environmental variables in build.gradle file not recognized
  • Java static enum method to return a default enum value
  • What is the complexity of empty for loop?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org