Note - I was working on this answer right before you deleted your previous question, so the answer may see a little off in terms of the new code you posted in this question, but it gets you towards the same goal.
Don't initialize everthing in the
actionPerformed
. You're getting aNullPointerException
becausepaint
is called by the frame implicitly before the array is initialized. What I did was create a method to initialize itint[] iToken = initArray(); ... private int[] initArray() { String text = "200 300 250 150 400 100"; String[] token = text.split("\\W"); int[] itoken = new int[token.length]; int i = 0; for (String str : token) { itoken[i++] = Integer.parseInt(str); } return itoken; }
Don't paint on top level containers like
JFrame
. Instead us aJPanel
orJCompoent
and overridepaintComponent
, and overridegetPreferredSize()
in yourJPanel
so you won't have to set the size of yourJFrame
. Justpack()
it.Run Swing apps from the Event Dispatch Thread like this
public static void main(String[] args) { SwingUtilitiies.invokeLater(new Runnable(){ public void run(){ new Test(); } }); }
You never add your button to the frame.
Don't use a null layout. Use Layout Managers.
Add you components, then call
setVisible
Here's the running refactored code
import javax.swing.*;
import java.awt.Graphics;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test extends JFrame implements ActionListener {
JButton button;
boolean paint = false;
int x, y;
int[] iToken = initArray();
public Test() {
super("Test");
button = new JButton("GO");
button.setBounds(500, 100, 50, 50);
button.addActionListener(this);
add(button, BorderLayout.SOUTH);
add(new DrawPanel());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
this.setResizable(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
paint = true;
repaint();
}
}
private int[] initArray() {
String text = "200 300 250 150 400 100";
String[] token = text.split("\\W");
int[] itoken = new int[token.length];
int i = 0;
for (String str : token) {
itoken[i++] = Integer.parseInt(str);
}
return itoken;
}
public class DrawPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (paint) {
for (int i = 0; i < iToken.length; i += 2) {
x = iToken[i];
y = iToken[i + 1];
g.drawOval(x - 5, y - 5, 10, 10);
}
}
}
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Test();
}
});
}
}