0

I want to display a new button on screen after another button (named done) is clicked.

I have to get a gridSize from text field by user. After user clicks on done button, I have to initialize JButtons array of size [gridSize][gridSize].

For now, I have initialized a new JButton as gridCell in the mouse action listener of done button. But gridCell button does not appear when I click on done button. Where as it does appear when I initialize the gridCell button outside the scope of Mouse listener of done button.

Here's the code that shows initialization of gridCell inside action listener of done button.

    JButton btnDone = new JButton("Done");
    btnDone.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent arg0) {

            int gridSize = Integer.parseInt(textArea.getText());
            textArea.setText(""+gridSize);
            gridCell = new JButton[gridSize][gridSize];
            gridCell[0][0].setBounds(90, 140, 27, 23);
            frame.getContentPane().add(gridCell[0][0]);

        }
    });
    btnDone.setBounds(393, 12, 89, 23);
    frame.getContentPane().add(btnDone);
Leo
  • 436
  • 1
  • 3
  • 14
  • Don't add/remove controls in that way, the controls are controlled by the manager and thus should be initialized after they are created. – Roman C Oct 20 '15 at 17:06
  • But I have to initialize an array of a particular `gridsize` and that size is known only after mouse click is performed. – Leo Oct 20 '15 at 17:08
  • Could you add all necessary code? It's hard to tell exactly what is done when all code is not included. From what I can see now, you're not changing the layout at all, so maybe create a separate area that you add a GridLayout to, with the size that the user gives it. – LeFex Oct 20 '15 at 17:27
  • 2
    1) Use a [`CardLayout`](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html) as shown in [this answer](http://stackoverflow.com/a/5786005/418556). 2) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 3) For better help sooner, post a [MCVE]. – Andrew Thompson Oct 20 '15 at 18:07

0 Answers0