Placing a Jlabel At a Specific X,Y Coordinate on a Jpanel

Placing a JLabel at a specific x,y coordinate on a JPanel

You have to set your container's Layout to null:

myPanel.setLayout(null);

However is a good advise also to take a look at the Matisse Layout Manager, I guess it is called GroupLayout now. The main problem with absolute positioning is what happens when the window changes its size.

place a JLabel(s) at a desired location giving its coordinates

You can try using JDesktopPane or JLayeredPane, it works the same as the JPanels, but you won't use layouts, with these you will use Bounds, you always have to set the bound of a jlabel like this.

JLabel label = new JLabel("Hello");
label.setBounds(0, 0, 100, 20);
//label.setBounds(x, y, width, height);
pane.add(label)

if you need to move that label, then you can use something like

int xx = label.getBounds().getX();
int yy = label.getBounds().getY();
int ww = label.getBounds().getWidth();
int hh = label.getBounds().getHeight();

//to the right 10 units
xx+=10;
label.setBounds( xx, yy, ww, hh );

Positioning JLabel in JPanel below the image

Consider making use of the API's available functionality...

Take a look at:

  • JLabel#setHorizontalTextPosition
  • JLabel#setVerticalTextPosition
  • How to use labels

For example...

private ImageIcon image;

public TestLabel100(Integer size, String name) {
//...
JLabel textLabel = new JLabel(name);
textLabel.setIcon(image);
textLabel.setHorizontalTextPosition(JLabel.CENTER);
textLabel.setVerticalTextPosition(JLabel.SOUTH);
//textLabel.setBounds(100, 100, 70, 30);
//...
}

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//...

Drawing a JLabel with X,Y coordinate of the center

The way I eventually solved the problem is by offsetting the Location in the setLocation method. It's not the most beautiful of answers, but for now it'll do the job.

@Override
public void setLocation(int x, int y) {
super.setLocation(x-(size/2), y-(size/2));
}
@Override
public void setLocation(Point p) {
super.setLocation((int)p.getX()-size/2,(int)p.getY()-size/2);
}

If you have any suggestion to improve this answer, please comment or answer yourself.
There is no need to override paintComponent with this.

JLabel text position

By overriding the paintComponent method, text can be drawn in any position.

JLabel label = new JLabel(icon) {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("Hi", 10, 10); //these are x and y positions
}
};

Putting a JLabel on top of a JLabel in Java

People have asked for help with this before but the solutions that I found do not satisfy with me since they require me to set the frame layout to null, but I am using GridBagLayout

The frame is using a GridBagLayout.

You are adding the foreground JLabel, so the background JLabel. The background label can use any layout (including null) that you wish.

the foreground picture is displayed on top of the background, right in the middle of it.

That is because you are using a BorderLayout and are adding the foreground to the CENTER, which is the default when you don't specify a constraint.

How to change position of a JLabel?

I made a similar example just so you can get the basic jest of it, try copy pasting this in a new class called "LabelPlay" and it should work fine.

import java.awt.EventQueue;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class LabelPlay {

private JFrame frame;
private JLabel label;
private Random rand;

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LabelPlay window = new LabelPlay();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

public LabelPlay() {
initialize();
}

private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 659, 518);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);

label = new JLabel("YEEEHAH!");
label.setBounds(101, 62, 54, 21);
frame.getContentPane().add(label);

JButton btnAction = new JButton("Action!");
rand = new Random();
btnAction.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int a = rand.nextInt(90)+10;
int b = rand.nextInt(90)+10;
int c = rand.nextInt(640)+10;
int d = rand.nextInt(500)+10;
label.setBounds(a, b, c, d);
}
});
btnAction.setBounds(524, 427, 89, 23);
frame.getContentPane().add(btnAction);

}

}

If you want this to happen in a loop at certain times, you can just put it in a loop and use Thread.sleep(amount of miliseconds) in the loop before you run the code.

How do I get coordinates of a JPanel in an 8x8 GridLayout?

As noted in comments, I would use a grid of JLabel, and add and remove icons, and would give my JLabel a client property value that corresponds to the appropriate row and column (file and rank in chess terminology). I would give my ChessBoard class two String constants to use when putting client properties in and when later extracting them:

public static final String RANK = "rank";
public static final String FILE = "file";

You add the properties by simply calling putClientProperty(...) on the JLabel:

label.putClientProperty(RANK, rank);
label.putClientProperty(FILE, file);

where rank and file are appropriate Strings.

For example, please run this demo program to see what I mean:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class SimpleChess extends JPanel {
private ChessBoard chessBoard = new ChessBoard();
private JTextField rankField = new JTextField(3);
private JTextField fileField = new JTextField(3);

public SimpleChess() {
MyMouse myMouse = new MyMouse();
chessBoard.addMouseListener(myMouse);

rankField.setHorizontalAlignment(SwingConstants.CENTER);
rankField.setFocusable(false);
fileField.setHorizontalAlignment(SwingConstants.CENTER);
fileField.setFocusable(false);
JPanel topPanel = new JPanel();
topPanel.add(new JLabel("Rank:"));
topPanel.add(rankField);
topPanel.add(Box.createHorizontalStrut(40));
topPanel.add(new JLabel("File:"));
topPanel.add(fileField);

setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(chessBoard, BorderLayout.CENTER);
}

class MyMouse extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
Component c = chessBoard.getComponentAt(e.getPoint());
if (!(c instanceof JLabel)) {
return;
}
JLabel cell = (JLabel) c;
String rank = (String) cell.getClientProperty(ChessBoard.RANK);
String file = (String) cell.getClientProperty(ChessBoard.FILE);
// icon = cell.getIcon();
rankField.setText(rank);
fileField.setText(file);
}
}

private static void createAndShowGui() {
JFrame frame = new JFrame("Chess");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SimpleChess());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

@SuppressWarnings("serial")
class ChessBoard extends JPanel {
public static final String RANK = "rank";
public static final String FILE = "file";
private static final int ROWS = 8;
private static final int COLS = 8;
private static final Color COLOR_LIGHT = new Color(240, 201, 175);
private static final Color COLOR_DARK = new Color(205, 133, 63);
private static final Dimension CELL_SIZE = new Dimension(60, 60);
private JLabel[][] chessTable = new JLabel[ROWS][COLS];

public ChessBoard() {
// create chess table
setLayout(new GridLayout(ROWS, COLS));
for (int i = 0; i < chessTable.length; i++) {
for (int j = 0; j < chessTable[i].length; j++) {
String rank = String.valueOf((char) ('8' - i));
String file = String.valueOf((char) ('a' + j));
JLabel label = new JLabel();
label.setPreferredSize(CELL_SIZE);
label.setOpaque(true);
Color c = i % 2 == j % 2 ? COLOR_LIGHT : COLOR_DARK;
label.setBackground(c);
label.putClientProperty(RANK, rank);
label.putClientProperty(FILE, file);
chessTable[i][j] = label;
add(label);
}
}
}
}

I was working on a more extensive version, one that moved Icons around, but haven't finished it yet....

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class ChessLocation extends JPanel {
public static final String RANK = "rank";
public static final String FILE = "file";
public static final String MOUSE_PRESS = "mouse press";
public static final String PIECE_IMG_PATH = "https://upload.wikimedia.org"
+ "/wikipedia/commons/thumb/b/b2/Chess_Pieces_Sprite.svg"
+ "/320px-Chess_Pieces_Sprite.svg.png"; // for smaller pieces
// + "/640px-Chess_Pieces_Sprite.svg.png"; // for larger pieces
private static final int IMG_ROWS = 2;
private static final int IMG_COLS = 6;
private static final int ROWS = 8;
private static final int COLS = 8;
private static final Color COLOR_LIGHT = new Color(240, 201, 175);
private static final Color COLOR_DARK = new Color(205, 133, 63);
private Map<ChessPiece, Icon> pieceIconMap = new HashMap<>();
private JLabel[][] chessTable = new JLabel[ROWS][COLS];

public ChessLocation(BufferedImage img) {
// get chess images and put into pieceIconMap
int w = img.getWidth() / IMG_COLS;
int h = img.getHeight() / IMG_ROWS;
for (int row = 0; row < IMG_ROWS; row++) {
int y = (row * img.getHeight()) / IMG_ROWS;
for (int col = 0; col < IMG_COLS; col++) {
int x = (col * img.getWidth()) / IMG_COLS;
BufferedImage subImg = img.getSubimage(x, y, w, h);
Icon icon = new ImageIcon(subImg);

PieceColor color = PieceColor.values()[row];
PieceType type = PieceType.values()[col];
ChessPiece chessPiece = new ChessPiece(type, color);
pieceIconMap.put(chessPiece, icon);
}
}

// create chess table
setLayout(new GridLayout(ROWS, COLS));
Dimension pieceSize = new Dimension(w, h);
for (int i = 0; i < chessTable.length; i++) {
for (int j = 0; j < chessTable[i].length; j++) {
String rank = String.valueOf((char) ('8' - i));
String file = String.valueOf((char) ('a' + j));
JLabel label = new JLabel();
label.setPreferredSize(pieceSize);
label.setOpaque(true);
Color c = i % 2 == j % 2 ? COLOR_LIGHT : COLOR_DARK;
label.setBackground(c);
label.putClientProperty(RANK, rank);
label.putClientProperty(FILE, file);
chessTable[i][j] = label;
add(label);
}
}
resetBoard();

MyMouse myMouse = new MyMouse();
addMouseListener(myMouse);
addMouseMotionListener(myMouse);
}

public void resetBoard() {
for (JLabel[] row : chessTable) {
for (JLabel cell : row) {
cell.setIcon(null);
}
}
chessTable[0][0].setIcon(pieceIconMap.get(new ChessPiece(PieceType.ROOK, PieceColor.BLACK)));
chessTable[0][7].setIcon(pieceIconMap.get(new ChessPiece(PieceType.ROOK, PieceColor.BLACK)));
chessTable[7][0].setIcon(pieceIconMap.get(new ChessPiece(PieceType.ROOK, PieceColor.WHITE)));
chessTable[7][7].setIcon(pieceIconMap.get(new ChessPiece(PieceType.ROOK, PieceColor.WHITE)));

chessTable[0][1].setIcon(pieceIconMap.get(new ChessPiece(PieceType.KNIGHT, PieceColor.BLACK)));
chessTable[0][6].setIcon(pieceIconMap.get(new ChessPiece(PieceType.KNIGHT, PieceColor.BLACK)));
chessTable[7][1].setIcon(pieceIconMap.get(new ChessPiece(PieceType.KNIGHT, PieceColor.WHITE)));
chessTable[7][6].setIcon(pieceIconMap.get(new ChessPiece(PieceType.KNIGHT, PieceColor.WHITE)));

chessTable[0][2].setIcon(pieceIconMap.get(new ChessPiece(PieceType.BISHOP, PieceColor.BLACK)));
chessTable[0][5].setIcon(pieceIconMap.get(new ChessPiece(PieceType.BISHOP, PieceColor.BLACK)));
chessTable[7][2].setIcon(pieceIconMap.get(new ChessPiece(PieceType.BISHOP, PieceColor.WHITE)));
chessTable[7][5].setIcon(pieceIconMap.get(new ChessPiece(PieceType.BISHOP, PieceColor.WHITE)));

chessTable[0][3].setIcon(pieceIconMap.get(new ChessPiece(PieceType.QUEEN, PieceColor.BLACK)));
chessTable[0][4].setIcon(pieceIconMap.get(new ChessPiece(PieceType.KING, PieceColor.BLACK)));
chessTable[7][3].setIcon(pieceIconMap.get(new ChessPiece(PieceType.QUEEN, PieceColor.WHITE)));
chessTable[7][4].setIcon(pieceIconMap.get(new ChessPiece(PieceType.KING, PieceColor.WHITE)));

// put in pawns
for (int i = 0; i < PieceColor.values().length; i++) {
PieceColor color = PieceColor.values()[i];
ChessPiece piece = new ChessPiece(PieceType.PAWN, color);
for (int j = 0; j < COLS; j++) {
int row = 6 - 5 * i;
chessTable[row][j].setIcon(pieceIconMap.get(piece));
}
}
}

private class MyMouse extends MouseAdapter {
String rank = "";
String file = "";
Icon icon = null;

@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
rank = "";
file = "";
icon = null;
Component c = getComponentAt(e.getPoint());
if (!(c instanceof JLabel)) {
return;
}
JLabel cell = (JLabel) c;
if (cell.getIcon() == null) {
return;
}
rank = (String) cell.getClientProperty(RANK);
file = (String) cell.getClientProperty(FILE);
icon = cell.getIcon();
// cell.setIcon(null);
}
}

private static void createAndShowGui() {
BufferedImage img = null;
try {
URL imgUrl = new URL(PIECE_IMG_PATH);
img = ImageIO.read(imgUrl);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
ChessLocation chessLocation = new ChessLocation(img);
JFrame frame = new JFrame("Chess");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(chessLocation);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

enum PieceColor {
WHITE, BLACK
}

enum PieceType {
KING(100), QUEEN(9), BISHOP(3), KNIGHT(3), ROOK(5), PAWN(1);
private int value;

private PieceType(int value) {
this.value = value;
}

public int getValue() {
return value;
}
}

class ChessPiece {
private PieceType type;
private PieceColor color;

public ChessPiece(PieceType type, PieceColor color) {
this.type = type;
this.color = color;
}

@Override
public String toString() {
return "ChessPiece [type=" + type + ", color=" + color + "]";
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((color == null) ? 0 : color.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ChessPiece other = (ChessPiece) obj;
if (color != other.color)
return false;
if (type != other.type)
return false;
return true;
}

}


Related Topics



Leave a reply



Submit