How would i be able to use gridlayout and panels to create a frame that resembles a checkered board pattern? it would seem that i can't create two panels with two diferent colors within the one for-loop.
import javax.swing.*;
import java.awt.*;
#SuppressWarnings("serial")
public class test extends JFrame {
public test() {
this.setSize(400, 400);
JPanel content = new JPanel(new GridLayout(4,4));
for(int i = 0; i < 8; i++) {
JPanel panel = new JPanel();
panel.setBackground(Color.RED);
content.add(panel);
JPanel panel2 = new JPanel();
panel.setBackground(Color.BLUE);
content.add(panel2);
}
// for(int i = 0; i < 8; i++) {
// JPanel panel = new JPanel();
// panel.setBackground(Color.BLUE);
// content.add(panel);
// }
this.add(content);
}
public static void main(String[] args) {
test app = new test();
app.setVisible(true);
app.setResizable(false);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
#SuppressWarnings("serial")
static class Test extends JFrame {
public Test() {
this.setSize(400, 400);
int size = 8;
JPanel content = new JPanel(new GridLayout(size,size));
for (int i = 0; i < size*size; ++i) {
JPanel panel = new JPanel();
panel.setBackground( i % 2 == i/size % 2 ? Color.RED : Color.BLUE);
content.add(panel);
}
this.add(content);
}
}
You can work directly on indices, you have to switch between colors every cell and starting for a different color for every row.
Typo (note the 2 in panel2):
panel2.setBackground(Color.BLUE);
Related
When I placed an array into mainJpanel it works correctly. I want to place an array into JScrollPane but it does not work. Please explain why.
import javax.swing.*;
import java.awt.*;
public class Window extends JFrame {
public Window() {
setLocation( 100,100);
setSize(300,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("FontView");
setVisible(true);
setLayout( new FlowLayout());
JPanel mainPanel = new JPanel();
setContentPane(mainPanel);
Method fontMassive = new Method();
//поехали
JPanel[] jPanels = new JPanel[3];
JLabel[] jLabels = new JLabel[3];
for (int i = 0; i < 3; i++) {
jPanels[i]=new JPanel();
jLabels[i] = new JLabel(fontMassive.getFonts(i));
jPanels[i].add(jLabels[i]);
}
JScrollPane scroll = new JScrollPane();
for (int i = 0; i < 3; i++) {
scroll.add(jPanels[i]);
}
mainPanel.add(scroll);
}
}
placed into mainPanel
placed into scroll
Just another Java programmer 's answer was right, i need to place an array into Panel and then place it into Srcoll.
Thank you guys for the answers.
Hi guys I'm using Eclipse and I'm trying to create a Connect4 Game Grid , which is an JPanel gridArray [6] [7]. I later add the different Panels for buttons and the grid into a main panel and add it into my frame.
My Problem:
I want to fill the gridArray JPanel with Pictures of an empty field(white color) but first of all i want to create a new Panel and insert it into my gridArray through a loop until gridArray has all 42 Panels inside it and is fully filled. I have my Code below but somehow it doesnt work, although my logic should be fine.
I tried it with using a helper Function to create a new JPanel and call the function for each loop in fillGrid();, basically calling it 42 times but it still wont work...
I will gladly appreciate some help!
package connect4;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GridTest extends JFrame {
JFrame mainWindow;
JPanel buttonPanel, mainPanel;
JPanel gridPanel;
JPanel emptyPanel;
JPanel panel1;
ImageIcon emptyBox;
JPanel[][] gridArray;
JLabel emptyLabel;
JButton arrow1,arrow2,arrow3,arrow4,arrow5,arrow6,arrow7;
public GridTest() {
createGameGrid();
fillGrid();
}
public void createGameGrid() {
//creating window and mainpanel
mainWindow = new JFrame("Connect 4");
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
//defining top panel with 7 buttons;
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 7));
arrow1 = new JButton("V");
arrow2 = new JButton("V");
arrow3 = new JButton("V");
arrow4 = new JButton("V");
arrow5 = new JButton("V");
arrow6 = new JButton("V");
arrow7 = new JButton("V");
buttonPanel.add(arrow1);
buttonPanel.add(arrow2);
buttonPanel.add(arrow3);
buttonPanel.add(arrow4);
buttonPanel.add(arrow5);
buttonPanel.add(arrow6);
buttonPanel.add(arrow7);
//create Grind Panel
gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(6,7));
mainPanel.add(buttonPanel, BorderLayout.NORTH);
mainPanel.add(gridPanel, BorderLayout.SOUTH);
mainWindow.add(mainPanel);
mainWindow.pack();
mainWindow.setLocationRelativeTo(null);
mainWindow.setVisible(true);
}
private JPanel greateOnePanel(){
//here we need to insert the icon which is in empty box into a newly created panel
//ifirst wanted to insert black panels do ensure it works as intended but it doesnt
JPanel panel = new JPanel();
panel.setBackground(Color.BLACK);
panel.setSize(50,50);
return panel;
}
//here we need to fill the grid with the panels created above from left to right...
public void fillGrid() {
for(int j = 0; j < 6; j++) {
for (int k = 0; k < 7; k++) {
gridPanel.add(greateOnePanel());
}
}
}
public static void main(String[] args) {
new GridTest();
}
}
i tried it with this method using gridArray, but it throws NullPointer Exeptions and wont fill the grid with simple textlabels "Hallo" (just for testing purposes)
public void fillGrid() {
for(int j = 0; j < 6; j++) {
for (int k = 0; k < 7; k++) {
JLabel label = new JLabel("Hallo");
gridArray[j][k] = new JPanel();
gridArray[j][k].setSize(50, 50);
gridArray[j][k].setBackground(Color.RED);
gridArray[j][k].add(label);
gridPanel.add(gridArray[j][k]);
}
}
}
Here is a short, self contained, code that should help with various aspects of the task.
There is no need for a panel in each cell. The only thing it helped with was setting a BG color. That can be done in a label as long as the background is set to opaque.
This code defines a SquareLabel which overrides getPreferredSize() to return the maximum of preferred width and height as the value of both (usually it is the width).
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class SquareLabelGrid {
int rows = 6;
int cols = 7;
JLabel[][] labelArray = new JLabel[cols][rows];
Font bigFont = new Font(Font.SANS_SERIF, Font.BOLD, 30);
Insets labelInsets;
SquareLabelGrid() {
JPanel gameBoard = new JPanel(new GridLayout(rows, cols));
// a border to make the cell boundaries more clear and add
// some space around the text
Border border = new CompoundBorder(
new LineBorder(Color.BLACK),new EmptyBorder(4,4,4,4));
for (int yy = 0; yy < rows; yy++) {
for (int xx = 0; xx < cols; xx++) {
JLabel l = getColoredSquareLabel(xx, yy);
labelArray[xx][yy] = l;
gameBoard.add(l);
l.setBorder(border);
}
}
JOptionPane.showMessageDialog(null, gameBoard);
}
private JLabel getColoredSquareLabel(int x, int y) {
SquareLabel label = new SquareLabel(
String.format("%1s,%1s", (x+1), (y+1)));
label.setFont(bigFont);
label.setOpaque(true); // so we can see the BG color
label.setBackground(Color.ORANGE); // I prefer orange!
// make the GUI less 'crowded'
label.setBorder(new EmptyBorder(4,4,4,4));
return label;
}
public static void main(String[] args) {
Runnable r = () -> {
new SquareLabelGrid();
};
SwingUtilities.invokeLater(r);
}
}
class SquareLabel extends JLabel {
SquareLabel(String label) {
super(label);
}
/* This will create a square component that accounts for the
size of the String / Icon it contains. No guesswork! */
#Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
int w = d.width;
int h = d.height;
int sz = w > h ? w : h;
return new Dimension(sz, sz);
}
}
The problem is that you have not initialized the grid array .
Otherwise it will throw Null pointer exception.
JPanel[][] gridArray = new JPanel[6][8];
Also set the preferred size of main panel to make the grids visible .
mainPanel.setPreferredSize(new Dimension(400, 200));
Here is what i can see when I run your code with the modifications mentioned here .
Also please execute it from main with following code .
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GridTest();
}
});
}
Can somebody tell me why after calling method getContentPane().add(grid[i][j]) I am not able to display the matrix of JLabels. There's only one "e" label displayed.
public class SudokuFrame extends JFrame implements ActionListener {
JButton generateButton;
JLabel[][] grid;
public SudokuFrame(){
setSize(300, 300);
setTitle("Sudoku");
setLayout(null);
generateButton = new JButton("Generate");
generateButton.setBounds(90, 220, 100, 30);
add(generateButton);
generateButton.addActionListener(this);
grid = new JLabel[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
grid[i][j] = new JLabel("e");
grid[i][j].setBounds(100, 100, 30, 30);
getContentPane().add(grid[i][j]);
}
}
}
public static void main(String[] args){
SudokuFrame frame = new SudokuFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
You're giving every JLabel the exact same bounds -- same size and same position and so every new label is placed right smack dab on top of the previously added ones.
Solution: don't use null layout. Why use this when the problem is perfectly suited for a GridLayout? In general you want to avoid using null layouts and setBounds as the layout managers will make your coding and your GUI much easier to manage. Let the layouts do the heavy lifting for you.
e.g.,
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.*;
public class SimpleSudoku extends JPanel {
private static final int GAP = 1;
private static final Font LABEL_FONT = new Font(Font.DIALOG, Font.PLAIN, 24);
private JLabel[][] grid = new JLabel[9][9];
public SimpleSudoku() {
JPanel sudokuPanel = new JPanel(new GridLayout(9, 9, GAP, GAP));
sudokuPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
sudokuPanel.setBackground(Color.BLACK);
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
grid[row][col] = new JLabel(" ", SwingConstants.CENTER);
grid[row][col].setFont(LABEL_FONT); // make it big
grid[row][col].setOpaque(true);
grid[row][col].setBackground(Color.WHITE);
sudokuPanel.add(grid[row][col]);
}
}
JPanel bottomPanel = new JPanel();
bottomPanel.add(new JButton("Regenerate"));
setLayout(new BorderLayout());
add(sudokuPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
private static void createAndShowGui() {
SimpleSudoku mainPanel = new SimpleSudoku();
JFrame frame = new JFrame("SimpleSudoku");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
I'm dumbfounded here. I have a JPanel (defBoardPanel) that I'm adding to a parent JPanel (GamePanel) as follows:
public GamePanel(SetupBoard sb) {
this.setLayout(new BorderLayout());
// this.setBackground(Color.yellow);
JPanel defBoardPanel = new JPanel();
defBoardPanel.setBackground(Color.yellow);
for (int r = 0; r < sb.boardSize; r++){
for (int c = 0; c < sb.boardSize; c++){
Cell c = new Cell(r, c);
c.label.setOpaque(true);
if (sb.getCell(r, c).status == sb.getCell(r,c).status.occupied){
c.label.setBackground(Color.black);
System.out.println("LABEL IS OCCUPIED");
}
else {
c.label.setBackground(Color.white);
}
defBoardPanel.add(c.label);
}
}
defBoardPanel.revalidate();
defBoardPanel.setVisible(true);
this.add(defBoardPanel, BorderLayout.WEST);
this.revalidate();
this.setVisible(true);
This panel is to be added to a JFrame (MainFrame), which is shown below. When the application is launched, the JFrame displays a different type of Panel (SetupBoard), with which the user sets up their game board. When they click "accept", the StartGame() method of the MainFrame is called, which should show the JPanels above.
public MainFrame() {
this.setLayout(new BorderLayout());
this.setSize(500, 500);
SetupBoard sb = new SetupBoard(10, this);
this.setContentPane(sb);
}
void startGame(SetupBoard sb){
GamePanel gp = new GamePanel(sb);
this.setContentPane(gp);
this.revalidate();
}
My issue is that the child panel (defBoardPanel) is not displaying. The GamePanel itself displays (which I've verified using the setBackground(Color.yellow) method you see commented out), but not the panel I've added onto it.
What stupid mistake am I overlooking here?
EDIT: startGame() is being called from within the SetupBoard class:
void startGame(){
mf.startGame(this);
}
where mf is a reference to the MainFrame that created the SetupBoard instance. The fact that the GamePanel displays at all confirms that this is being called correctly.
Seems to work ok if I trim the code I don't have. Most likely the issue is coming from what you are not showing us. Therefore, producing an SSCCE would greatly benefit you. Meanwhile, you can always take advantage (to find the differences with your code) of the following one, which is highly originated from yours (I filled some gaps as I could):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GamePanel extends JPanel {
private static final int COLS = 10;
private static final int ROWS = 10;
public GamePanel() {
this.setLayout(new BorderLayout());
// this.setBackground(Color.yellow);
JPanel defBoardPanel = new JPanel(new GridLayout(ROWS, COLS));
defBoardPanel.setBackground(Color.yellow);
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLS; c++) {
JLabel label = new JLabel((r + 1) + " " + (c + 1));
label.setOpaque(true);
if (Math.random() > 0.5) {
label.setBackground(Color.black);
label.setForeground(Color.WHITE);
System.out.println("LABEL IS OCCUPIED");
} else {
label.setBackground(Color.white);
}
defBoardPanel.add(label);
}
}
this.add(defBoardPanel, BorderLayout.WEST);
}
public static class MainFrame extends JFrame {
public MainFrame() {
this.setLayout(new BorderLayout());
this.setSize(500, 500);
}
void startGame() {
GamePanel gp = new GamePanel();
this.setContentPane(gp);
pack();
setVisible(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MainFrame mainFrame = new MainFrame();
mainFrame.startGame();
}
});
}
}
This code sequence replaces the GamePanel after it has been added to MainFrame
public MainFrame() {
this.setLayout(new BorderLayout());
this.setSize(500, 500);
SetupBoard sb = new SetupBoard(10, this); // invokes startGame
this.setContentPane(sb); <----- GamePanel replaced here
}
void startGame(SetupBoard sb) {
GamePanel gp = new GamePanel(sb);
this.setContentPane(gp);
this.revalidate();
}
I want to add multiple jpanels to jpanel.So i added a root panel to jscrollpane.and then added all individual jpanels to this root panel.I made jscrollpane's scrolling policy as needed.i.e HORIZONTAL_SCROLLBAR_AS_NEEDED,VERTICAL_SCROLLBAR_AS_NEEDED.
But the problem is all individual panels are not shown inside root panel.
Code:
JScrollPane scPanel=new JScrollPane();
JPanel rootPanel=new JPanel();
rootPanel.setLayout(new FlowLayout());
JPanel indPanel = new JPanel();
rootPanel.add(indPanel);
JPanel indPanel2 = new JPanel();
rootPanel.add(indPanel2);
//.....like this added indPanals to rootPanel.
scPanel.setViewPortView(rootPanel);
//scPanel.setHorizontalScrollPolicy(HORIZONTAL_SCROLLBAR_AS_NEEDED);
And one more thing is, as i scroll the scrollbar the panels are going out of jscrollpane area.
I am not able to see all individual panels,
Please suggest me.
Edit: code snippet from double post:
MosaicFilesStatusBean mosaicFilesStatusBean = new MosaicFilesStatusBean();
DefaultTableModel tableModel = null;
tableModel = mosaicFilesStatusBean.getFilesStatusBetweenDates(startDate, endDate);
if (tableModel != null) {
rootPanel.removeAll();
rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS));
for (int tempRow = 0; tempRow < tableModel.getRowCount(); tempRow++) {
int fileIdTemp = Integer.parseInt(tableModel.getValueAt(tempRow, 0).toString());
String dateFromTemp = tableModel.getValueAt(tempRow, 3).toString();
String dateToTemp = tableModel.getValueAt(tempRow, 4).toString();
int processIdTemp = Integer.parseInt(tableModel.getValueAt(tempRow, 5).toString());
int statusIdTemp = Integer.parseInt(tableModel.getValueAt(tempRow, 6).toString());
String operatingDateTemp = tableModel.getValueAt(tempRow, 7).toString();
MosaicPanel tempPanel =
new MosaicPanel(fileIdTemp, dateFromTemp, dateToTemp, processIdTemp, statusIdTemp, operatingDateTemp);
rootPanel.add(tempPanel);
}
rootPanel.revalidate();
}
The main reason, why you couldn't see your JPanel is that you are using FlowLayout as the LayoutManager for the rootPanel. And since your JPanel added to this rootPanel has nothing inside it, hence it will take it's size as 0, 0, for width and height respectively. Though using GridLayout such situation shouldn't come. Have a look at this code example attached :
import java.awt.*;
import javax.swing.*;
public class PanelAddition
{
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("Panel Addition Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 1));
JScrollPane scroller = new JScrollPane();
CustomPanel panel = new CustomPanel(1);
contentPane.add(panel);
scroller.setViewportView(contentPane);
frame.getContentPane().add(scroller, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
for (int i = 2; i < 20; i++)
{
CustomPanel pane = new CustomPanel(i);
contentPane.add(pane);
contentPane.revalidate();
contentPane.repaint();
}
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PanelAddition().createAndDisplayGUI();
}
});
}
}
class CustomPanel extends JPanel
{
public CustomPanel(int num)
{
JLabel label = new JLabel("" + num);
add(label);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(200, 50));
}
}
Don't use FlowLayout for the rootPanel. Instead consider using BoxLayout:
JPanel rootPanel=new JPanel();
// if you want to stack JPanels vertically:
rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS));
Edit 1
Here's an SSCCE that's loosely based on your latest code posted:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.*;
#SuppressWarnings("serial")
public class PanelsEg extends JPanel {
private static final int MAX_ROW_COUNT = 100;
private Random random = new Random();
private JPanel rootPanel = new JPanel();
public PanelsEg() {
rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS));
JScrollPane scrollPane = new JScrollPane(rootPanel);
scrollPane.setPreferredSize(new Dimension(400, 400)); // sorry kleopatra
add(scrollPane);
add(new JButton(new AbstractAction("Foo") {
#Override
public void actionPerformed(ActionEvent arg0) {
foo();
}
}));
}
public void foo() {
rootPanel.removeAll();
// rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS)); // only need to set layout once
int rowCount = random.nextInt(MAX_ROW_COUNT);
for (int tempRow = 0; tempRow < rowCount ; tempRow++) {
int fileIdTemp = tempRow;
String data = "Data " + (tempRow + 1);
MosaicPanel tempPanel =
new MosaicPanel(fileIdTemp, data);
rootPanel.add(tempPanel);
}
rootPanel.revalidate();
rootPanel.repaint(); // don't forget to repaint if removing
}
private class MosaicPanel extends JPanel {
public MosaicPanel(int fileIdTemp, String data) {
add(new JLabel(data));
}
}
private static void createAndShowGui() {
PanelsEg mainPanel = new PanelsEg();
JFrame frame = new JFrame("PanelsEg");
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();
}
});
}
}
This SSCCE works, in that it easily shows removing and adding JPanels to another JPanel that is held by a JScrollPane. If you're still having a problem, you should modify this SSCCE so that it shows your problem.