Chess Board Coordinates - java

Im trying to create a chess program in Java. Right now, I have the board done together with the pieces present, which I can move with my mouse by dragging and dropping.
What I need is to add coordinates to the squares at the sides, like on a real board. Doesn't have to be anything fancy, just a visual. Since I drew my board not with Graphics, I don't know how to draw on top of the board I have created :/
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ChessGame extends JFrame implements MouseListener,
MouseMotionListener {
JLayeredPane layeredPane;
JPanel chessBoard;
JLabel chessPiece;
int xCoordinate;
int yCoordinate;
public ChessGame() {
Dimension boardSize = new Dimension(600, 600);
layeredPane = new JLayeredPane();
getContentPane().add(layeredPane);
layeredPane.setPreferredSize(boardSize);
layeredPane.addMouseListener(this);
layeredPane.addMouseMotionListener(this);
// adding chess board
chessBoard = new JPanel();
layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER);
chessBoard.setLayout(new GridLayout(8, 8));
chessBoard.setPreferredSize(boardSize);
chessBoard.setBounds(0, 0, boardSize.width, boardSize.height);
for (int i = 0; i < 64; i++) {
JPanel square = new JPanel(new BorderLayout());
chessBoard.add(square);
int row = (i / 8) % 2;
if (row == 0)
square.setBackground(i % 2 == 0 ? new Color(238, 221, 187)
: new Color(204, 136, 68));
else
square.setBackground(i % 2 == 0 ? new Color(204, 136, 68)
: new Color(238, 221, 187));
}
// Black pieces on the board
JLabel piece = new JLabel(new ImageIcon(getClass().getResource(
"Rooka8.png")));
JPanel panel = (JPanel) chessBoard.getComponent(0);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Knightb8.png")));
panel = (JPanel) chessBoard.getComponent(1);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Bishopc8.png")));
panel = (JPanel) chessBoard.getComponent(2);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Queend8.png")));
panel = (JPanel) chessBoard.getComponent(3);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Kinge8.png")));
panel = (JPanel) chessBoard.getComponent(4);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Bishopf8.png")));
panel = (JPanel) chessBoard.getComponent(5);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Knightg8.png")));
panel = (JPanel) chessBoard.getComponent(6);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Rookh8.png")));
panel = (JPanel) chessBoard.getComponent(7);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawna7.png")));
panel = (JPanel) chessBoard.getComponent(8);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pb7.png")));
panel = (JPanel) chessBoard.getComponent(9);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawnc7.png")));
panel = (JPanel) chessBoard.getComponent(10);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawnd7.png")));
panel = (JPanel) chessBoard.getComponent(11);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawne7.png")));
panel = (JPanel) chessBoard.getComponent(12);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawnf7.png")));
panel = (JPanel) chessBoard.getComponent(13);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawng7.png")));
panel = (JPanel) chessBoard.getComponent(14);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawnh7.png")));
panel = (JPanel) chessBoard.getComponent(15);
panel.add(piece);
// White pieces on the board
piece = new JLabel(new ImageIcon(getClass().getResource("Pawna2.png")));
panel = (JPanel) chessBoard.getComponent(48);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawnb2.png")));
panel = (JPanel) chessBoard.getComponent(49);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawnc2.png")));
panel = (JPanel) chessBoard.getComponent(50);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawnd2.png")));
panel = (JPanel) chessBoard.getComponent(51);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawne2.png")));
panel = (JPanel) chessBoard.getComponent(52);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawnf2.png")));
panel = (JPanel) chessBoard.getComponent(53);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawng2.png")));
panel = (JPanel) chessBoard.getComponent(54);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawnh2.png")));
panel = (JPanel) chessBoard.getComponent(55);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Rooka1.png")));
panel = (JPanel) chessBoard.getComponent(56);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Knightb1.png")));
panel = (JPanel) chessBoard.getComponent(57);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Bishopc1.png")));
panel = (JPanel) chessBoard.getComponent(58);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Queend1.png")));
panel = (JPanel) chessBoard.getComponent(59);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Kinge1.png")));
panel = (JPanel) chessBoard.getComponent(60);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Bishopf1.png")));
panel = (JPanel) chessBoard.getComponent(61);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Knightg1.png")));
panel = (JPanel) chessBoard.getComponent(62);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Rookh1.png")));
panel = (JPanel) chessBoard.getComponent(63);
panel.add(piece);
}
public void mousePressed(MouseEvent e) {
chessPiece = null;
Component c = chessBoard.findComponentAt(e.getX(), e.getY());
if (c instanceof JPanel)
return;
Point parentLocation = c.getParent().getLocation();
xCoordinate = parentLocation.x - e.getX();
yCoordinate = parentLocation.y - e.getY();
chessPiece = (JLabel) c;
chessPiece.setLocation(e.getX() + xCoordinate, e.getY() + yCoordinate);
chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight());
layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER);
}
// move pieces
public void mouseDragged(MouseEvent me) {
if (chessPiece == null)
return;
chessPiece.setLocation(me.getX() + xCoordinate, me.getY() + yCoordinate);
}
// drop a piece when mouse is released
public void mouseReleased(MouseEvent e) {
if (chessPiece == null)
return;
chessPiece.setVisible(false);
Component c = chessBoard.findComponentAt(e.getX(), e.getY());
if (c instanceof JLabel) {
Container parent = c.getParent();
parent.remove(0);
parent.add(chessPiece);
}
else
{
Container parent = (Container) c;
parent.add(chessPiece);
}
chessPiece.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public static void main(String[] args) {
JFrame frame = new ChessGame();
frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
frame.pack();
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

You should put your chessBoard JPanel into another BorderLayout-using JPanel.
This container JPanel will hold a GridLayout using JPanel on the left and on the bottom.
And these can hold JLabels which hold your row and column labels.
Edit
On second thought, better for the container JPanel to use a GridBagLayout so that the side JPanels will size correctly.
Edit 2
For example:
import java.awt.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class ChessGame2 extends JPanel {
private static final int RANKS = 8;
private static final int FILES = RANKS;
private static final int SIDE = 80;
private static final Dimension SQUARE_SIZE = new Dimension(SIDE, SIDE);
private static final Color LIGHT_COLOR = new Color(238, 221, 187);
private static final Color DARK_COLOR = new Color(204, 136, 68);
private static final int GAP = 5;
private JPanel chessBoard = new JPanel(new GridLayout(RANKS, FILES));
public ChessGame2() {
for (int rank = 0; rank < RANKS; rank++) {
for (int file = 0; file < FILES; file++) {
JPanel square = new JPanel();
square.setPreferredSize(SQUARE_SIZE);
Color bg = (rank % 2 == file % 2) ? LIGHT_COLOR : DARK_COLOR;
square.setBackground(bg);
chessBoard.add(square);
}
}
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(0, 2 * GAP, 0, 2 * GAP);
add(createRankPanel(), gbc);
gbc.gridx = 2;
gbc.anchor = GridBagConstraints.EAST;
add(createRankPanel(), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.SOUTH;
gbc.insets = new Insets(GAP, 0, GAP, 0);
add(createFilePanel(), gbc);
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.NORTH;
add(createFilePanel(), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.CENTER;
gbc.insets = new Insets(0, 0, 0, 0);
add(chessBoard, gbc);
}
private JPanel createFilePanel() {
JPanel filePanel = new JPanel(new GridLayout(1, 0));
for (int i = 0; i < FILES; i++) {
char fileChar = (char) ('A' + i);
filePanel.add(new JLabel(String.valueOf(fileChar), SwingConstants.CENTER));
}
return filePanel;
}
private JPanel createRankPanel() {
JPanel rankPanel = new JPanel(new GridLayout(0, 1));
for (int i = 0; i < RANKS; i++) {
int row = RANKS - i;
rankPanel.add(new JLabel(String.valueOf(row)));
}
return rankPanel;
}
private static void createAndShowGui() {
ChessGame2 mainPanel = new ChessGame2();
JFrame frame = new JFrame("Chess Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Which displays as:

The panel that you return from the chess board should be your custom class extending JPanel and in there you will want to override paintComponent().

Related

Panels take equal space

I have two panels. The first one looks like this.
public class BoardPanel extends JPanel
{
public BoardPanel()
{
setLayout(null);
this.setOpaque(false);
Button button = new JButton("..");
button.setLocation(...);
button.setSize(...);
add(button);
}
public void paintComponent( Graphics g )
{
/*
* Painting some stuff here.
*/
}
}
The other panel is something like this:
public class OtherPanel extends JPanel
{
public OtherPanel()
{
super();
this.setLayout(null);
this.setOpaque(false);
JPanel panel1 = new JPanel();
panel1.setLocation(...);
panel1.setSize(...);
panel1.setOpaque( .. );
JPanel panel2 = new JPanel();
panel2.setLocation(...);
panel2.setSize(...);
panel2.setOpaque( .. );
add(panel1):
add(panel2);
}
}
After that , I put both my panels in a frame. But I want my BoardPanel to occupy more screen than OtherPanel. So I used GridBagLayout for the frame
public class MainFrame extends JFrame
{
private GridBagLayout aGridLayout = new GridBagLayout();
private GridBagConstraints constraints = new GridBagConstraints();
public MainFrame()
{
super("Quoridor");
setLayout(gridLayout);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(1366, 768);
setVisible(true);
setResizable(false);
this.getContentPane().setBackground(Color.decode("#b2a6a6"));
BoardPanel boardPanel = new BoardPanel();
OtherPanel otherPanel = new OtherPanel();
this.addComponent(boardPanel, 1, 1, 2, 1);
this.addComponent(otherPanel, 1, 3, 1, 1);
}
public void addComponent(Component component , int row , int column , int width
, int height)
{
constraints.gridx = column;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
aGridLayout.setConstraints(component, constraints);
add(component);
}
}
The problem is , that the frame gives equal space to both panels , and dont give more space to the boardPanel.
Why is this happening ? Doest it have to do with the bounds of the panels ?
Here is a good tutorial on GridBagLayout: https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html . Also see the code below and screenshot. The anchor field positions the component at the first line. The weightx field gives more space to the columns for boardPanel. The ipady field specifies how much to add to the height of the component. Here, boardPanel gets most of the width and all of the height. The otherPanel panel gets half of the height.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GridExample {
private JFrame mainFrame;
private JPanel boardPanel, otherPanel;
public GridExample(){
mainFrame = new JFrame();
mainFrame.setSize(600,400);
mainFrame.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
boardPanel = new JPanel();
boardPanel.add(new JLabel("board panel"));
boardPanel.setBackground(Color.yellow);
otherPanel = new JPanel();
otherPanel.add(new JLabel("other panel"));
otherPanel.setBackground(Color.green);
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.75;
c.ipady = 400;
c.gridx = 0;
c.gridy = 0;
mainFrame.add(boardPanel, c);
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.25;
c.ipady = 200;
c.gridx = 1;
c.gridy = 0;
mainFrame.add(otherPanel, c);
mainFrame.setVisible(true);
}
public static void main(String[] args){
GridExample swingContainerDemo = new GridExample();
}
}

How to use any other layout manager for jscrollpane with it instead of using null layout

I had created this view by using null layout:
This is the Code i had used to create above layout
public class Page1311 extends JPanel {
// private JTable table;
// public JScrollPane pane=null;
public JPanel panel=null;
public JButton back=null;
/**
* Create the panel.
*/
public Page1311() {
setLayout(null);
back = new JButton("back");
back.setFont(new Font("Arial", Font.PLAIN, 20));
back.setBounds(10,10, 150, 27);
add(back);
List<List<String>> list=new ArrayList<List<String>>();
for(int j=0;j<=5;j++)
{
List<String> list1=new ArrayList<>();
list1.add("Honda Showroom"+j);
list1.add("Mandsaur");
list1.add("25 Chakrawati Colony Railway Station Road");
list1.add("Activa");
list1.add("2017");
list1.add("Honda");
list.add(list1);
}
getLayout(list,this);
back = new JButton("back");
back.setFont(new Font("Arial", Font.PLAIN, 20));
back.setBounds(10,10, 150, 27);
add(back);
}
public static void getLayout(List<List<String>> list,JPanel pane)
{
int i=0;
int x=100;
int y=100;
int height=20;
int width=200;
int size=list.size();
JLabel[] lblSName=new JLabel[size];
JLabel[] lblSAddress=new JLabel[size];
JLabel[] lblSCity=new JLabel[size];
JLabel[] lblVName=new JLabel[size];
JLabel[] lblVVersion=new JLabel[size];
JLabel[] lblVCompanies=new JLabel[size];
JButton[] lblGo=new JButton[size];
Iterator<List<String>> it=list.iterator();
while(it.hasNext())
{
System.out.println(x+" "+y+" "+width+" "+height+" "+i);
Iterator iit=it.next().iterator();
lblSName[i]= new JLabel();
lblSName[i].setText("Name:"+iit.next());
lblSName[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
lblSName[i].setBounds(x,y,width,height);
pane.add(lblSName[i]);
lblSCity[i] = new JLabel();
lblSCity[i].setText("City:"+iit.next());
lblSCity[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println((x+240)+" "+y+" "+width+" "+height+" "+i);
lblSCity[i].setBounds(x+240,y,width,height);
pane.add(lblSCity[i]);
lblSAddress[i]= new JLabel();
lblSAddress[i].setText("Address:"+iit.next());
lblSAddress[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println((x+470)+" "+y+" "+(width+256)+" "+height+" "+i);
lblSAddress[i].setBounds(x+470,y, width+256, height);
pane.add(lblSAddress[i]);
lblVName[i]= new JLabel();
lblVName[i].setText("Vehicle Name:"+iit.next());
lblVName[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println(x+" "+(y+35)+" "+width+" "+height+" "+i);
lblVName[i].setBounds(x,y+35,width, height);
pane.add(lblVName[i]);
lblVVersion[i] = new JLabel();
lblVVersion[i].setText("Vehicle Version:"+iit.next());
lblVVersion[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println((x+240)+" "+y+35+" "+width+" "+height+" "+i);
lblVVersion[i].setBounds(x+240,y+35, width, height);
pane.add(lblVVersion[i]);
lblVCompanies[i]= new JLabel();
lblVCompanies[i].setText("Vehicle Companies:"+iit.next());
lblVCompanies[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println((x+470)+" "+(y+35)+" "+(width+256)+" "+height+" "+i);
lblVCompanies[i].setBounds(x+470,y+35, width+256,height);
pane.add(lblVCompanies[i]);
lblGo[i]= new JButton("Go ");
lblGo[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 15));
System.out.println(x+" "+(y+70)+" "+(width-130)+" "+height+" "+i);
lblGo[i].setBounds(x,y+70,width-130, height);
pane.add(lblGo[i]);
i++;
y=y+160;
System.out.println("new height"+y);
}
}
public static void main(String[] args) {
JFrame frame=new JFrame();
frame.add(new Page1311());
frame.setExtendedState(frame.MAXIMIZED_BOTH);
frame.setLocation(0, 0);
frame.setVisible(true);
}
}
But now i found that i cant use jscrollpane with null layout manager.So i want to create same layout by using any other layout manager.Can any one please help with with this or you can provide me any other way to use jscrollpane with null layout manager.
Thanks in advance
I'd use a combination of a GridBagLayout for each 'show room' panel, then a single column GridLayout panel to stack the collection of show room panels in a single container. The second panel would go in the scroll pane.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class ShowRoomLayout {
private JComponent ui = null;
ShowRoomLayout() {
initUI();
}
private JPanel getShowRoomPanel(int num) {
JPanel p = new JPanel(new GridBagLayout());
p.setBorder(new TitledBorder("GridBagLayout"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
p.add(new JLabel("Name:Honda Showroom" + num), gbc);
gbc.gridx = 1;
p.add(new JLabel("City:Mandsaur"), gbc);
gbc.gridx = 2;
p.add(new JLabel("Address:25 Chakrawati Colony Railway Station Road"), gbc);
gbc.gridy = 1;
gbc.gridx = 0;
p.add(new JLabel("Vehicle Name:Activa"), gbc);
gbc.gridx = 1;
p.add(new JLabel("Vehicle Version:2017"), gbc);
gbc.gridx = 2;
p.add(new JLabel("Vehicle Companies:Honda"), gbc);
gbc.gridy = 2;
gbc.gridx = 0;
p.add(new JButton("Go"), gbc);
return p;
}
public void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
JPanel pList = new JPanel(new GridLayout(0, 1, 3, 3));
pList.setBorder(new TitledBorder("GridLayout"));
for (int ii = 1; ii < 21; ii++) {
pList.add(getShowRoomPanel(ii));
}
JScrollPane scrollPane = new JScrollPane(pList,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
ui.add(scrollPane);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
ShowRoomLayout o = new ShowRoomLayout();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
Dimension d = f.getSize();
f.setSize(new Dimension(d.width, 400));
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
JScrollPane has its own layout: ScrollPaneLayout. If you want to use any other, you don't set it on the scroll pane itself, you put a JPanel inside it and set the layout on that panel.
Another way without the need to set any layout manager for the JScrollPane is the method
JScrollPane.setViewportView(Component);
This is my preferred way. No size or layout handling on the fly.
If you want to place several Components to the same JScrollPane, just put a JPanel in between. The JPanel can have your preferred Layout.
If your layout uses a null layout manager, you need to tell the scroll pane the size of your component
JPanel pane = new JPanel(){
Dimension d = new Dimension(400, 400);
#Override
public Dimension getMinimumSize(){
return d;
}
#Override
public Dimension getPreferredSize(){
return d;
}
#Override
public Dimension getMaximumSize(){
return d;
}
#Override
public void paintComponent(Graphics g){
g.setColor(Color.RED);
g.fill3DRect(25, 25, 350, 350, true);
}
};
pane.setLayout(null);
JFrame frame = new JFrame("check");
frame.setSize(200, 200);
frame.add(new JScrollPane(pane));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
For this, I set the size of the pane to be 400, 400. The scroll pane will respect this. If you comment out the overriden methods, you'll see the scroll doesn't work anymore.
For OP to apply this technique they would just have to change the line where they add the panel to the JFrame.
frame.add(new JScrollPane(new Page1311()));
Since Page1311 doesn't use a layout manager then they need to override, getMin/Max/Preferred. as I did in my example. That would wrap the custom JPanel with a scroll pane, and the content would be scrollable.

Drawing & Changing an Image within a JPanel (from another class)

So yeah, I'm trying to write a rock paper scissors program with images, but I'm having trouble at putting in the pictures. There seems to only be a small white square on the JPanel.
Here's the code for my Main Class:
public class Practice extends JPanel implements ActionListener {
// Images
final ImageIcon rockPic = new ImageIcon("D:\\JOVO\\RPS\\src\\rock.png");
final ImageIcon paperPic = new ImageIcon("D:\\JOVO\\RPS\\src\\paper.png");
// variables
String results = null;
Image pic = null;
//Image Panel
ImagePanel youPic = new ImagePanel();
public Practice() {
// FRAME
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("RPS");
frame.setLayout(new BorderLayout());
frame.setVisible(true);
// SUPER JPANEL
setLayout(new GridBagLayout());
setBackground(Color.WHITE);
GridBagConstraints c = new GridBagConstraints();
frame.add(this);
// JPANELS - RPS title, JButton, PICTURES
JPanel rpsTitle = new JPanel();
c.fill = GridBagConstraints.CENTER;
c.gridy = 0;
c.gridx = 1;
rpsTitle.setBackground(Color.WHITE);
add(rpsTitle, c);
JPanel jbuts = new JPanel();
c.gridy = 3;
jbuts.setLayout(new BorderLayout());
add(jbuts, c);
// ImagePanels
c.gridy = 2;
c.gridx = 0;
add(youPic,c);
c.gridy = 0;
c.gridx = 1;
// JBUTTONS
JButton rock = new JButton(" Rock ");
JButton paper = new JButton(" Paper ");
JButton scissors = new JButton("Scissors");
jbuts.add(rock, BorderLayout.WEST);
jbuts.add(paper, BorderLayout.CENTER);
jbuts.add(scissors, BorderLayout.EAST);
paper.addActionListener(this);
JButton resultB = new JButton("RES");
c.gridy = 2;
c.weighty = 10;
add(resultB, c);
c.weighty = 0;
// FONTS
Font rps = new Font(null, Font.BOLD, 28);
Font labels = new Font(null, Font.ITALIC, 18);
// JLABELS
JLabel rpsTit = new JLabel("Rock, Paper, Scissors");
rpsTit.setFont(rps);
rpsTitle.add(rpsTit);
JLabel you = new JLabel("You: ");
you.setFont(labels);
JLabel com = new JLabel("Com: ");
com.setFont(labels);
c.gridy = 1;
c.gridx = 0;
add(you, c);
c.gridx = 2;
add(com, c);
// PICTURES
// comPic.setPic(rockPic);
// youPic.setPic(pic);
}
public String test(String name) {
// test the game
return results;
}
public static void main(String[] args) {
// main stuffs
Practice prac = new Practice();
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Works");
ImageIcon pic = null;
pic = paperPic;
youPic.setPic(pic);
}
}
And my other class:
public class ImagePanel extends JPanel {
Image pic = null;
public ImagePanel() {
repaint();
}
public void setPic(ImageIcon pic) {
// set picture for painting
this.pic = pic.getImage();
System.out.println("Set Pic");
repaint();
}
public void paintComponent(Graphics g) {
// paint
super.paintComponent(g);
System.out.println("Painting");
g.drawImage(pic, 0, 0, this);
}
}
Thanks in advance! :)

Why does GridBagLayout provide strange result?

I want the various components to spread out and fill the entire window.
Have you tried anything else? Yes, I tried GridLayout but then the buttons look huge. I also tried pack() which made the window small instead. The window should be 750x750 :)
What I was trying is this:
These 4 buttons on the top as a thin strip
The scroll pane with JPanels inside which will contain all the video conversion tasks. This takes up the maximum space
A JPanel at the bottom containing a JProgressBar as a thin strip.
But something seems to have messed up somewhere. Please help me solve this
SSCCE
import java.awt.*;
import javax.swing.*;
import com.explodingpixels.macwidgets.*;
public class HudTest {
public static void main(String[] args) {
HudWindow hud = new HudWindow("Window");
hud.getJDialog().setSize(750, 750);
hud.getJDialog().setLocationRelativeTo(null);
hud.getJDialog().setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel buttonPanel = new JPanel(new FlowLayout());
JButton addVideo = HudWidgetFactory.createHudButton("Add New Video");
JButton removeVideo = HudWidgetFactory.createHudButton("Remove Video");
JButton startAll = HudWidgetFactory.createHudButton("Start All Tasks");
JButton stopAll = HudWidgetFactory.createHudButton("Stop All Tasks");
buttonPanel.add(addVideo);
buttonPanel.add(startAll);
buttonPanel.add(removeVideo);
buttonPanel.add(stopAll);
JPanel taskPanel = new JPanel(new GridLayout(0,1));
JScrollPane taskScrollPane = new JScrollPane(taskPanel);
IAppWidgetFactory.makeIAppScrollPane(taskScrollPane);
for(int i=0;i<10;i++){
ColorPanel c = new ColorPanel();
c.setPreferredSize(new Dimension(750,100));
taskPanel.add(c);
}
JPanel progressBarPanel = new JPanel();
JComponent component = (JComponent) hud.getContentPane();
component.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
Insets in = new Insets(2,2,2,2);
gbc.insets = in;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 10;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
component.add(buttonPanel,gbc);
gbc.gridy += 1;
gbc.gridheight = 17;
component.add(taskScrollPane,gbc);
gbc.gridy += 17;
gbc.gridheight = 2;
component.add(progressBarPanel,gbc);
hud.getJDialog().setVisible(true);
}
}
Use this
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridbagConstraints.BOTH
Why not simply place three JPanels on top of one JPanel with BorderLayout as Layout Manager, where the middle JPanel with all custom panels with their respective sizes can be accommodated inside a JScrollPane, as shown in the below example :
import javax.swing.*;
import java.awt.*;
import java.util.Random;
/**
* Created with IntelliJ IDEA.
* User: Gagandeep Bali
* Date: 5/17/13
* Time: 6:09 PM
* To change this template use File | Settings | File Templates.
*/
public class PlayerBase
{
private JPanel contentPane;
private JPanel buttonPanel;
private JPanel centerPanel;
private CustomPanel[] colourPanel;
private JPanel progressPanel;
private JButton addVideoButton;
private JButton removeVideoButton;
private JButton startAllButton;
private JButton stopAllButton;
private JProgressBar progressBar;
private Random random;
public PlayerBase()
{
colourPanel = new CustomPanel[10];
random = new Random();
}
private void displayGUI()
{
JFrame playerWindow = new JFrame("Player Window");
playerWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new JPanel(new BorderLayout(5, 5));
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
addVideoButton = new JButton("Add New Video");
removeVideoButton = new JButton("Remove Video");
startAllButton = new JButton("Start all tasks");
stopAllButton = new JButton("Stop all tasks");
buttonPanel.add(addVideoButton);
buttonPanel.add(removeVideoButton);
buttonPanel.add(startAllButton);
buttonPanel.add(stopAllButton);
contentPane.add(buttonPanel, BorderLayout.PAGE_START);
JScrollPane scroller = new JScrollPane();
centerPanel = new JPanel(new GridLayout(0, 1, 2, 2));
for (int i = 0; i < colourPanel.length; i++)
{
colourPanel[i] = new CustomPanel(new Color(
random.nextInt(255), random.nextInt(255)
, random.nextInt(255)));
centerPanel.add(colourPanel[i]);
}
scroller.setViewportView(centerPanel);
contentPane.add(scroller, BorderLayout.CENTER);
progressPanel = new JPanel(new BorderLayout(5, 5));
progressBar = new JProgressBar(SwingConstants.HORIZONTAL);
progressPanel.add(progressBar);
contentPane.add(progressPanel, BorderLayout.PAGE_END);
playerWindow.setContentPane(contentPane);
playerWindow.pack();
//playerWindow.setSize(750, 750);
playerWindow.setLocationByPlatform(true);
playerWindow.setVisible(true);
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
#Override
public void run()
{
new PlayerBase().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class CustomPanel extends JPanel
{
public CustomPanel(Color backGroundColour)
{
setOpaque(true);
setBackground(backGroundColour);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(750, 100));
}
}
OUTPUT :

Nested JPanels and GridBagLayout Not "Packing" Components

I've attached a screenshot for which the following Border legend applies:
Yellow = JPanel with BorderLayout
Blue = JPanel with GridBagLayout
Fuchsia = JPanel with FlowLayout
There are two panels not blocked out in colors that warrant mentioning:
1) The title panel where the word "Primary" is displayed; this panel is at BorderLayout.NORTH in "Yellow" panel.
2) The image panel where the image of the device is located; this panel is a sibling to "Fuchsia"
"Blue" is at BorderLayout.CENTER in "Yellow" while "Fuchsia" and the image panel are given the following constraints:
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.NORTHWEST;
c.insets = new Insets(0, 10, 0, 0);
c.fill = GridBagConstraints.BOTH;
//"Blue".add(imagePanel, c);
c.weighty = 0.80;
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
//"Blue".add("Fuchsia", c);
As you can probably tell from the image, I'm trying to get rid of the "wasted" space in "Blue" right below "Fuchsia". I don't seem to be able to do it with GridBagConstraints, so am I just using the wrong LayoutManager? It looks to me like "Blue", who is at CENTER in the BorderLayout is just giving each child JPanel half of the available space and reserving the remainder space instead of contracting upward. What am I missing here? Is this simply a matter of setting a preferred or maximum size on "Fuchsia"? it doesn't seem like that will get me where I want to be, since the border around "Fuchsia" (which is covered by my color coding) is where I want the end of the component to be.
Have a look at this output, from this code example :
import java.awt.*;
import javax.swing.*;
public class LayoutTest
{
private void displayGUI()
{
JFrame frame = new JFrame("Layout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setOpaque(true);
contentPane.setBackground(Color.YELLOW);
contentPane.setLayout(new BorderLayout(2, 2));
JPanel topPanel = new JPanel();
topPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
JLabel headingLabel = new JLabel("Primary");
topPanel.add(headingLabel);
contentPane.add(topPanel, BorderLayout.PAGE_START);
JPanel centerPanel = new JPanel();
centerPanel.setOpaque(true);
centerPanel.setBackground(Color.BLUE);
centerPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0;
gbc.weighty = 0.2;
gbc.gridx = 0;
gbc.gridy = 0;
JPanel imagePanel = new JPanel();
JLabel imageLabel = null;
try
{
imageLabel = new JLabel(
new ImageIcon(
new java.net.URL(
"http://pscode.org/"
+ "tame/screenshot/"
+ "landscape/slider1.gif")));
}
catch(Exception e)
{
e.printStackTrace();
}
imagePanel.add(imageLabel);
centerPanel.add(imagePanel, gbc);
JPanel detailsPanel = new JPanel();
detailsPanel.setOpaque(true);
detailsPanel.setBackground(Color.WHITE);
detailsPanel.setBorder(
BorderFactory.createEmptyBorder(
5, 5, 5, 5));
detailsPanel.setLayout(new GridLayout(0, 1, 5, 5));
JLabel statusLabel = new JLabel("Chassis Status : ");
JLabel usageLabel = new JLabel("Bandwidth Usage : ");
JLabel fanLabel = new JLabel("Fan Status : ");
detailsPanel.add(statusLabel);
detailsPanel.add(usageLabel);
detailsPanel.add(fanLabel);
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 0.8;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridheight = 3;
centerPanel.add(detailsPanel, gbc);
contentPane.add(centerPanel, BorderLayout.CENTER);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new LayoutTest().displayGUI();
}
});
}
}
Without using GridBagLayout could be
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class NestedLayout {
private JFrame frame = new JFrame();
private JPanel yellowNorthPanel = new JPanel();
private JPanel yellowPanel = new JPanel();
private JPanel bluePanel = new JPanel();
private JPanel fuchsiaTopPanel = new JPanel();
private JPanel fuchsiaBottonPanel = new JPanel();
public NestedLayout() {
yellowNorthPanel.setBorder(new LineBorder(Color.yellow, 5));
yellowPanel.setLayout(new BorderLayout());
yellowPanel.setBorder(new LineBorder(Color.yellow, 5));
bluePanel.setLayout(new BorderLayout(5, 5));
bluePanel.setBorder(new LineBorder(Color.blue, 5));
fuchsiaTopPanel.setBorder(new LineBorder(Color.cyan, 5));
fuchsiaBottonPanel.setBorder(new LineBorder(Color.cyan, 5));
bluePanel.add(fuchsiaTopPanel, BorderLayout.NORTH);
bluePanel.add(fuchsiaBottonPanel);
yellowPanel.add(bluePanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(yellowNorthPanel, BorderLayout.NORTH);
frame.add(yellowPanel);
//frame.pack();
frame.setSize(400, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new NestedLayout();
}
});
}
}

Categories