Java Panel Won't Paint - java

Basic summary: Working on a game that generates a 15x15 grid for the player to move around in. Each cell in the grid as an image that is randomly generated with shades of brown so each cell looks different. Only problem is I'm trying to create a buffered image for each cell that holds the random series of colors. My problem in the Dirt class is it won't call the paintComponent method. Here is the Dirt class. (passed in a rectangle of the cell in constructor)
package game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class Dirt extends JPanel{
private Rectangle rect;
private BufferedImage image;
private int pixelSize;
public Dirt(Rectangle x){
rect = x;
image = new BufferedImage(rect.width, rect.width, BufferedImage.TYPE_INT_RGB);
pixelSize = rect.width/15;
setVisible(true);
validate();
this.repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = image.createGraphics();
Rectangle[][] rects = new Rectangle[15][15];
Color[] colors = {new Color(160,82,45),new Color(139,69,19),new Color(165,42,42)};
java.util.Random randomGenerator = new java.util.Random();
for(int i = 0; i < 15; i++){
for(int j = 0; j < 15; j++)
rects[i][j] = new Rectangle(pixelSize*i,pixelSize*j,pixelSize,pixelSize);
}
for(int i = 0; i < 15; i++){
for(int j = 0; j < 15; j++){
System.out.println(i + " " + j);
g2d.setColor(colors[randomGenerator.nextInt(3)]);
g2d.fillRect(rects[i][j].x, rects[i][j].y, rects[i][j].width, rects[i][j].height);
}
}
g2d.dispose();
}
public Image getImage(){return image;}
public Rectangle getRect(){return rect;}
}

Add the following to the end of your paintComponent method:
g.drawImage(image, 0, 0, this);
Like #Carl Manaster says in his comment, you've drawn to the buffered image, but you're not then drawing the buffered image to the Graphics object passed into the paintComponent method.
EDIT: I added the following to your class to test, and included my code line above in the paintComponent method and it works for me:
public static void main(String args[]) {
JFrame f = new JFrame();
f.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.getContentPane().setLayout(null);
Dirt d = new Dirt(new Rectangle(40, 40));
d.setBounds(20, 20, 64, 64);
f.getContentPane().add(d);
f.setSize(300, 300);
f.setVisible(true);
}

Related

Create Image from Jframe

I created a pie chart using JFrame and swings. But I want to convert the pie chart into the image and save in desktop/local path. But not having idea how to create image using JFrame Pie.
package test;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
class Main1 {
double value;
Color color;
public Main1(double value, Color color) {
this.value = value;
this.color = color;
}
}
class MyComponent extends JComponent {
Main1[] slices = { new Main1(1, Color.black), new Main1(1, Color.green),
new Main1(1, Color.yellow), new Main1(1, Color.red) };
MyComponent() {
}
public void paint(Graphics g) {
drawPie((Graphics2D) g, getBounds(), slices);
}
void drawPie(Graphics2D g, Rectangle area, Main1[] slices) {
double total = 0.0D;
for (int i = 0; i < slices.length; i++) {
total += slices[i].value;
}
double curValue = 0.0D;
int startAngle = 0;
for (int i = 0; i < slices.length; i++) {
startAngle = (int) (curValue * 360 / total);
int arcAngle = (int) (slices[i].value * 360 / total);
g.setColor(slices[i].color);
g.fillArc(area.x, area.y, area.width, area.height, startAngle, arcAngle);
curValue += slices[i].value;
}
}
}
public class Main2 {
public JPanel contentPane;
public static void main(String[] argv) {
JFrame frame = new JFrame();
frame.getContentPane().add(new MyComponent());
frame.setSize(300, 200);
frame.setVisible(true);
}
}
The basic logic for creating an Image of a Swing component is:
Dimension d = component.getSize();
BufferedImage image = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
component.print( g2d );
g2d.dispose();
ImageIO.write(image, ".jpg", new File(...));
You can also check out the Screen Image class for convenience methods that paint the entire frame, a component on the frame or a rectangle of a component on the frame.
Note the above suggestion assumes you do the custom painting correctly which means you:
extend JPanel
override paintComponent(...), not paint(...)
invoke super.paintComponent(...)
If you want to extend JComponent then you need to:
override paintComponent(...);
fill the background of your component first before invoking the drawPie(...) method
But I want to convert the pie chart into the image
Create a BufferedImage and paint to it
BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bi.createGraphics();
new MyComponent().drawPie(g2d, new Rectangle(0, 0, 200, 200), slices);
g2d.dispose();
and save in desktop/local path
Use ImageIO
ImageIO.write(bi, "jpg", new File("the/path/andName.jpg"));

JLabels in GridLayout are Not Always Painted

I am creating a basic Tic-Tac-Toe application in Java Swing, and for this purpose, I have started investigating drawing. However, I have encountered an issue when a subclass of JPanel contains more than one instance of a subclass of JLabel, which overrides the paintComponent(Graphic) method, in a GridLayout array format embedded in itself. The issue is that only the first element in this array is painted.
An example for the customized subclass of JLabel:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JLabel;
#SuppressWarnings("serial")
public class DrawLabel extends JLabel {
private boolean hasPaint;
public DrawLabel() {
super();
this.hasPaint = false;
}
public void draw() {
hasPaint = true;
repaint();
}
public void clear() {
hasPaint = false;
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if (hasPaint) {
g2.drawOval(getX(), getY(), getWidth(), getHeight());
} else {
g2.clearRect(getX(), getY(), getWidth(), getHeight());
}
}
}
An example for the customized subclass of JPanel:
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class DrawPanel extends JPanel {
private Dimension size;
private DrawLabel[][] fields;
public DrawPanel(Dimension d) {
super();
this.size = d;
this.fields = new DrawLabel[size.height][size.width];
this.setLayout(new GridLayout(size.height, size.width));
for (int i = 0; i < size.height; i++) {
for (int j = 0; j < size.width; j++) {
this.fields[i][j] = new DrawLabel();
this.add(fields[i][j]);
}
}
}
public void draw(int row, int col) {
fields[row][col].draw();
}
public void clear() {
for (int i = 0; i < size.height; i++) {
for (int j = 0; j < size.width; j++) {
fields[i][j].clear();
}
}
}
}
An example of an issue-provoking scenario:
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
public class Driver {
public static void main(String[] args) {
DrawPanel board = new DrawPanel(new Dimension(2, 1));
JFrame canvas = new JFrame();
canvas.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
canvas.add(board, BorderLayout.CENTER);
canvas.pack();
canvas.setLocationRelativeTo(null);
canvas.setVisible(true);
board.draw(0, 0); // This gets painted.
board.draw(0, 1); // This does not get painted!
}
}
Curiously, if the DrawPanel.draw(int, int) is changed to set the text of the element rather than draw upon it, only the second element is updated, while the first is not, which is the exact opposite of the original problem.
I have tried to look up other issues and questions related to painting of subcomponents, but I have yet to find an issue like this one, where it seems that every instance beyond the first in the GridLayout are not drawable in the same way. What could be wrong?
Thank you for your time and effort!
g2.drawOval(getX(), getY(), getWidth(), getHeight());
Painting of a component is done relative to the component, not the panel the component is painted in. The getX/Y() methods return the location of the component relative to the parent component.
So if the size of each component is (200, 200) then the oval of the first component will be painted using
g2.drawOval(0, 0, 200, 200);
The second component will be painted at:
g2.drawOval(200, 0, 200, 200);
but since the component is only 200 pixels wide, the start x location of 200 is outside the bounds of the component so there is nothing to paint.
Instead just use:
g2.drawOval(0, 0, getWidth(), getHeight());

BufferedImage doesn't draw from 0,0

I hope my first post isn't too basic for y'all.
I'm trying to do some per-pixel drawing on a JCanvas using a BufferedImage (using setRGB()). I thought I would test all was working with a single diagonal line from the origin to the width/height of the JCanvas. The trouble is that I get a strange offset in the x axis that I can't seem to fix!
Here's a link to the problem:
http://i811.photobucket.com/albums/zz31/bohngy/problemMandel_zpsae20713a.jpeg
Here's the code:
public class Mandelbrot extends JFrame {
private BufferedImage I;
public Mandelbrot() {
super("Mandelbrot Set");
setSize(600, 600);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
I = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < getHeight(); x++) {
for (int y = 0; y < getWidth(); y++) {
I.setRGB(x, x, Color.GREEN.getRGB());
}
}
}
#Override
public void paint(Graphics g) {
g.drawImage(I, 0, 0, this);
}
public static void main(String[] args) {
new Mandelbrot().setVisible(true);
}
}
General issues
Don't extend JFrame (particularly, don't override the paint method of JFrame). Instead, do the painting in the paintComponent method a class that extends JPanel
Create the GUI from the Event Dispatch Thread
The main reason for the unexpected result is that you are creating an image that has the size of the frame - but the frame also has a title bar and a border, and these are "covering" parts of the image. The size of the area that is actually available for painting is smaller than the total frame size. Additionally, the getWidth() and getHeight() methods may return garbage as long as the frame is not yet visible on the screen.
One approach considering all this could look like in this snippet:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Mandelbrot
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout(1, 1));
BufferedImage image = createImage(500, 500);
ImagePanel imagePanel = new ImagePanel(image);
frame.getContentPane().add(imagePanel);
frame.pack();
frame.setVisible(true);
}
private static BufferedImage createImage(int w, int h)
{
BufferedImage image = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < w; x++)
{
image.setRGB(x, x, Color.GREEN.getRGB());
}
return image;
}
static class ImagePanel extends JPanel
{
private final BufferedImage image;
ImagePanel(BufferedImage image)
{
this.image = image;
}
#Override
public Dimension getPreferredSize()
{
if (super.isPreferredSizeSet())
{
return super.getPreferredSize();
}
return new Dimension(image.getWidth(), image.getHeight());
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}
}
All BufferedImage objects have an upper left corner coordinate of (0, 0). Any Raster used to construct a BufferedImage must therefore have minX=0 and minY=0.
Therein lies your problem.
JavaDoc for BufferedImage
Edit:
Also remove this from your loop:
for (int y = 0; y < getWidth(); y++) {
I.setRGB(x, x, Color.GREEN.getRGB());
}

Repeating an image based on random integers

I created a background using a relatively bland texture (it repeats well, so that's a bonus). However, on top of that, I am trying to add two images in random positions, each five times. So I tried that out with this -
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Insets;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class RepeatDiagonals {
public static Image whiteOverlayStreak;
public static Image blackOverlayStreak;
public static JFrame framePanel;
public static DiagonalImages diagTest;
public static void createAndInitGUI() {
diagTest = new DiagonalImages();
framePanel = new JFrame("Diagonal Testing");
framePanel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
framePanel.setPreferredSize(new Dimension(1020, 720));
framePanel.add(diagTest);
framePanel.pack();
framePanel.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndInitGUI();
} // public void run() Closing
}); // SwingUtilities Closing
}
}
// TODO Add in constructor for better image import
class DiagonalImages extends JPanel {
public static final String IMAGE_PATH_WHITESTREAK = "imageFolder/whiteBackgroundStreakOverlay.png";
public static final String IMAGE_PATH_BLACKSTREAK = "imageFolder/blackBackgroundStreakOverlay.png";
public static Image whiteOverlayStreak;
public static Image blackOverlayStreak;
public static Image overlayStreak;
DiagonalImages() {
loadImages();
setVisible(true);
setOpaque(false);
};
public void loadImages() {
try {
whiteOverlayStreak = ImageIO.read(new File(IMAGE_PATH_WHITESTREAK));
blackOverlayStreak = ImageIO.read(new File(IMAGE_PATH_BLACKSTREAK));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Dimension size = this.getSize();
Insets insets = this.getInsets();
int w = size.width - insets.left - insets.right;
int h = size.height - insets.top - insets.bottom;
Random randomInteger = new Random();
randomInteger.nextInt(900);
for (int i = 0; i < 3; i++) {
int x = randomInteger.nextInt() % w;
int y = randomInteger.nextInt() % h;
g2d.drawImage(blackOverlayStreak, x, y, null);
}
for (int i2 = 0; i2 < 5; i2++){
int x2 = randomInteger.nextInt() % w;
int y2 = randomInteger.nextInt() % h;
g2d.drawImage(whiteOverlayStreak, x2, y2, null);
}
}
}
The relevant part of the main code:
// Makes the Initial BorderLayout
allContent = new ImagePanel(image);
allContent.setLayout(new BorderLayout());
allContent.add(new DiagonalImages());
allContent.add(tabbedPane, BorderLayout.CENTER);
allContent.add(logoImage, BorderLayout.NORTH);
allContent.setVisible(true);
allContent.setOpaque(false);
// Add ScrollPane
scrollPane = new JScrollPane(allContent);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.getVerticalScrollBar().setUnitIncrement(10);
scrollPane.setOpaque(false);
scrollPane.getViewport().setOpaque(false);
scrollPane.setBorder(new EmptyBorder(0, 0, 0, 0));
scrollPane.setWheelScrollingEnabled(true);
// JFrame programFrame Constructors
programFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
programFrame.setLayout(new BorderLayout());
programFrame.add(scrollPane);
programFrame.pack();
programFrame.setVisible(true);
programFrame.setResizable(true);
programFrame.setSize(1280, 720);
programFrame.setLocationRelativeTo(null);
And here's the ImagePanel I have:
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;
class ImagePanel extends JPanel {
private Image image;
private boolean tile;
ImagePanel(Image image) {
this.image = image;
this.tile = false;
};
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int iw = image.getWidth(this);
int ih = image.getHeight(this);
if (iw > 0 && ih > 0) {
for (int x = 0; x < getWidth(); x += iw) {
for (int y = 0; y < getHeight(); y += ih) {
g.drawImage(image, x, y, iw, ih, this);
}
}
}
}
}
Thanks for the (future) help!
EDIT: Made a small change based on the answer given, and it's still not working.
Okay, so the problem is that the image that's supposed to be repeated isn't actually even showing up.
EDIT2: Rewrote my entire code for this, and it's still not working. Even setting the background color isn't working, which leads me to believe it's a problem with my paintComponent.
EDIT3: paintComponent is working thanks to help. My final problem is getting it to work correctly in my main method.
First JFrame.setVisible(true); should be done last, after pack() which does layouting.
framePanel.pack();
framePanel.setVisible(true);
The images maybe better reside in the application (jar) itself, then you can use getClass().getResource("...").
They should be loaded outside paint, say in the constructor. I guess, it was test code.
public static Image whiteOverlayStreak;
public static Image blackOverlayStreak;
DiagonalImages() {
loadImages();
}
private void loadImages() {
whiteOverlayStreak = new ImageIcon(
getClass().getResource("/white.jpg")).getImage();
blackOverlayStreak = new ImageIcon(
getClass().getResource("/black.jpg")).getImage();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
int x = r.nextInt(w);
int y = r.nextInt(h);
Your failure was not using #Override because then you would have seen, that you miswrote Graphics2D g instead of Graphics g. The function paintComponent never got called! LoL
Additional question: adding a second panel
framePanel.setLayout(new BorderLayout());
framePanel.add(diagTest, BorderLayout.CENTER);
framePanel.add(otherPanel, BorderLayout.SOUTH);
It wasn't really an SSCCE.
I haven't tested this fully, mainly because I didn't want to have to set up an entire Eclipse project just to point out the obvious mistake.
Separate the image process from the JPanel.
Only extend Swing components when you're modifying a component method.
Here's my version of your code. I had to modify your code to read an image to get it to work. You're going to have to figure out that part of the code yourself.
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
class GUIImages {
private Image whiteDiagonal;
// private Image blackDiagonal;
public GUIImages() {
loadImages();
}
private void loadImages() {
try {
whiteDiagonal = ImageIO.read(new File(
"C:/Documents and Settings/BOP00082/" +
"My Documents/My Pictures/Places-icon.png"));
} catch (IOException e) {
e.printStackTrace();
}
// whiteDiagonal = new ImageIcon(this.getClass().getResource(
// "imageFolder/whiteBackgroundStreakOverlay.png")).getImage();
// blackDiagonal = new ImageIcon(this.getClass().getResource(
// "imageFolder/blackBackgroundStreakOverlay.png")).getImage();
}
public void doDrawing(JPanel panel, Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(createDiagonalImage(panel), 0, 0, null);
}
private Image createDiagonalImage(JPanel panel) {
BufferedImage buffImg = new BufferedImage(677, 856,
BufferedImage.TYPE_INT_ARGB);
Graphics2D gbi = buffImg.createGraphics();
Dimension size = panel.getSize();
Insets insets = panel.getInsets();
int w = size.width - insets.left - insets.right;
int h = size.height - insets.top - insets.bottom;
Random r = new Random();
for (int i = 0; i < 5; i++) {
int x = Math.abs(r.nextInt()) % w;
int y = Math.abs(r.nextInt()) % h;
gbi.drawImage(whiteDiagonal, x, y, null);
}
gbi.dispose();
return buffImg;
}
}
class Surface extends JPanel {
GUIImages images;
public Surface(GUIImages images) {
this.images = images;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
images.doDrawing(this, g);
}
}
public class RepeatDiagonals implements Runnable {
JFrame frame;
#Override
public void run() {
frame = new JFrame();
frame.setTitle("Repeat Diagonals");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Surface(new GUIImages()));
frame.setSize(350, 250);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new RepeatDiagonals());
}
}

JTextArea Not Showing When repaint(), but Graphics not updating when revalidate()?

I am making a program that simulates an NHL Draft Lottery, where there should be a JTextField on the right of the screen, and draftballs being drawn on the left that bounce around. I made a class called Ball that implements Runnable, and runs as a Thread in my main DraftLottery class. However, when my draw method calls repaint(), the JTextArea doesn't show. I tried switching repaint() to revalidate(), but then balls weren't moving. Then I tried calling repaint() and revalidate(), but it acted the same as repaint().
Here is the code for my DraftLottery class:
package ca.WiltzSports.DraftLottery;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import ca.WiltzSports.DraftLottery.DraftBall.Ball;
public class DraftLottery extends JFrame {
public static final long serialVersionUID = 89L;
int teams;
String[] teamNames;
int[] balls;
JTextArea display;
JPanel screen;
JPanel animation;
List<String> entries;
public static List<Ball> ball;
String [] draftOrder;
Random rand;
int counter = 1;
javax.swing.Timer t;
public static int width = 1024;
public static int height = 768;
Graphics dbg;
Image dbImage;
int i = 0;
public DraftLottery(int teams, String[] teamNames, int[] balls){
t = new javax.swing.Timer(2000, new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
draft();
}
});
ball = new ArrayList<Ball>();
rand = new Random();
this.teams = teams;
this.teamNames = teamNames;
this.balls = balls;
this.screen = new JPanel();
this.animation = new JPanel();
display = new JTextArea(20,50);
display.setBackground(Color.BLACK);
display.setForeground(Color.YELLOW);
draftOrder = new String[teams];
this.entries = new ArrayList<String>();
addTeamBalls();
setSize(width,height);
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Draft Lottery");
setLayout(new BorderLayout());
screen.add(display);
add("East", new JScrollPane(display));
add("West", animation);
t.start();
}
#Override
public void paint(Graphics g){
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
Graphics2D g2d = (Graphics2D) dbg;
draw(g2d);
g.drawImage(dbImage, 0, 0, this);
Ball.runBalls(ball);
}
public void draw(Graphics2D g2d){
for (Ball b: ball){
b.draw(g2d);
}
revalidate();
repaint();
}
public void addTeamBalls(){
for (int c = 0; c < teamNames.length; c++){
for (int j = 0; j < balls[c]; j++){
entries.add(teamNames[c]);
ball.add(new Ball(rand.nextInt(width/2 - Ball.SIZE), rand.nextInt(height - Ball.SIZE), teamNames[c], i++));
}
}
}
public void draft(){
int q = 0;
String [] e = entries.toArray(new String[entries.size()]);
String draftedTeam;
int index = rand.nextInt(entries.size());
draftedTeam = e[index];
if(!draftedTeam.equals("X")){
display.append("" + counter++ + ". " + draftedTeam + "\n");
for(int c = 0; c < e.length; c++){
if (e[c].equals(draftedTeam)){
e[c] = "X";
}
}
removeBalls();
}else {
boolean again = false;
for (int c = 0; c < e.length; c++){
if (!e[c].equals("X")){
again = true;
}
}
if(again){
}else{
t.stop();
display.append("DRAFT LOTTERY COMPLETE");
}
}
entries = Arrays.asList(e);
}
public void removeBalls(){
Ball [] bs;
int q = 0;
for (Ball b: ball){
if (b.getTeamName().equals("X")){
continue;
}else{
q++;
}
}
bs = new Ball[q];
q = 0;
for (Ball b: ball){
if (!b.getTeamName().equals("X")){
bs[q++] = b;
}
}
ball = Arrays.asList(bs);
}
}
Any help would be greaty appreciated.
Thanks a lot!
You have a number of problems:
You've overridden the paint method of a top level container. This is generally not recommend, as it's not double buffered and can produce flicker with animation and other paint updates.
You've failed to call super.paint. The paint mathod is responsible for pulling all the sub-paint methods together, including, paintComponents; but since you're not allowing paint to do it's job, it's not rendering those components for you.
Instead,
Create a custom component, extending from something like JPanel.
Add all the required logic for the animation to this component.
Override it's paintComponent method and add all your animation and custom painting to it.
Add it to the frame.
Take a look at Performing Custom Painting and Painting in AWT and Swing for more details.

Categories