0

I have this form :

enter image description here

which has one button,three labels,three textfields and internal frame above them.

this is going to be a Nurikabe game, the user will input matrix size msize for short,number of numbered cells(cells that contain a number)nncells for short, and a maximum number a numbered cell can have max for short.

I create a grid of msize*msize and fill nncells of it, which cells I choose ? well I choose them randomly, what number do I fill them with ? a random number in the interval [1,max].

I created this form with Netbeans Designer, this is the code for the whole JFrame file: package javaapplication1;

import java.awt.Color;
import java.awt.GridLayout;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class PrologTest extends javax.swing.JFrame {

public PrologTest() {
    initComponents();
}
private void initComponents()
{
    jLabel1 = new javax.swing.JLabel();
    matrixsize = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    numcells = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    maximumnumber = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jButton3 = new javax.swing.JButton();
    Nurikabe = new javax.swing.JInternalFrame();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setBackground(new java.awt.Color(255, 0, 0));

    jLabel1.setText("matrix size");
    jLabel1.setToolTipText("");

    matrixsize.setToolTipText("");
    matrixsize.setName("matrixsize"); // NOI18N

    jButton1.setBackground(new java.awt.Color(255, 255, 255));
    jButton1.setText("validate");
    jButton1.setToolTipText("");

    jButton2.setText("show solutions");
    jButton2.setToolTipText("");

    numcells.setToolTipText("");
    numcells.setName("numcells"); // NOI18N

    jLabel2.setText("number of numbered cells");
    jLabel2.setToolTipText("");

    maximumnumber.setToolTipText("");
    maximumnumber.setName("maximumnumber"); // NOI18N

    jLabel3.setText("maximum number for a cell");
    jLabel3.setToolTipText("");

    jButton3.setText("create");
    jButton3.setToolTipText("");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }
    });

    Nurikabe.setVisible(true);
    Nurikabe.getContentPane().setLayout(new java.awt.GridLayout(1, 0));

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(numcells)
                .addComponent(maximumnumber, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)
                .addComponent(matrixsize))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel3))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE))
            .addContainerGap())
        .addComponent(Nurikabe)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addComponent(Nurikabe, javax.swing.GroupLayout.PREFERRED_SIZE, 401, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1)
                .addComponent(matrixsize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton3))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jButton2)
                    .addGap(37, 37, 37))
                .addGroup(layout.createSequentialGroup()
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(numcells, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel2))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(maximumnumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
    );

    pack();
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) 
{                                         
    Nurikabe.removeAll();
    int matsize=Integer.parseInt(matrixsize.getText());
    int numberedcells=Integer.parseInt(numcells.getText());
    int maximumcellnum=Integer.parseInt(maximumnumber.getText());
    Random r=new Random();           
    Cells=new JButton[matsize][matsize];
    Nurikabe.getContentPane().setLayout(new GridLayout(matsize,matsize));            
    for(int i=0;i<matsize;i++)                            
    {
        for(int j=0;j<matsize;j++)    
        {
            Cells[i][j]=new JButton();
            Cells[i][j].setContentAreaFilled(false);  
            Cells[i][j].setBackground(Color.white);
            final JButton Cell=Cells[i][j];
            Cells[i][j].addMouseListener(new java.awt.event.MouseAdapter() 
            {
                @Override
                public void mousePressed(java.awt.event.MouseEvent evt) 
                {
                    if(SwingUtilities.isRightMouseButton(evt))
                    {
                        Cell.setBackground(Color.green);
                    }
                    else if(SwingUtilities.isLeftMouseButton(evt))
                    {
                        Cell.setBackground(Color.blue);
                    }                                 
                }
            });  
            Nurikabe.add(Cells[i][j]);
        }
    }
    for(int i=0;i<numberedcells;i++)    
    {
        int k=r.nextInt(matsize-1)+1,l=r.nextInt(matsize-1)+1;
        String text=String.valueOf(r.nextInt(maximumcellnum));
        Cells[k][l].setText(text);
        Cells[k][l].setBackground(Color.green);                
    }            
    Nurikabe.validate();
    Nurikabe.pack();
    Nurikabe.repaint();                
}
public static void main(String[] args)
{
    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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(PrologTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }                
    java.awt.EventQueue.invokeLater(() -> {
        new PrologTest().setVisible(true);
    });
}
private javax.swing.JButton Cells[][];
// Variables declaration - do not modify                     
private javax.swing.JInternalFrame Nurikabe;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JTextField matrixsize;
private javax.swing.JTextField maximumnumber;
private javax.swing.JTextField numcells;
}

this code doesn't work !! it doesn't show a thing in the internal frame.

I'm removing all compenents So to clear what was added by previous press, I called validate and repaint in the end.

I found this question on SO but The answer work when I know the size of the grid, I don't know it as the user will input it.(also didn't fi

So what's the problem ?

PS

when I press the button more than one time the internal frame gets bigger but with nothing in it, I set the layout of it to null from netbeans and set layout of it in the button.

Community
  • 1
  • 1
niceman
  • 2,653
  • 29
  • 57
  • 1
    1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). 2) Please learn common Java nomenclature (naming conventions - e.g. `EachWordUpperCaseClass`, `firstWordLowerCaseMethod()`, `firstWordLowerCaseAttribute` unless it is an `UPPER_CASE_CONSTANT`) and use it consistently. – Andrew Thompson May 27 '15 at 09:08
  • @AndrewThompson I added the event and the controls by netbeans designer, the only code I wrote is the code posted – niceman May 27 '15 at 09:09
  • The link you are referring to is using a `GridPane` – Murat Karagöz May 27 '15 at 09:10
  • @MuratK. yes I know, still the answer work when I know the size(as said in the post), hmmm and I didn't find GridPane in netbeans designer – niceman May 27 '15 at 09:18
  • @AndrewThompson is this MCVE ? – niceman May 27 '15 at 12:31
  • 1
    You can answer that question yourself. Here's how: An MCVE of a run-time problem needs (at the very least) to compile cleanly so it can run. Make a new project in your environment called (or at least the main class called) `PrologTest`. Paste that code seen above. Does it compile cleanly? Then once you've sorted that: can it be run? does it show the problem? What you're trying to create is an example that makes it easy for others to help - so it must be copy/paste/compile/run **see problem.** – Andrew Thompson May 27 '15 at 14:03
  • @AndrewThompson for it to run, I must add initComponents's body and main's body which are generated by netbeans, I don't see this relevant to the problem(it can't be netbeans's fault I think), are you saying I should add them ? – niceman May 27 '15 at 14:25
  • 1
    @AndrewThompson Considering the anguish you've been through here, I felt it necessary to inform you of your success... – user1803551 May 28 '15 at 08:05
  • 1
    Why are you using an internal frame? It's not what it's used for. – user1803551 May 28 '15 at 08:21
  • `Nurikabe.removeAll();` Firstly I'd recommend using a `CardLayout` instead of a lot of things, including any mention of `removeAll()`. See the [docs](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html) & this [example](http://stackoverflow.com/a/5786005/418556). Thanks for the heads-up @user1803551. To be honest I'd shut the browser tab after making that last comment.. ;) Still looking at the source, since I'm still not sure what it should be doing, but that comment about not using internal frames unless you actually need an MDI sounds like good advice.. – Andrew Thompson May 28 '15 at 08:27
  • Close vote retracted. – Andrew Thompson May 28 '15 at 08:31
  • @AndrewThompson forgive me, I'm still beginner to java swing – niceman May 28 '15 at 12:55
  • @AndrewThompson `CardLayout` can be useful for switching between green , blue and white(better than change the background color) but I must use grid layout for the whole game, hmmm how can I use them both ? do I use JPanel divided into JPanels ? – niceman May 28 '15 at 13:17
  • *"how can I use them both"* It's easy. A `CardLayout` can contain any type of `JComponent`. If we put a `JPanel` into one of the cards of the card layout, it can have whatever layout it needs. It is quite common to 'nest' layouts in this way. Here is a [classic example](http://stackoverflow.com/a/5630271/418556). – Andrew Thompson May 28 '15 at 13:50

1 Answers1

2

Instead of n JInternalFrame, just use a JPanel. Initialize it with:

nurikabe = new JPanel(new GridLayout(1, 0));

And in the creation process, use:

nurikabe.setLayout(new GridLayout(matsize, matsize));

Notes:

  • Variable names should start with a lowercase (cells, nurikabe...).
  • Check for exceptions when using parseInt from a user input.
  • Generally, call revalidate instead of validate. Here you don't need any of them because you call setLayout.
  • No need to call repaint also.
  • Important: the GUI builder generally has bad coding standards since it programatically creates the GUI and has its own ways of dealing with the code. For a human to read it later will take more time than it should (no, not complaining about GroupLayout). I suggest you learn to code the GUI yourself. Even the one you have right now is not that hard to make.
user1803551
  • 12,965
  • 5
  • 47
  • 74
  • good tips, And I agree with writing by myself, netbeans doesn't let me change the code generated and he itself put warnings on its code. – niceman May 28 '15 at 13:19
  • @niceman Did this solve your problem, or are you looking for something different? – user1803551 May 29 '15 at 03:04