Simple paint program using JPanel shows random images of JButtons - java

I'm trying to make a simple paint program in Java. It has 3 colors and a JField to enter the thickness. It works, except every time I enter a button, an image of that button shows up in the JPanel that contains the drawing portion.
I know that I can set the paintPane JPanel to opaque, but it relies on drawing over it self for the painting to work - otherwise it just drags a point around the screen. Thanks!!!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class SimplePainting
{
//The main method simply creates a frame, and terminates the program
//once that frame is closed.
public static void main (String [] args)
{
PaintFrame frame = new PaintFrame();
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}
}
class PaintFrame extends JFrame implements ActionListener
{
JPanel pane;
PaintPane drawPane;
Color paintColor = Color.black;
private int radius = 5;
//holds the thickness of the line
JTextField thick;
public PaintFrame ()
{
//We use the JFrame consturctor to add a title to the frame
super("Windows Paint");
//set the main content pane
pane = (JPanel)getContentPane();
pane.setLayout(new BorderLayout());
//make a pane to hold the drawing
drawPane = new PaintPane();
drawPane.addMouseMotionListener(drawPane);
//Make a JPanle to hold all of the buttons
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new GridLayout(1,6));
//add the buttons
JButton black = new JButton("Black");
buttonPane.add(black);
JButton red = new JButton("Red");
buttonPane.add(red);
JButton green = new JButton("Green");
buttonPane.add(green);
//Make a field to re-enter the thickness
thick = new JTextField(3);
thick.setText("5");
JButton thickness = new JButton("Reset Thickness");
thickness.addActionListener(this);
buttonPane.add(thickness);
buttonPane.add(thick);
JButton reset = new JButton("New Drawing");
reset.addActionListener(this);
buttonPane.add(reset);
black.addActionListener(this);
red.addActionListener(this);
green.addActionListener(this);
pane.add(drawPane, BorderLayout.CENTER);
pane.add(buttonPane, BorderLayout.SOUTH);
setSize(500,200);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Black"))
paintColor = Color.black;
else if (e.getActionCommand().equals("Red"))
paintColor = Color.red;
else if (e.getActionCommand().equals("Green"))
paintColor = Color.green;
else if (e.getActionCommand().equals("Reset Thickness"))
{
if (thick.getText() != "")
{
int lineThickness = Integer.parseInt(thick.getText());
radius = lineThickness;
}
}
else if (e.getActionCommand().equals("New Drawing"))
{
drawPane.startPaint = false;
drawPane.repaint();
}
}
class PaintPane extends JPanel implements MouseMotionListener
{
private int x;
private int y;
// don't paint a point until mouse is dragged
boolean startPaint = false;
public PaintPane()
{
setBackground(Color.white);
}
//paints a circle centered at x,y
public void paint(Graphics g)
{
//recall that the frist (x,y) coordiantes represent the top left
//corner of a box holding the circle
g.setColor(paintColor);
if (startPaint)
g.fillOval(x-radius,y-radius, 2*radius, 2*radius);
else
super.paintComponent(g);
}
public void mouseDragged(MouseEvent e)
{
startPaint = true;
x = e.getX();
y = e.getY();
repaint();
}
public void mouseMoved(MouseEvent e)
{
}
}
}

Related

Why can't I paint on the panel

I have made three panels south, east and north, I am trying to draw a circle on the north panel but I just can't figure out why it is not drawing. Here is my code: What I want is a small application that draws circles of different sizes and colors chosen by the user.
import com.sun.prism.shader.DrawCircle_Color_Loader;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class drawing extends JFrame implements MouseListener{
private int r = 255, g = 0, b = 0;
private JSlider colorSlider, redSlider,greenSlider,blueSlider;
private JLabel colorLabel,redLabel,greenLabel,blueLabel;
private int x = 50;
private int y = 50;
public drawing(){
JFrame frame = new JFrame("Drawing App");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(800,800);
Container contentPane = frame.getContentPane();
JMenuBar mb = new JMenuBar();
frame.setJMenuBar(mb);
JMenu color = new JMenu("Colour");
JMenu size = new JMenu("Size");
mb.add(color);
mb.add(size);
JMenuItem colorRed = new JMenuItem("Red");
JMenuItem colorBlue = new JMenuItem("Blue");
JMenuItem colorGreen = new JMenuItem("Green");
color.add(colorBlue);
color.add(colorGreen);
color.add(colorRed);
JMenuItem one = new JMenuItem("1");
JMenuItem two = new JMenuItem("2");
JMenuItem three = new JMenuItem("3");
JMenuItem four = new JMenuItem("4");
JMenuItem five = new JMenuItem("5");
size.add(one);
size.add(two);
size.add(three);
size.add(four);
JPanel panel = new JPanel();
setBackground(Color.WHITE);
contentPane.add(panel,BorderLayout.NORTH);
JPanel panel1 = new JPanel();
contentPane.add(panel1,BorderLayout.SOUTH);
JPanel panel2 = new JPanel();
contentPane.add(panel2,BorderLayout.EAST);
panel1.setLayout(new GridLayout(0,1));
JColorChooser colors = new JColorChooser();
panel1.add(colors);
frame.setVisible(true);
panel.add(panel);
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillOval(x,y,100,100);
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
public static void main(String[] args) {
drawing Drawing = new drawing();
}
}
You created another instance of JFrame inside the constructor drawing()
Remove that instance and replace with this for all the initialization inside the constructor.
add super.paint(g); to the first line of your public void paint(Graphics g) method.
A panel with no content has a default size of 0x0, so the only way you might see such a panel is if the layout stretches it in both height and width. It is best to override the getPreferredSize() method of a custom painted panel to return a sensible size, then pack() the top level container.

Buttons and Icons Within a Label - SquareIcon

I am trying to create a program with three buttons and a label with a CompositeIcon that at the start is empty.
When you click one of the buttons there will be added a square at the screen (with the described color), when another button is pressed there is gonna be added another square and so on. That means, when i press a button five times, there will be created five squres at the given colors.
If any one will read my code i will be thankful.
/*
This program creates a window with three buttons - red, green and blue - and a label with an icon.
This icon is a CompositeIcon that at the start is empty. When we press one of the three buttons, there will
be added a square at the specified color.
*/
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ResponsiveFrame extends JFrame {
static SquareIcon icon;
static int number; // this
static Color awtColor; // this
public static void main(String[] args) {
final JFrame frame = new JFrame();
final JLabel label = new JLabel();
JButton redButton = new JButton("RED");
JButton greenButton = new JButton("GREEN");
JButton blueButton = new JButton("BLUE");
/*
this is the part that i am not sure about!
not sure about the parameters.
*/
icon = new SquareIcon(number, awtColor);
redButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
icon.addIcon(new SquareIcon(20, Color.RED));
label.setIcon(icon);
frame.repaint();
frame.pack();
}
});
greenButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
icon.addIcon(new SquareIcon(20, Color.GREEN));
label.setIcon(icon);
frame.repaint();
frame.pack();
}
});
blueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
icon.addIcon(new SquareIcon(20, Color.BLUE));
label.setIcon(icon);
frame.repaint();
frame.pack();
}
});
frame.setLayout(new FlowLayout());
frame.add(redButton);
frame.add(greenButton);
frame.add(blueButton);
frame.add(label);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
And here is the part with the SquareIcon.
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class SquareIcon implements Icon {
private ArrayList<Icon> icons;
private int width;
private int height;
public SquareIcon(int number, Color awtColor) {
icons = new ArrayList<Icon>();
number = number;
awtColor = awtColor;
}
public void addIcon(Icon icon) {
icons.add(icon);
width += icon.getIconWidth();
int iconHeight = icon.getIconHeight();
if (height < iconHeight)
height = iconHeight;
}
public int getIconHeight() {
return height;
}
public int getIconWidth() {
return width;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
for (Icon icon : icons) {
icon.paintIcon(c, g, x, y);
x += icon.getIconWidth();
}
}
}
The program does compile, but when i press the buttons, nothing happens!
You create a JLabel but add it to nothing.
I suggest that you create a new JLabel each time you need one, and be sure to add it to the GUI after creating it. You will want to add it to a JPanel that is displayed in the JFrame/GUI, and will want to call revalidate() and repaint() on the JPanel after adding the label so that the panel knows to re-layout all its components, including the new one, and to re-draw itself and its children.

repaint() isn't called in Java program

I have a simple program (most of it is going to be used for something else) that just draws ovals when a user clicks the drawPanel JPanel and displays ovals. The problem is that the repaint() method isn't calling paintComponent(). Why is this?
Here is the code:
// Imports Used:
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
import java.awt.geom.*;
// Class DrawPolygon
public class DrawPolygon extends JPanel implements MouseListener
{
// Variables used in GUI
static JFrame frame;
static JPanel drawPanel;
static JPanel labelPanel;
static JPanel primaryPanel;
static JButton loadButton;
static JButton saveButton;
static JButton clearButton;
static JButton addButton;
static JButton moveButton;
static JButton exitButton;
// Variables used for GUI interaction
static final int SIZE = 6;
static int numVertices;
ArrayList<Point> vertices;
static Color outlineColor = Color.RED;
static int lineWidth = 10;
static Color fillColor = Color.BLACK;
// Constructor for new Polygon Drawing Application
public DrawPolygon()
{
// Create Frame
frame = new JFrame("Vector Painter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Set Location of GUI on screen
frame.setLocation(225,100);
// Primary Panel to store Draw Panel and Lable/Button Panel
primaryPanel = new JPanel();
// Create Label Panel
createLabelPanel();
// Create Draw Panel
createDrawPanel();
// Add panels to Primary
primaryPanel.add(labelPanel);
primaryPanel.add(drawPanel);
// Add to frame
frame.getContentPane().add(primaryPanel);
frame.pack();
frame.setVisible(true);
}
// Add Buttons to left side
public void createLabelPanel()
{
// Label Panel to add Buttons
labelPanel = new JPanel();
labelPanel.setBackground(Color.BLACK);
labelPanel.setPreferredSize(new Dimension(200,600));
// Create JButtons
loadButton = new JButton("LOAD");
loadButton.setPreferredSize(new Dimension(180,75));
loadButton.setBackground(Color.BLACK);
loadButton.setForeground(Color.WHITE);
loadButton.addMouseListener(this);
saveButton = new JButton("SAVE");
saveButton.setPreferredSize(new Dimension(180,75));
saveButton.setBackground(Color.BLACK);
saveButton.setForeground(Color.WHITE);
saveButton.addMouseListener(this);
clearButton = new JButton("CLEAR");
clearButton.setPreferredSize(new Dimension(180,75));
clearButton.setBackground(Color.BLACK);
clearButton.setForeground(Color.WHITE);
clearButton.addMouseListener(this);
addButton = new JButton("ADD");
addButton.setPreferredSize(new Dimension(180,75));
addButton.setBackground(Color.BLACK);
addButton.setForeground(Color.WHITE);
addButton.addMouseListener(this);
moveButton = new JButton("MOVE");
moveButton.setPreferredSize(new Dimension(180,75));
moveButton.setBackground(Color.BLACK);
moveButton.setForeground(Color.WHITE);
moveButton.addMouseListener(this);
exitButton = new JButton("EXIT");
exitButton.setPreferredSize(new Dimension(180,75));
exitButton.setBackground(Color.BLACK);
exitButton.setForeground(Color.WHITE);
exitButton.addMouseListener(this);
// Add Buttons to Label Panel
labelPanel.add(loadButton);
labelPanel.add(saveButton);
labelPanel.add(clearButton);
labelPanel.add(addButton);
labelPanel.add(moveButton);
labelPanel.add(exitButton);
}
// Creates Draw Panel
public void createDrawPanel()
{
// Draw Panel to Draw Polygons
drawPanel = new JPanel();
drawPanel.setBackground(Color.BLACK);
drawPanel.setPreferredSize(new Dimension(600,600));
drawPanel.addMouseListener(this);
vertices = new ArrayList<>();
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.ORANGE);
for (Point spot : vertices)
{
g.fillOval(spot.x-SIZE, spot.y-SIZE, SIZE*2, SIZE*2);
}
g.drawString("Count: " + vertices.size(), 5, 15);
System.out.println("repaint is working?");
}
// Execute when Load button is clicked
public void loadButton()
{
System.out.println("Load Button CLICKED!!");
}
// Execute when Save button is clicked
public void saveButton()
{
System.out.println("Save Button CLICKED!!");
}
// Execute when Clear button is clicked
public void clearButton()
{
System.out.println("Clear Button CLICKED!!");
}
// Execute when Add button is clicked
public void addButton()
{
System.out.println("Add Button CLICKED!!");
}
// Execute when Move button is clicked
public void moveButton()
{
System.out.println("Move Button CLICKED!!");
}
public void mouseClicked(MouseEvent e)
{
if (e.getSource() == loadButton)
{
loadButton();
}
else if (e.getSource() == saveButton)
{
saveButton();
}
else if (e.getSource() == clearButton)
{
clearButton();
}
else if (e.getSource() == addButton)
{
addButton();
}
else if (e.getSource() == moveButton)
{
moveButton();
}
else if (e.getSource() == exitButton)
{
System.exit(0);
}
else if (e.getSource() == drawPanel)
{
System.out.println("TEST");
vertices.add(e.getPoint());
repaint();
}
}
// These are here because program wouldn't compile without them
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
// Main Function
public static void main(String[] args)
{
// Create Frame
new DrawPolygon();
}
}
Actually repaint is being called, but on the current DrawPolygon object, but since you don't seem to be displaying one of these paintComponent(...) won't ever be called. To clarify, your current class, DrawPolygon, extends JPanel, but it doesn't seem to have been added to any container that is part of your GUI hierarchy. Perhaps you want to add your current object, your this, to the GUI somewhere? In fact you probably should consider using your current object in place of the your drawPanel JPanel object. I would consider just deleting that variable entirely.
Also unrelated to your problem, you almost never want to use MouseListeners on JButtons where ActionListeners should instead be used.

Java Swing Repaint slow or not working

I am trying to draw graphics based on a button click using boolean flags. Before, I set the boolean value as a public static boolean type in the ShapeGUI class, and called it in ShapeListener using Shape.draw and that worked, although it took around 10 seconds to conjure a drawing.
Now I set the boolean flag inside the ShapeListener class itself. Now its either not repainting or is very slow. How can I make a drawing appear instantly when I click a button?
public class ShapeGUI extends JFrame
{
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public ShapeGUI()
{
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setLayout(new FlowLayout());
setLocationRelativeTo(null);
JMenuBar menu = new JMenuBar();
JMenu file = new JMenu("File");
menu.add(file);
JMenuItem save = new JMenuItem("Save Information");
JMenuItem exit = new JMenuItem("Exit");
file.add(save);
file.add(exit);
setJMenuBar(menu);
ShapeListener test = new ShapeListener();
JButton button = new JButton("Hello");
test.setBackground(Color.CYAN);
button.addActionListener(new ShapeListener());
test.add(button);
add(test);
//followed this person's advice
//First off, your drawing should be done in a paintComponent method override that is held in a class that extends JPanel. Next, this class could have a boolean variable that the paintComponent uses to decide if it will draw a rectangle or not. The button press simply sets the boolean variable and calls repaint on the drawing JPanel.
}
}
public class ShapeListener extends JPanel implements ActionListener
{
boolean draw = false;
Shape s = new Circle();
Shape a = new Rectangle();
#Override
public void actionPerformed(ActionEvent e)
{
draw = true;
repaint();
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(draw)
{
s.draw(g);
}
else
{
a.draw(g);
}
}
}
Your logic is a little off...
ShapeListener test = new ShapeListener(); // First instance
JButton button = new JButton("Hello");
test.setBackground(Color.CYAN);
button.addActionListener(new ShapeListener()); // Second instance...
test.add(button);
add(test);
You create two instance of the ShapeListener class, add one to the container and use the other as the action listener. Neither will know about each other, meaning that you can click to the cows come home, the first instance of ShapeListener will never change.
Also, unless you're planning to override the preferredSize method of the ShapeListener pane, I'd use something like a BorderLayout on the frame, to ensure that the panel is properly laid out, otherwise it will look like the panel isn't being painted...
Try something like...
public class ShapeGUI extends JFrame {
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public ShapeGUI() {
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JMenuBar menu = new JMenuBar();
JMenu file = new JMenu("File");
menu.add(file);
JMenuItem save = new JMenuItem("Save Information");
JMenuItem exit = new JMenuItem("Exit");
file.add(save);
file.add(exit);
setJMenuBar(menu);
setLayout(new BorderLayout());
ShapeListener test = new ShapeListener();
JButton button = new JButton("Hello");
test.setBackground(Color.CYAN);
button.addActionListener(test);
test.add(button);
add(test);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
new ShapeGUI();
}
});
}
public class ShapeListener extends JPanel implements ActionListener {
Shape s = new Ellipse2D.Float(0, 0, 20, 20);
Shape a = new Rectangle2D.Float(0, 0, 20, 20);
private Shape paintMe = a;
#Override
public void actionPerformed(ActionEvent e) {
paintMe = s;
repaint();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int x = (getWidth() - paintMe.getBounds().width) / 2;
int y = (getHeight() - paintMe.getBounds().height) / 2;
Graphics2D g2d = (Graphics2D) g.create();
g2d.translate(x, y);
g2d.draw(paintMe);
g2d.dispose();
}
}
}
instead...

Adding a JLabel on top of a JPanel

I attempting to place a .jpg icon on top of a JPanel in order to represent a board piece on a board. I have a GUI folder with the .java files and another folder containing the .jpg files.
--Major Edit--
Example Code
When a square is clicked a white icon is meant to be placed then black etc etc. This is a very basic example of what im trying to achieve
import java.awt.Dimension;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class gui extends JFrame implements MouseListener {
/**
*
*/
private static final long serialVersionUID = -973341728129968945L;
JLayeredPane layeredPane;
JPanel board;
JLabel piece;
int numSquares;
private boolean currentPlayer;
public gui(){
Dimension boardSize = new Dimension(600, 600);
numSquares = 6;
currentPlayer = true;
layeredPane = new JLayeredPane();
getContentPane().add(layeredPane);
layeredPane.setPreferredSize(boardSize);
layeredPane.addMouseListener(this);
board = new JPanel();
layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);
board.setLayout( new GridLayout(numSquares, numSquares) );
board.setPreferredSize( boardSize );
board.setBounds(0, 0, boardSize.width, boardSize.height);
for (int i = 0; i < (numSquares * numSquares); i++) {
JPanel square = new JPanel( new BorderLayout() );
square.setBorder(BorderFactory.createLineBorder(Color.black));
square.setBackground(Color.green);
board.add( square );
}
}
public static void main(String[] args) {
JFrame frame = new gui();
frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE );
frame.pack();
frame.setResizable(true);
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
#Override
public void mouseClicked(MouseEvent e) {
JPanel temp = (JPanel)board.findComponentAt(e.getX(), e.getY());
System.out.println(e.getX() + " " + e.getY());
if( currentPlayer ){
ImageIcon white = new ImageIcon("l/Images/white.jpg");
piece = new JLabel(white);
temp.add(piece);
}
else{
ImageIcon black = new ImageIcon( "/Images/black.jpg");
piece = new JLabel(black);
temp.add(piece);
}
currentPlayer = !currentPlayer;
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
}
}
Don't forget to revalidate and repaint if adding or removing components from a container. I've modified your SSCCE, and have gotten rid of the need to use images to make it runnable by folks who don't have access to your image files (like me!). Changes are noted by the // !! comments:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
public class Gui2 extends JFrame implements MouseListener {
private static final long serialVersionUID = -973341728129968945L;
JLayeredPane layeredPane;
JPanel board;
JLabel piece;
int numSquares;
private boolean currentPlayer;
// !!
private ImageIcon whiteIcon;
private ImageIcon blackIcon;
public Gui2() {
// !!
whiteIcon = createIcon(Color.white);
blackIcon = createIcon(Color.black);
Dimension boardSize = new Dimension(600, 600);
numSquares = 6;
currentPlayer = true;
layeredPane = new JLayeredPane();
getContentPane().add(layeredPane);
layeredPane.setPreferredSize(boardSize);
layeredPane.addMouseListener(this);
board = new JPanel();
layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);
board.setLayout(new GridLayout(numSquares, numSquares));
board.setPreferredSize(boardSize);
board.setBounds(0, 0, boardSize.width, boardSize.height);
for (int i = 0; i < (numSquares * numSquares); i++) {
// !! JPanel square = new JPanel(new BorderLayout());
JPanel square = new JPanel(new GridBagLayout()); // !!
square.setBorder(BorderFactory.createLineBorder(Color.black));
square.setBackground(Color.green);
square.setName(String.format("[%d, %d]", i % numSquares, i
/ numSquares)); // !!
board.add(square);
}
}
// !!
private ImageIcon createIcon(Color color) {
int width = 40;
int height = width;
BufferedImage img = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(color);
g2.fillOval(0, 0, width, height);
g2.dispose();
ImageIcon icon = new ImageIcon(img);
return icon;
}
public static void main(String[] args) {
JFrame frame = new Gui2();
frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
frame.pack();
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
#Override
// !!
public void mousePressed(MouseEvent e) {
JPanel temp = (JPanel) board.findComponentAt(e.getX(), e.getY());
System.out.println(e.getX() + " " + e.getY());
System.out.println(temp.getName()); // !!
if (currentPlayer) {
// !! ImageIcon white = new ImageIcon("l/Images/white.jpg");
// !! piece = new JLabel(white);
piece = new JLabel(whiteIcon); // !!
temp.add(piece);
} else {
// !! ImageIcon black = new ImageIcon("/Images/black.jpg");
// !! piece = new JLabel(black);
piece = new JLabel(blackIcon); // !!
temp.add(piece);
}
temp.revalidate(); // !!
temp.repaint(); // !!
currentPlayer = !currentPlayer;
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mouseClicked(MouseEvent arg0) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
}
Also class names should be capitalized, and also you should again make your ImageIcons once. Again, one ImageIcon can be shared by many JLabels. You'll also want to respond to mousePressed not mouseClicked as mouseClicked can be fussy, especially if you move the mouse between press down and mouse release.
Hopefully you've also seen the value of an SSCCE. :)

Categories