Here is my code below. It draw triangles on execution. I want to make a little change in it.
Change is
On execution there would be 1 triangle. but if i Click inside the triangle 1 then it draw other triangle. else dont draw.
I tried to do with the changes in g2d.draw(triangle2);
But it have problem. It just dont show triangle but draw it as hidden.
public class Triangle_shape extends JFrame implements ActionListener {
public static int x=0;
public static JButton btnSubmit = new JButton("Submit");
public static JButton change = new JButton("Change");
public Triangle_shape(){
}
public static void main(String[] args) {
TrianglePanel t= new TrianglePanel();
ClickListener cl= new ClickListener();
JFrame frame = new JFrame ();
final int FRAME_WIDTH = 500;
final int FRAME_HEIGHT = 500;
btnSubmit.addActionListener(cl);
frame.setSize (FRAME_WIDTH, FRAME_HEIGHT);
frame.setLayout(new BorderLayout());
frame.add(new TrianglePanel(), BorderLayout.CENTER);
frame.add(btnSubmit, BorderLayout.PAGE_END);
frame.add(change, BorderLayout.LINE_END);
frame.pack();
frame.repaint();
frame.setTitle("A Test Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static class TrianglePanel extends JPanel implements MouseListener{
private Polygon triangle,triangle2;
public TrianglePanel(){
//Create triangle
System.out.println("From Draw "+x);
triangle = new Polygon();
triangle.addPoint(150, 200);
triangle.addPoint(100, 100);
triangle.addPoint(200, 100);
triangle2 = new Polygon();
triangle2.addPoint(200, 300);
triangle2.addPoint(200, 200);
triangle2.addPoint(300, 200);
//Add mouse Listener
addMouseListener(this);
//Set size to make sure that the whole triangle is shown
setPreferredSize(new Dimension(300, 300));
}
/** Draws the triangle as this frame's painting */
public void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D)g;
System.out.println("From Graphics "+x);
g2d.draw(triangle);
g2d.draw(triangle2);
}
//Required methods for MouseListener, though the only one you care about is click
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
/** Called whenever the mouse clicks. */
public void mouseClicked(MouseEvent e) {
x++;
Point p = e.getPoint();
if(triangle.contains(p) )
System.out.println("1");
else if (triangle2.contains(p))
{ System.out.println("2");
}
else
{
System.out.println("Trianglhhhhhhhhhhhhhhhhhhpoint");
x--;}
}
}
private static class ClickListener implements ActionListener {
private int clickCount = 0;
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnSubmit) {
clickCount++;
if (clickCount == 1)
btnSubmit.setText("clicked!");
else
btnSubmit.setText("Inside Triangle " + x + " times!");
}
else {
//JOptionPane.showMessageDialog(MainClass.this, "You must click at least once!",
btnSubmit.setText("Error " + clickCount + " times!");
}
}
}
}
Try the below code, its a sample created from your own code.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MyTriangle{
static JFrame frame = new JFrame();
public static void main(String[] args)
{
frame.setSize(1000, 1500);
frame.setTitle("Triangle Draw");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//add panel to frame and make it visible
Polygon triangle1 = new Polygon();
triangle1.addPoint(100, 500); // first
triangle1.addPoint(600, 500);//last
triangle1.addPoint(350, 300);//middel
addTriangle(new Triangle(triangle1));
frame.setVisible(true);
}
public static void addTriangle(Triangle triangle1)
{
frame.add(triangle1);
}
static class Triangle extends JPanel implements MouseListener{
private Polygon triangle;
public Triangle(Polygon triangle)
{
this.triangle = triangle;
addMouseListener(this);
}
public void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D)g;
g2d.draw(triangle);
}
#Override
public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
if(triangle.contains(p))
{
Polygon triangle2 = new Polygon();
triangle2.addPoint(200, 300);
triangle2.addPoint(200, 200);
triangle2.addPoint(300, 200);
MyTriangle.addTriangle(new Triangle(triangle2));
Graphics2D g2d = (Graphics2D)this.getGraphics();
g2d.draw(triangle2);
}
}
}
}
Related
Got method paint() to draw mouse coordinates in JFrame in coordinates x=20, y=20. Is there a way to move rendering mouse coordinates to the title of the JFrame? Try to use jFrame.setTitle() but it want String as parametr.
jFrame.setTitle(g.drawString("Coordinates x:" + xCord + " y" + yCord, 20, 20)) not work.
Here is my code:
private static void paint() {
JComponent jComponent = new JComponent() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Font font = new Font("Comic Sans MS", Font.BOLD, 20);
g.setFont(font);
g.drawString("Coordinates x:" + xCord + " y" + yCord, 20, 20);
}
};
jFrame.add(jComponent);
jFrame.addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
xCord = e.getX();
yCord = e.getY();
jComponent.repaint();
}
});
}
Here's a simple example of a GUI that updates the title of the JFrame.
I just updated the title String with the coordinates from the mouseMoved method of the MouseMOtionListener.
Here's the runnable, contained, example.
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MouseCoordinatesTitle implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new MouseCoordinatesTitle());
}
private JFrame frame;
private String title;
public MouseCoordinatesTitle() {
this.title = "Coordinates: ";
}
#Override
public void run() {
frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(600, 400));
panel.addMouseMotionListener(new PositionListener());
return panel;
}
public void updateJFrameTitle(Point point) {
StringBuilder builder = new StringBuilder(title);
builder.append("X: ");
builder.append(point.x);
builder.append(", Y: ");
builder.append(point.y);
frame.setTitle(builder.toString());
}
public class PositionListener implements MouseMotionListener {
#Override
public void mouseMoved(MouseEvent event) {
Point point = event.getPoint();
updateJFrameTitle(point);
}
#Override
public void mouseDragged(MouseEvent event) {
}
}
}
I am trying to make the effect of gravity but it just looks like there are growing streaks of circles instead of individual circles moving down. I do not know how to remove the circles I have already drawn. There are no errors in the code btw.
import javax.swing.Timer;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
public class Tester {
static JFrame frame;
static JPanel panel;
static JButton button;
static ArrayList<Ellipse2D.Double> circles = new ArrayList<Ellipse2D.Double>();
static void init(){
frame = new JFrame();
panel = new JPanel(new BorderLayout());
button = new JButton("South");
panel.add(button, BorderLayout.SOUTH);
frame.add(panel);
frame.setVisible(true);
panel.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setBackground(Color.LIGHT_GRAY);
}
public static void main(String[] args) {
init();
class MeteorMover extends JPanel{
Ellipse2D.Double m;
int x = 40,y=40;
boolean isSettingGravity=true;
public MeteorMover(){
m = new Ellipse2D.Double(x,y,30,30);
}
void createNewMeteor(int n){
repaint();
}
void setGravity(){
isSettingGravity = true;
for (int i=0;i<circles.size();i++){
Ellipse2D.Double m = circles.get(i);
m= new Ellipse2D.Double(m.getX(),m.getY()+1,30,30);
circles.set(i, m);
}
repaint();
}
protected void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.WHITE);
if (isSettingGravity){
for (Ellipse2D.Double c:circles){
g2.draw(c);
}
isSettingGravity = false;
}
else{
m = new Ellipse2D.Double(x,y,30,30);
circles.add(m);
g2.fill(m);
g2.draw(m);
Random r = new Random();
x = r.nextInt(500);
y=r.nextInt(100);
}
}
}
final MeteorMover m = new MeteorMover();
panel.add(m);
panel.repaint();
class TimerListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent arg0) {
m.createNewMeteor(1);
}
}
TimerListener cListener = new TimerListener();
Timer timer = new Timer(1000,cListener);
timer.start();
class TimerListener2 implements ActionListener{
#Override
public void actionPerformed(ActionEvent arg0) {
m.setGravity();
}
}
TimerListener2 gListener = new TimerListener2();
Timer gTimer = new Timer(100,gListener);
gTimer.start();
}
}
call super.paintComponent(g);
protected void paintComponent(Graphics g) {
super.paintComponent(g);
read more about super.paintComponent .
There's no direct way to erase with graphics, you have two options:
If you always know which ellipse you need to erase, AND the ellipses never intersect, then you could keep in memory which is the next ellipse to erase and call g.setColor(bgColor); g.fill(erasedEllipse);
This is option is more reliable, You could keep an ArrayList of ellipses to draw. and you could clear all the pane and repaint all
the ellipses in the ArrayList, and if you want to erase one, you
just call ArrayList.remove(erasedElipseIndex)
I am designing a DFA related program.. so I want to put stuffs like Q0 or Q1 inside the circles but I don't know how.. Can someone please look at my code and tell me how? If its possible to directly put a name that will appear inside the circles, it would be great because I think its hard to set location for a JLabel.. here's my code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class midterm extends JFrame
{
JPanel mainpanel;
JPanel gamepanel;
JPanel controls;
ExitButtonListener end=new ExitButtonListener();
public midterm()
{
super("My DFA Design");
setSize(700,700);
setLocation(400,100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
panel();
this.getContentPane().add(mainpanel);
this.pack();
setVisible(true);
setSize(400,400);
}
public static void main(String[] args)
{
midterm frame=new midterm();
}
void panel()
{
mainpanel=new JPanel();
mainpanel.setLayout(new BorderLayout());
gamepanel=new JPanel();
gamepanel.setBorder(BorderFactory.createTitledBorder("Deterministic Finite Automata"));
gamepanel.setLayout(new GridLayout(2,3));
controls = new JPanel();
controls.setLayout(new BorderLayout());
controls.setBorder(BorderFactory.createTitledBorder("Control"));
JButton newGame = new JButton("Reset");
newGame.addActionListener(new NewButtonListener());
controls.add(newGame, BorderLayout.NORTH);
JButton exitGame = new JButton("Exit");
exitGame.addActionListener(end);
controls.add(exitGame, BorderLayout.SOUTH);
mainpanel.add(gamepanel, BorderLayout.CENTER);
mainpanel.add(controls, BorderLayout.EAST);
mainpanel.setVisible(true);
q1 c1=new q1();
q2 c2=new q2();
q3 c3=new q3();
gamepanel.add(c1);
gamepanel.add(c2);
gamepanel.add(c3);
}
class ExitButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
}
class NewButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
}
}
class q1 extends JPanel
{
final int radius=25;
public void paint(Graphics gr)
{
setBackground(Color.black);
gr.drawOval((100/2-radius),(100/2-radius), radius*2, radius*2);
}
}
class q2 extends JPanel
{
final int radius=25;
public void paint(Graphics gr)
{
setBackground(Color.black);
gr.drawOval((95/2-radius),(100/2-radius), radius*2, radius*2);
}
}
class q3 extends JPanel
{
final int radius=25;
public void paint(Graphics gr)
{
setBackground(Color.black);
gr.drawOval((250/2-radius),(50/2-radius), radius*2, radius*2);
}
}
}
Possible, yes, recommended, maybe not...
public class TestLabel {
public static void main(String[] args) {
new TestLabel();
}
public TestLabel() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
add(new CircleLable("1"));
add(new JLabel("What is the capital of SegWay?"));
}
}
public class CircleLable extends JLabel {
public CircleLable() {
init();
}
public CircleLable(String text) {
super(text);
init();
}
protected void init() {
setHorizontalAlignment(CENTER);
setVerticalAlignment(CENTER);
setBorder(new EmptyBorder(2, 2, 2, 2));
}
#Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width = Math.max(size.width, size.height);
size.height = size.width;
return size;
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Insets insets = getInsets();
int width = (getWidth() - (insets.left + insets.right));
int height = getHeight() - (insets.top + insets.bottom);
int radius = Math.max(width, height);
int x = insets.left + ((width - radius) / 2);
int y = insets.top + ((height - radius) / 2);
g2d.drawOval(x, y, radius, radius);
super.paintComponent(g2d);
g2d.dispose();
}
}
}
The problem I have with this solution is there is to much that can go wrong. Adding a Icon, changing the text alignment ect could through it off.
Personally, I would simply use a custom JPanel and render the text my self (making sure that the component was transparent first), but that's just me...
#MadProgrammer idea is better, but you can use dingbats for circled numbers: ➀, ➁, ➂, …
I am trying to create a swing program. In my program I want to achieve something like this: right click on a panel and select the menu "Draw rectangle" and program should draw a very simple rectangle on the panel. Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;
public class MainWindow extends JFrame {
JFrame frame = null;
AboutDialog aboutDialog = null;
JLabel statusLabel = null; //label on statusPanel
public MainWindow() {
frame = new JFrame("Project");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//MENUS
JMenuBar menuBar = new JMenuBar(); //menubar
JMenu menuDosya = new JMenu("Dosya"); //menus on menubar
JMenu menuYardim = new JMenu("Yardım"); //menus in menus
menuBar.add(menuDosya);
menuBar.add(menuYardim);
JMenuItem menuItemCikis = new JMenuItem("Çıkış", KeyEvent.VK_Q); //dosya menus
menuItemCikis.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
menuDosya.add(menuItemCikis);
JMenuItem menuItemYardim = new JMenuItem("Hakkında", KeyEvent.VK_H); //hakkinda menus
menuItemYardim.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JDialog f = new AboutDialog(new JFrame());
f.show();
}
});
menuYardim.add(menuItemYardim);
frame.setJMenuBar(menuBar);
//TOOLBAR
JToolBar toolbar = new JToolBar();
JButton exitButton = new JButton("Kapat");
toolbar.add(exitButton);
//STATUSBAR
JPanel statusPanel = new JPanel();
statusPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
frame.add(statusPanel, BorderLayout.SOUTH);
statusPanel.setPreferredSize(new Dimension(frame.getWidth(), 20));
statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.X_AXIS));
statusLabel = new JLabel("Ready.");
statusLabel.setHorizontalAlignment(SwingConstants.LEFT);
statusPanel.add(statusLabel);
//MAIN CONTENT OF THE PROGRAM
final JPanel mainContentPanel = new JPanel();
//RIGHT CLICK MENU
final JPopupMenu menuSag = new JPopupMenu("RightClickMenu");
JMenuItem menuRightClickRectangle = new JMenuItem("draw rectangle");
menuRightClickRectangle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//CircleShape cs=new CircleShape();
mainContentPanel.add(new CircleShape()); //trying to draw.
mainContentPanel.repaint();
//mainContentPanel.repaint(); boyle olacak.
}
});
JMenuItem menuRightClickCircle = new JMenuItem("Daire çiz");
menuSag.add(menuRightClickRectangle);
menuSag.add(menuRightClickCircle);
mainContentPanel.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
menuSag.show(e.getComponent(), e.getX(), e.getY());
statusLabel.setText("X=" + e.getX() + " " + "Y=" + e.getY());
}
}
});
JButton west = new JButton("West");
JButton center = new JButton("Center");
JPanel content = new JPanel(); //framein icindeki genel panel. en genel panel bu.
content.setLayout(new BorderLayout());
content.add(toolbar, BorderLayout.NORTH);
content.add(statusPanel, BorderLayout.SOUTH);
content.add(west, BorderLayout.WEST);
content.add(mainContentPanel, BorderLayout.CENTER);
frame.setContentPane(content);
frame.setPreferredSize(new Dimension(400, 300));
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
The problem is nothing is drawn on the panel. I guess there is an event loss in the program but i don't know how to solve this issue.
Please modify the code in the following way. Add a new class like this:
class MainPanel extends JPanel {
private List<Rectangle> rectangles = new ArrayList<Rectangle>();
private void addRectangle(Rectangle rectangle) {
rectangles.add(rectangle);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (Rectangle rectangle : rectangles) {
g2.drawRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
}
}
}
Then, instead of
final JPanel mainContentPanel = new JPanel();
you should do:
final MainPanel mainContentPanel = new MainPanel();
And the action listener for the menu item becomes something like this:
menuRightClickRectangle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// TODO: add your own logic here, currently a hardcoded rectangle
mainContentPanel.addRectangle(new Rectangle(10, 10, 100, 50));
mainContentPanel.repaint();
}
});
You can't do that by calling add method.To draw a shape you will have to override paintComponent method:
Example of drawing rectangle:
public void paintComponent(Graphics g){
g.setColor(Color.RED);
g.fillRect(50,50,50,50);
}
Hmm did a short example for you:
Test.java:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class Test {
private final JFrame frame = new JFrame();
private final MyPanel panel = new MyPanel();
private void createAndShowUI() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test().createAndShowUI();
}
});
}
}
MyPanel.java:
class MyPanel extends JPanel {
private final JPopupMenu popupMenu = new JPopupMenu();
private final JMenuItem drawRectJMenu = new JMenuItem("Draw Rectangle here");
private int x = 0, y = 0;
private List<Rectangle> recs = new ArrayList<>();
public MyPanel() {
initComponents();
}
private void initComponents() {
setBounds(0, 0, 600, 600);
setPreferredSize(new Dimension(600, 600));
popupMenu.add(drawRectJMenu);
add(popupMenu);
addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
checkForTriggerEvent(e);
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
private void checkForTriggerEvent(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
x = e.getX();
y = e.getY();
popupMenu.show(e.getComponent(), x,y);
}
}
});
drawRectJMenu.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
addRec(new Rectangle(x, y, 100, 100));
repaint();
}
});
}
public void addRec(Rectangle rec) {
recs.add(rec);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (Rectangle rec : recs) {
g2d.drawRect(rec.x, rec.y, rec.width, rec.height);
}
}
}
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. :)