So I am working on a GUI project for my class and I am a bit stuck. My problem has to do with my GUI aspect so I guess you could ignore the other methods having to do with the sorting. As of now, my main concern is just getting the GUI working. However, I keep running into an error, a null pointer exception to be exact:
Java.lang.NullPointerException
at SortDriver$SortCanvas.paint(SortDriver.java:253)
at SortDriver.init(SortDriver.java:197)
at sun.applet.AppletPanel.run(AppletPanel.java:436)
at java.lang.Thread.run(Thread.java:679)
After reading though my code, I think I narrowed it down to the my SortCanvas class. I never used it before but it was part of the stub my professor gave to us. That is to say that it works correctly and displays the image correctly but it looks like my implementation is incorrect however. Could someone help me figure out how to implement my SortCanvas "picture" correctly please? I read over the Java Docs for Canvas and I still don't understand what I am doing wrong. Here is my code:
import java.awt.*;
import java.applet.Applet;
import javax.swing.*;
import java.awt.event.*;
public class SortDriver extends Applet {
private int array[]; // array to be sorted
private int limit = 1000; // size of array to be sorted - you may have to make
// this bigger for faster sorts
private int largestNum; // need to know for color scaling purposes in paint()
// flag to tell paint() whether to paint a single location or the whole array
private enum PaintType {ALL, SINGLE};
private PaintType doPaint = PaintType.ALL;
private int index = -1; // index of single array location to be painted
//this listener object responds to button events
private ButtonActionListener buttonListener;
//button to start the sort
private JButton sortButton;
//basic window frame
private JFrame mainFrame;
//layouts
private BorderLayout initialLayout;
private FlowLayout northLayout;
private BorderLayout centerLayout;
private BorderLayout southLayout;
//basic panel for window frame
private JPanel initialPanel;
//panels for window layout
private JPanel northPanel;
private JPanel centerPanel;
private JPanel southPanel;
//panels for radio buttons
private JPanel radioOrderPanel;
private JPanel radioSortPanel;
private JPanel radioColorPanel;
//north panel header labels
private JLabel topTitleLabel;
private JLabel bottomTitleLabel;
private JLabel arraySizeLabel;
//radio buttons for list order (radioOrderButton)
//random set, ordered set, reverse set
private JRadioButton rOB1, rOB2, rOB3;
//radio buttons for sort type (radioSortButton)
//bubblesort, insertionsort, mergesort, quicksort
private JRadioButton rSB1, rSB2, rSB3, rSB4;
//radio buttons for color choice (radioColorButton)
//green, red, white, blue
private JRadioButton rCB1, rCB2, rCB3, rCB4;
//radio button groups for each radio panel
private ButtonGroup orderGroup, sortGroup, colorGroup;
//text field for size of the array
private JTextField arraySizeTextField;
// the picture of the sort will appear on this canvas
private SortCanvas picture;
private final int pictureWidth = 500; // size of the sort bar 1001
private final int pictureHeight = 50;
public void init() {
buttonListener = new ButtonActionListener();
array = new int[limit];
// load the array
largestNum = array[0] = (int) (Math.random()*1000000.0);
for (int i=1; i<limit; i++) {
array[i] = (int) (Math.random()*1000000.0);
// also keep track of the largest so that we can scale by it in paint()
if (array[i] > largestNum) largestNum = array[i];
}
//set up the main frame
mainFrame = new JFrame();
initialPanel = (JPanel) mainFrame.getContentPane();
initialLayout = new BorderLayout();
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(650, 750);
initialPanel.setLayout(initialLayout);
//set up north panel
northPanel = new JPanel();
northLayout = new FlowLayout();
topTitleLabel = new JLabel("SortIt!");
bottomTitleLabel = new JLabel("A program by Mike Sevilla");
northPanel.setLayout(northLayout);
northPanel.add(topTitleLabel, BorderLayout.NORTH);
northPanel.add(bottomTitleLabel, BorderLayout.NORTH);
initialPanel.add(northPanel, BorderLayout.NORTH);
//set up center panel
centerPanel = new JPanel();
centerLayout = new BorderLayout();
centerPanel.setLayout(centerLayout);
//place array size label
arraySizeLabel = new JLabel("Size:");
//place array size text field w/ space for 5 chars
arraySizeTextField = new JTextField("", 5);
//place sort button
sortButton = new JButton("Sort it!");
// the listener is triggered when the button is clicked
sortButton.addActionListener(buttonListener);
centerPanel.setLayout(centerLayout);
//place sort bar on top of center layout
picture = new SortCanvas();
centerPanel.add(picture, BorderLayout.CENTER);
centerPanel.add(arraySizeLabel, BorderLayout.CENTER);
centerPanel.add(arraySizeTextField, BorderLayout.CENTER);
centerPanel.add(sortButton, BorderLayout.CENTER);
initialPanel.add(centerPanel, BorderLayout.CENTER);
//set up south panel
southPanel = new JPanel();
southLayout = new BorderLayout();
southPanel.setLayout(southLayout);
//set radio buttons and format layouts
radioOrderPanel = new JPanel();
radioOrderPanel.setLayout(new BoxLayout(radioOrderPanel, BoxLayout.Y_AXIS));
radioSortPanel = new JPanel();
radioSortPanel.setLayout(new BoxLayout(radioSortPanel, BoxLayout.Y_AXIS));
radioColorPanel = new JPanel();
radioColorPanel.setLayout(new BoxLayout(radioColorPanel, BoxLayout.Y_AXIS));
//define radio buttons
rOB1 = new JRadioButton("Random Order", true);
rOB1.addActionListener(buttonListener);
radioOrderPanel.add(rOB1);
rOB2 = new JRadioButton("In Order", false);
rOB2.addActionListener(buttonListener);
radioOrderPanel.add(rOB2);
rOB3 = new JRadioButton("In Reverse", false);
rOB3.addActionListener(buttonListener);
radioOrderPanel.add(rOB3);
rSB1 = new JRadioButton("Bubble Sort", true);
rSB1.addActionListener(buttonListener);
radioSortPanel.add(rSB1);
rSB2 = new JRadioButton("Insertion Sort", false);
rSB2.addActionListener(buttonListener);
radioSortPanel.add(rSB2);
rSB3 = new JRadioButton("Merge Sort", false);
rSB3.addActionListener(buttonListener);
radioSortPanel.add(rSB3);
rSB4 = new JRadioButton("Quick Sort", false);
rSB4.addActionListener(buttonListener);
radioSortPanel.add(rSB4);
rCB1 = new JRadioButton("Green", true);
rCB1.addActionListener(buttonListener);
radioColorPanel.add(rCB1);
rCB2 = new JRadioButton("Red", false);
rCB2.addActionListener(buttonListener);
radioColorPanel.add(rCB2);
rCB3 = new JRadioButton("White", false);
rCB3.addActionListener(buttonListener);
radioColorPanel.add(rCB3);
rCB4 = new JRadioButton("Blue", false);
rCB4.addActionListener(buttonListener);
radioColorPanel.add(rCB4);
//add radio buttons to a button group
orderGroup = new ButtonGroup();
orderGroup.add(rOB1);
orderGroup.add(rOB2);
orderGroup.add(rOB3);
sortGroup = new ButtonGroup();
sortGroup.add(rSB1);
sortGroup.add(rSB2);
sortGroup.add(rSB3);
sortGroup.add(rSB4);
colorGroup = new ButtonGroup();
colorGroup.add(rCB1);
colorGroup.add(rCB2);
colorGroup.add(rCB3);
colorGroup.add(rCB4);
initialPanel.add(southPanel, BorderLayout.NORTH);
picture.paint(picture.getGraphics());
mainFrame.setVisible(true);
}
// this object is triggered whenever a button is clicked
private class ButtonActionListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
// find out which button was clicked
Object source = event.getSource();
// start sort button was clicked
if (source == sortButton) {
// call the sort
doBubblesort();
}
// called when user hits return in text field
if (source == arraySizeTextField) {
int size = Integer.parseInt(arraySizeTextField.getText());
}
}
}
private void doBubblesort() {
int temp;
// this is just bubblesort
for (int i=0; i<limit-1; i++) {
for (int j=0; j<limit-1-i; j++) {
if (array[j]>array[j+1]) {
temp = array[j]; array[j] = array[j+1]; array[j+1] = temp;
// redraw only locations j and j+1
doPaint = PaintType.SINGLE; // try changing this to ALL and see what happens
index = j;
picture.paint(picture.getGraphics());
index = j+1;
picture.paint(picture.getGraphics());
}
}
}
}
class SortCanvas extends Canvas {
// this class paints the sort bar
SortCanvas() {
setSize(pictureWidth, pictureHeight);
setBackground(Color.white);
}
public void paint(Graphics g) {
if (doPaint == PaintType.ALL) {
// paint whole array - this takes time so it shouldn't be done too frequently
setBackground(Color.white);
g.setColor(Color.white);
g.fillRect(0, 0, pictureWidth, pictureHeight);
for (int i=0; i<limit; i++) {
// the larger the number, the brighter green it is
// green is between 0.0 and 1.0
// divide by the largest number to get a value between 0 and 1
float green = (float)(array[i]/(float)largestNum);
// clamp if necessary - it shouldn't be
if (green<0f) green = 0f;
if (green>1f) green = 1f;
g.setColor(new Color(0.0f, green, 0.0f));
// array location 0 is painted at left;
// array location limit-1 is painted to right
//this is a single vertical line in the bar
g.drawLine((int)(i*pictureWidth/limit), 0,
(int)(i*pictureWidth/limit), pictureHeight);
}
}
else {
// just paint one location on the bar
float green = (float)(array[index]/(float)largestNum);
if (green<0f) green = 0f;
if (green>1f) green = 1f;
g.setColor(new Color(0.0f, green, 0.0f));
g.drawLine((int)(index*pictureWidth/limit), 0,
(int)(index*pictureWidth/limit), pictureHeight);
}
}
}
}
This is not required;
picture.paint(picture.getGraphics());
getGraphics will return null if the component has not yet being painted itself. You should avoid using this method, it is simply a snap shot of the current components graphical state (which in your case is nothing)
You don't control the paint process, that's down to the repaint manager. You can request updates via the repaint methods. Have a read through Painting in AWT and Swing
You should avoid mixing heavy weight (Canvas) & light weight components (JFrame) together, where possible, you should stick with Swing components
Calling paint() directly can lead to unexpected behavior as you are see from this, use repaint() instead:
picture.repaint();
Related
I am building a chess program in Java. I am not able to display a jPanel containing the promotion options, on top of the jPanel, i.e. the Board.
The board is inside a JLayeredPane and when a pawn reaches the final square, I instantiate the PromotionOptions panel inside the event handler and revalidate. But the jPanel is not being displayed.
I already tried setting proper Size & Location to the jPanel object, putting revalidate(), also used repaint() method. I also assigned JLayeredPane a layout of null explicitly.
All of the questions already in stackoverflow related to this, was solved by properly setting the layout, which doesn't appear to be the problem here...
// JLayeredPane created here...
class Game extends JFrame {
Game() {
super.setLayout(new TableLayout(new double[][]{{0.5, 475, 0.5}, {0.5, 475, 0.5}}));
JLayeredPane layeredContainer = new JLayeredPane();
layeredContainer.setLayout(null);
Board board = new Board(layeredContainer);
board.arrange();
layeredContainer.add(board, 1);
board.setSize(475, 475);
super.add(layeredContainer, "1, 1");
super.setSize(600, 600);
super.setResizable(false);
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
super.validate();
}
}
// PromotionOptions created here...
public class Board extends JPanel {
//skipping some irrelevant code...
private class PromotionOptions extends JPanel {
private PromotionOptions(PieceColor color) {
super.setSize(50,200);
super.setBackground(Color.WHITE);
super.setLayout(new GridLayout(4, 1));
ImageIcon queenIcon = new ImageIcon(getClass().getResource("/pieceIcons/" + color.abbr + "Q.png"));
ImageIcon rookIcon = new ImageIcon(getClass().getResource("/pieceIcons/" + color.abbr + "R.png"));
ImageIcon bishopIcon = new ImageIcon(getClass().getResource("/pieceIcons/" + color.abbr + "B.png"));
ImageIcon knightIcon = new ImageIcon(getClass().getResource("/pieceIcons/" + color.abbr + "N.png"));
JLabel queenLabel = new JLabel(queenIcon);
JLabel rookLabel = new JLabel(rookIcon);
JLabel bishopLabel = new JLabel(bishopIcon);
JLabel knightLabel = new JLabel(knightIcon);
super.add(queenLabel);
super.add(rookLabel);
super.add(bishopLabel);
super.add(knightLabel);
}
}
// skipping some more irrelevant code...
private void executeMove(Tile clickedTile) {
// skip to where I create the PromotionOption object and add to layeredPane...
case PROMOTION:
moveMade.initialTile.removePiece();
JPanel promotionOptions = new PromotionOptions(colorToMove);
promotionOptions.setLocation(200,200);
layeredPaneContainer.add(promotionOptions, 2);
layeredPaneContainer.revalidate();
break;
// Some more code here
}
// End of Board class...
}
Due to some bug, whenever the pawn reaches the final tile, nothing is displayed and the application continues as it is.
After hours of frustrated debugging, I finally somehow made it work correctly. What I did was I added SwingUtilities.invokeLater() method and passed the code inside it like this..
case PROMOTION:
moveMade.initialTile.removePiece();
SwingUtilities.invokeLater(() -> {
JPanel promotionOptions = new PromotionOptions(colorToMove.opposite);
promotionOptions.setLocation(clickedTile.getLocation());
layeredPaneContainer.add(promotionOptions, 2);
layeredPaneContainer.revalidate();
});
break;
I made a simple phone keypad and I want to change a button to add numbers. Right now, the + button simply adds a + to the displayed numbers at the top, but I want that to add the inputted numbers. Like on a calculator, exactly what the + does. And I would like to change the clear button to be an enter button. Here's my partner's and I code so far to make the keypad:
public class Keypad extends JPanel implements ActionListener {
JLabel display;
JButton numButton;
JButton clearButton;
String displayContent = "";
String[] numPadContent = {"1","2","3","4","5","6","7","8","9","+","0"};
ArrayList<JButton> buttonList;
// Keypad constructor class
public Keypad(Container pane) {
// sets the size of the Keypad display
pane.setPreferredSize(new Dimension(320, 335));
// initialize display to hold displayContent
display = new JLabel(displayContent);
display.setPreferredSize(new Dimension(320, 25));
// create lowered bevel border around the display
display.setBorder(BorderFactory.createLoweredBevelBorder());
// add the display to the panel
pane.add(display, BorderLayout.PAGE_START);
// initialize the buttonList
buttonList = new ArrayList<JButton>(12);
JPanel numberPanel = new JPanel();
// set the numberPanel to have a 4row by 3col grid layout
numberPanel.setLayout(new GridLayout(4,3,0,0));
// set the size of the numberPanel
numberPanel.setPreferredSize(new Dimension(320,260));
// create the buttons and add them to the buttonList, properly displaying the numbers
for (int i = 0; i < numPadContent.length; i++) {
numButton = new JButton(numPadContent[i]);
buttonList.add(numButton);
}
// add the buttonList to the number panel
for (int n = 0; n < buttonList.size(); n++) {
buttonList.get(n).addActionListener(this);
numberPanel.add(buttonList.get(n));
}
// create black border around the number panel
numberPanel.setBorder(BorderFactory.createMatteBorder(5, 5, 5, 5, Color.black));
// add number panel to center part of display
pane.add(numberPanel, BorderLayout.LINE_END);
// create Clear button that is actionable
clearButton = new JButton("Clear");
clearButton.setPreferredSize(new Dimension(320, 30));
clearButton.addActionListener(this);
// add Clear button to bottom of display
pane.add(clearButton, BorderLayout.PAGE_END);
}
// update the display depending on clicked button(s)
public void actionPerformed(ActionEvent e) {
String textThere = display.getText();
String additionalText = "";
// add clicked number button text to display
for (int a = 0; a < buttonList.size(); a++) {
if (e.getSource().equals(buttonList.get(a))) {
additionalText = buttonList.get(a).getText();
}
}
// clear display if "Clear" button is clicked
if (e.getSource().equals(clearButton)) {
textThere = "";
}
display.setText(textThere.concat(additionalText));
}
public static void main(String[] args) {
//create and set up the window.
JFrame frame = new JFrame("Keypad");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//set up the content pane.
frame.getContentPane().add(new Keypad(frame));
frame.pack();
frame.setVisible(true);
}
See this link: Is there an eval() function in Java?
You can import javax.script and use the ScriptEngine's eval() method to evaluate your expression.
I'm creating a program that features a grid of 12 JPanels. When the "add image" button is pressed, an image appears in the first JPanel in the grid and a counter is incremented by one. From then onwards, every time the "add image" is clicked again, an image would be added to the next JPanel. For some reason, the button only adds an image to the first JPanel and then stops working. Here's the code I've got so far.
public class ImageGrid extends JFrame {
static JPanel[] imageSpaces = new JPanel[12];
int imageCounter = 0;
ImageGrid() {
this.setTitle("Image Grid");
setSize(750, 750);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p3 = new JPanel();
p3.setLayout(new GridLayout(3, 4, 10, 5));
p3.setBackground(Color.WHITE);
p3.setOpaque(true);
p3.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
for (int j = 0; j < imageSpaces.length; j++) {
imageSpaces[j] = setImageSpace();
p3.add(imageSpaces[j]);
}
MyButtonPanel p1 = new MyButtonPanel();
add(p1, BorderLayout.SOUTH);
add(p3, BorderLayout.CENTER);
}
public JPanel setImageSpace() {
JPanel test;
test = new JPanel();
test.setOpaque(true);
test.setPreferredSize(new Dimension(100, 100));
return test;
}
class MyButtonPanel extends JPanel implements ActionListener {
final JButton addImage = new JButton("Add Image");
ImageIcon lorryPicture = new ImageIcon(ImageGrid.class.getResource("/resources/lorry.png"));
JLabel lorryImage = new JLabel(lorryPicture);
MyButtonPanel() {
add(addImage);
addImage.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addImage) {
imageSpaces[imageCounter].add(lorryImage);
revalidate();
repaint();
imageCounter++;
}
}
}
public static void main(String[] args) {
ImageGrid test = new ImageGrid();
test.setVisible(true);
}
}
You should be revalidating and repainting the panel, (which is the containter being affected by the addition), not the frame
imageSpaces[imageCounter].add(lorryImage);
imageSpaces[imageCounter].revalidate();
imageSpaces[imageCounter].repaint();
Diclaimer: This may work as a simple fix, but also note that a component (in this case your JLabel lorryImage) can only have one parent container. The reason the above fix still works is because you don't revalidate and repaint the previous panel, the label was added to. So you may want to think about doing it correctly, and adding a new JLabel to each panel.
if (e.getSource() == addImage) {
JLabel lorryImage = new JLabel(lorryPicture);
imageSpaces[imageCounter].add(lorryImage);
imageSpaces[imageCounter].revalidate();
imageSpaces[imageCounter].repaint();
imageCounter++;
}
Disclaimer 2: You should add a check, to only add a label if the count is less than the array length, as to avoid the ArrayIndexOutOfBoundsException
Side Notes
Swing apps should be run from the Event Dispatch Thread (EDT). You can do this by wrapping the code in the main in a SwingUtilities.invokeLater(...). See more at Initial Threads
You could also just use a JLabel and call setIcon, instead of using a JPanel
I keep getting a null pointer exception at the line between the * lines when I click. I've been looking at it for about an hour and cant seem to figure out why. Any help would be greatly appreciated. Thanks.
private Color currentColor;
private char currentChar;
private Letter letter;
private JComboBox comboBox;
private JPanel controlPanel;
private Color[] colorArray = {Color.black,Color.blue,Color.cyan,Color.orange,Color.white,Color.yellow};
private String[] colorStringArray = {"black","blue","cyan","orange","white","yellow"};
private ArrayList<Letter> letterList;
private JButton button1;
private Canvas canvas;
public WholePanel()
{
comboBox = new JComboBox(colorStringArray);
// here we use black to draw a letter
currentColor = colorArray[Color.black];
// set the default character to 'A'
currentChar = 'A';
button1 = new JButton("Undo");
controlPanel = new JPanel();
controlPanel.add(button1);
controlPanel.add(comboBox);
canvas = new Canvas();
JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT, controlPanel, canvas);
canvas.addMouseListener(new PointListener());
add(sp);
// make this panel listen to mouse
addMouseListener(new PointListener());
setBackground(Color.white);
//This method needs to be called for this panel to listen to keys
//When panel listens to other things, and go back to listen
//to keys, this method needs to be called again.
requestFocus();
}
private class PointListener implements MouseListener
{
int x;
int y;
// when a user clicks the panel (applet),
// KeyListener is focused in it.
public void mousePressed(MouseEvent event)
{
x = event.getX();
y = event.getY();
letter = new Letter(x,y,currentChar,colorArray[comboBox.getSelectedIndex()]);
//******************************
letterList.add(letter);
//******************************
for(Letter letter1 : letterList)
{
letter1.Draw(getGraphics());
}
x=y=0;
requestFocus();
}
}
}
You didn't initialize letterList.
Add the following line to your constructor for WholePanel:
letterList = new ArrayList<Letter>();
I'm trying to create a board for a game, i first made a frame then if the user //enters the rows and columns as numbers and pushes the start button, it should remove all //whats on frame and add a panel with a grid layout having buttons everywhere
Here is the code ( Problem is the frame gets cleared and nothing appears)
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Frame extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
JButton newButton;
JButton Start;
JTextArea row;
JTextArea col;
JLabel background;
JLabel rows;
JLabel columns;
JLabel Error;
JPanel myPanel;
JCheckBox box;
public Frame()
{
//adding frame
setTitle("DVONN Game");
setSize(1000, 700);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
//making start button
Start = new JButton(new ImageIcon("Start"));
Start.setBounds(500, 30, 300, 300);
Start.setOpaque(true);
Start.addActionListener(this);
//make background
background = new JLabel();
background.setBounds(0, -300, 2000, 1500);
background.setIcon(Color.BLUE));
rows = new JLabel("Enter the rows");
columns = new JLabel("Enter the columns");
rows.setForeground(Color.WHITE);
columns.setForeground(Color.WHITE);
rows.setBounds(10,10,100,30);
columns.setBounds(10,45,105,30);
row = new JTextArea();
col = new JTextArea();
row.setBounds(120,10,100,30);
col.setBounds(120,45,100,30);
Error = new JLabel("Enter numbers plz!");
Error.setBounds(10, 100, 400, 30);
Error.setForeground(Color.RED);
Error.setVisible(true);
box = new JCheckBox("Enable Random Filling");
box.setBounds(10, 200, 150, 20);
box.setVisible(true);
myPanel = new JPanel();
myPanel.setBounds(30, 30, 700, 500);
myPanel.setVisible(true);
newButton = new JButton();
newButton.setOpaque(true);
getContentPane().add(box);
getContentPane().add(rows);
getContentPane().add(columns);
getContentPane().add(row);
getContentPane().add(col);
getContentPane().add(Start);
getContentPane().add(background);
this.validate();
this.repaint();
}
public static void main(String[]args)
{
new Frame();
}
//adding actions for start button
public void actionPerformed(ActionEvent e) {
boolean flag = true;
String r1 = row.getText();
String c1 = col.getText();
int x = 0,y = 0;
try{
x = Integer.parseInt(r1);
y = Integer.parseInt(c1);
} catch(NumberFormatException l) {
flag = false;
}
int size = x * y;
if (flag == true) {
this.getContentPane().removeAll();
this.validate();
this.repaint();
myPanel.setLayout(new GridLayout(x, y));
while(size != 0)
{
myPanel.add(newButton);
size --;
}
this.getContentPane().add(myPanel);
} else {
this.getContentPane().add(Error);
}
}
}
There are several issues with this code
Is it really needed to post that much code. A simple UI with one button to press, and then another component which should appear would be sufficient for an SSCCE
The use of null layout's. Please learn to use LayoutManagers
Each Swing component can only be contained once in the hierarchy. So this loop is useless since you add the same component over and over again (not to mention that a negative size would result in an endless loop)
while(size != 0){
myPanel.add(newButton);
size --;
}
Have you tried debugging to see whether size is actually >0. Since you silently ignore ParseExceptions you might end up with a size of 0 which will clean the content pane and add nothing
Then do as goldilocks suggests and call validate after adding the components. See the javadoc of the Container#add method
This method changes layout-related information, and therefore, invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to display the added component.
Call validate() and repaint() after the new elements have been added instead of after the old ones have been removed.
You don't need to be calling setVisible() on individual components, call it after pack() on the Frame itself, and you shouldn't use validate() and repaint() in the constructor. Ie, replace those with:
pack();
setVisible(true);
or you can do that on the object after the constructor is called.
Try to replace
public static void main(String[]args)
{
new Frame();
}
by
public static void main(String[]args)
{
new Frame().setVisible(true);
}
Remove the call to this.setVisible in the constructor and make this your main method.
public static void main(String[] args) {
final Frame fr = new Frame();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
fr.setVisible(true);
}
});
}
This will make sure that the frame elements will be in place before it becomes visible.