Make a grid layout displaying on JPanel - java

My task is to create checked board on JPAnel. For that purpose I'm trying to fill in parent JPanel with JPanels that has borders, but for some reason code doesnt give desired result and no error shown to do investigation why. Here is the code:
private static class GlassView extends JFrame {
private static int width = 600;
private static int height = 750;
public GlassView() {
this.setSize(width, height);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void workingFrame() {
int cols = 0;
int rows = 0;
String frameName = "Bot World";
WorkFrame workF = new WorkFrame(0, 0, frameName);
wfFrame = workF.newFrame();
wfFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
wfFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
wfFrame.setVisible(true);
JSplitPane splitPane = new JSplitPane();
splitPane.setSize(width, height);
splitPane.setDividerSize(0);
splitPane.setDividerLocation(150);
splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
JPanel panelLeft = createLftPanel();
JPanel panelRight = createRightPanel();
splitPane.setLeftComponent(panelLeft);
splitPane.setRightComponent(panelRight);
wfFrame.add(splitPane);
}
}
Here is the code for the panelRight which needs to be cheked:
public static JPanel createRightPanel() {
JPanel panel = new JPanel();
int rows = 100;
int cols = 100;
panel.setLayout(new GridLayout(rows, cols));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
JPanel pane = new JPanel();
pane.add(new JTextField("both"));
pane.setBorder(BorderFactory.createLineBorder(Color.black));
panel.add(new JButton(""));
}
}
return panel;
}
Any help will be appreciated. Thank you

Ok, my (second) guess is that the frame isn't laid out again after the call to
wfFrame.setVisible(true);
For me the example below:
public class Framed {
public static void workingFrame() {
JFrame frame = new JFrame();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.getContentPane().add(createRightPanel(10, 10));
frame.revalidate(); // <-- HERE
}
public static JPanel createRightPanel(int rows, int cols) {
JPanel panel = new JPanel(new GridLayout(rows, cols));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
JPanel pane = new JPanel();
pane.setBackground((i+j)%2==0?Color.black:Color.white);
panel.add(pane);
}
}
return panel;
}
public static void main(String... none) throws Exception {
workingFrame();
}
}
Shows a checker grid, but is you remove the call to
frame.revalidate(); // <-- HERE
Then the gird is not displayed (until you do something with the frame that causes it to lay out again). Better than calling revalidate() though may be to call setVisible only after all the components have been added.

Related

How can I redraw a grid on a JPanel if the frame gets bigger?

So basically I am trying to code a grid, that adjusts it's size everytime I make the JFrame bigger/smaller.
Now I don't want the grid to take the whole JFrame up, it also is supposed to only grow to a certain extend which I specified with the JPanels MaximumSize, I think.
Here's what I got so far:
public class GridMaker extends JPanel{
public int ROWS = 20; //this is because of 400/40 = 20
public int COLS = 20;
public static int cell_size = 40;
public Cell[][] cells;
public MazePanel(Color c) {
setMinimumSize(new Dimension(400, 400));
setBackground(c);
createCells();
}
//Create content of the array in form of cells
private void createCells() {
cells= new Cell[ROWS][COLS];
Cell cell;
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
cell= new Cell(i, j, cell_size, this); //cell class only contains coordinates where to
cells[i][j] = cell; //draw my lines
}
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Cell cell;
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
cell = cells[i][j];
if(cell != null) {
cell.draw(g);
}
}
}
repaint();
}
This Grid-Panel I then add onto another panel, called gridShow-Panel which is allowed to have a minimum size of (400, 500) and maximum size of (600, 800). My frame class adds the panel then with a simple gridbaglayout.
Now, I don't know where I can get the width and height of my gridShow-Panel, since only after I add it to my JFrame the measures get finalized, I think. Also I don't know how I can code it so, every time I make my Frame bigger the grid width and height values can get "send" over to my GridMaker class before showing the final grid...
public Frame() {
setTitle("Grid");
setMinimumSize(new Dimension(600, 600));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gridPanel= new GridPanel();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.8/1;
add(gridPanel, gbc);
getContentPane().addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
Component c = (Component)e.getSource();
HEIGHT = gridPanel.getHeight(); //Testing if I can get the height and width like this, though when used in ROWS = WIDTH/cell_size nothing works...
WIDTH = gridPanel.getWidth();
System.out.println("Height: "+HEIGHT);
System.out.println("Width: "+WIDTH);
}
});
setResizable(true);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
//Also my GridPanel class:
public class GridPanel extends JPanel{
public GridPanel() {
setMinimumSize(new Dimension(400, 500));
setPreferredSize(new Dimension(600, 800));
setLayout(new GridLayout(1,1));
GridMaker panel = new GridMaker(Color.white);
add(panel);
}
}
Any help would be very much appreciated :)

Resizing of JPanel with GridBagLayout does not work while in JScrollPane

I have a JPanel with GridBagLayout that is resizing properly when it is not in JScrollPane. But when I add it to the JScrollPane and try to resize the frame the resizing of the content just does not work and it acts like in AbsoluteLayout.
[Code of JPanel and JScrollPane][1]
//ACTIVITIES PANEL
aPanel = new JPanel();
aPanel.setPreferredSize(new Dimension(width, height/100*78));
aPanel.setMaximumSize(new Dimension(width,height/100*78));
aPanel.setMinimumSize(new Dimension(width,height/100*78));
//aPanel.setBackground(new Color(32,64,128));
aPanel.setLayout(new GridBagLayout());
gbcAP = new GridBagConstraints();
gbcAP.weightx = 1;
gbcAP.weighty = 1;
gbcAP.insets = new Insets(0,0,0,0);
gbcAP.anchor = GridBagConstraints.CENTER;
scrollPane = new JScrollPane(aPanel);
scrollPane.setPreferredSize(new Dimension(width,height/100*78));
scrollPane.setMinimumSize(new Dimension(width/2,(height/100*78)/2));
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
mainPanel.add(scrollPane,BorderLayout.CENTER);
loadPanel();
[This is method load JPanel within JScrollPane][2]
public void loadPanel() {
ArrayList<Activity> activities = activityController.getAllActivities();
int size = activities.size();
for(int i = 0 ; i != size; i++) {
int x = i;
int y = 0;
if(x < 5) {
gbcAP.gridx = x;
gbcAP.gridy = y;
aPanel.add(getMiniPanel(activities.get(i)),gbcAP);
scrollPane.repaint();
scrollPane.revalidate();
System.out.println("im here");
}
else {
x = 0;
i++;
gbcAP.gridx = x;
gbcAP.gridy = y;
aPanel.add(getMiniPanel(activities.get(i)),gbcAP);
}
}
}
Panel when its maximazed[1]
[1]: https://i.stack.imgur.com/tUaS1.png
Panel when its resized, JScrollPane even disappears
[2]: https://i.stack.imgur.com/NsQ14.png
UPDATE: THE PROBLEM IS SOLVED
I solved it by adding resizeListener to JPanel
public void componentResized(ComponentEvent e) {
aPanel.setPreferredSize(new Dimension(scrollPane.getWidth(), aPanel.getHeight()));
aPanel.revalidate();
aPanel.repaint();
scrollPane.repaint();
scrollPane.revalidate();
}

Remove gap between GridLayout elements

I am trying to create a 9x9 grid of JTextFields using GridLayout, however I am unable to remove the gap between the JTextFields within the GridLayout.
I have tried setting the horizontal and vertical gap to 0 using setHgap and setVgap methods, but the gap still exists, where am I going wrong ?
This is what I have tried so far,
class BoardGUI extends JFrame implements ActionListener {
private JPanel centerPanel, bottomPanel;
private JTextField grid[][];
private JButton loadBtn, saveBtn, solveBtn;
private GridLayout gridLayout;
private final int N = 9;
private final int MAX_HEIGHT = 450;
private final int MAX_WIDTH = 500;
public BoardGUI() {
super("Solver v2.0");
centerPanel = new JPanel();
bottomPanel = new JPanel();
grid = new JTextField[N][N];
for(int i=0; i<N; i++)
for(int j=0; j<N; j++)
grid[i][j] = new JTextField(1);
loadBtn = new JButton("Load");
saveBtn = new JButton("Save");
solveBtn = new JButton("Solve");
gridLayout = new GridLayout(N,N);
gridLayout.setVgap(0);
gridLayout.setHgap(0);
initLayout();
registerEventListeners();
}
private void initLayout() {
centerPanel.setLayout(gridLayout);
for(int i=0; i<N; i++)
for(int j=0; j<N; j++)
centerPanel.add(grid[i][j]);
bottomPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
bottomPanel.add(loadBtn);
bottomPanel.add(saveBtn);
bottomPanel.add(solveBtn);
this.setLayout(new BorderLayout());
this.getContentPane().add(centerPanel, BorderLayout.CENTER);
this.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
this.setSize(MAX_WIDTH, MAX_HEIGHT);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
private void registerEventListeners() {
loadBtn.addActionListener(this);
saveBtn.addActionListener(this);
solveBtn.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
}
}
Image:

Creating an Array of JButton

Basically I am trying to make a Lightout game! I want to make an array of JButtons
so I can keep track of the index of each of them (the reason being the state of each button is dependant on the state of the others)
so far I have:
JPanel panel = new JPanel();
setTitle("Memory");
setContentPane(panel);
setPreferredSize(new Dimension(300, 300));
panel.setLayout(new GridLayout(5,5));
JButton[][] buttons = new JButton[5][5] ;
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++) {
buttons[i][j] = new JButton();
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
But this isnt working how I expect it to. I just got a big blank JFrame when I run this. Any help would be appreciated
The attached code should fix it. You were creating button, but not adding it to the JFrame. I have edited the code to add action listener which accesses the id of the JButton and displays it , when you click it.
public class CodeSample extends JFrame {
private static final long serialVersionUID = -8134989438964195251L;
public CodeSample() {
JPanel panel = new JPanel();
setTitle("Memory");
setContentPane(panel);
setPreferredSize(new Dimension(300, 300));
panel.setLayout(new GridLayout(5, 5));
ButtonListener listener = new ButtonListener();
JButton[][] buttons = new JButton[5][5];
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
buttons[i][j] = new JButton();
buttons[i][j].setBackground(Color.black);
buttons[i][j].putClientProperty("id",
String.valueOf(i).concat(String.valueOf(j)));
buttons[i][j].addActionListener(listener);
panel.add(buttons[i][j]);
}
}
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(((JButton) e.getSource())
.getClientProperty("id"));
}
}
public static void main(String[] args) {
new CodeSample();
}
}

Java add buttons dynamically as an array [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
java - How would I dynamically add swing component to gui on click?
I want to add array of buttons dynamically.
I tried like this:
this.pack();
Panel panel = new Panel();
panel.setLayout(new FlowLayout());
this.add(panel);
panel.setVisible(true);
for (int i = 0; i < Setting.length; i++) {
for (int j = 0; j < Setting.width; j++) {
JButton b = new JButton(i+"");
b.setSize(30, 30);
b.setLocation(i * 30, j * 30);
panel.add(b);
b.setVisible(true);
}
}
but didn't get anything , what mistake did I make?
Edit
I have jFrame class "choices" on it i have a button , when I press the button, this is supposed to happen:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
structure.Setting s = new Setting(8, 8, 3, 1, 1);
Game g = new Game();
g.setSetting(s);
this.dispose();
g.show();
}
then i go to the Game class (also jFrame class) to the function setSetting and it is like this:
void setSetting(Setting s) {
this.setting = s;
structure.Game game = new structure.Game(setting);
JPanel panel = new JPanel(new GridLayout(5, 5, 4, 4));
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
JButton b = new JButton(String.valueOf(i));
panel.add(b);
}
}
add(panel);
pack();
setVisible(true);
}
structure.Setting setting;
}
You may use GridLayout to add equal height/width buttons:
public class Game extends JFrame {
private JPanel panel;
public Game(int rows,int cols,int hgap,int vgap){
panel=new JPanel(new GridLayout(rows, cols, hgap, vgap));
for(int i=1;i<=rows;i++)
{
for(int j=1;j<=cols;j++)
{
JButton btn=new JButton(String.valueOf(i));
panel.add(btn);
}
}
add(panel);
pack();
setVisible(true);
}
}
and code in button's handler should be:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Game g = new Game(5,5,3,3);
}
Note that you can also pass Setting object reference via Game constructor (when you may add widgets dynamically) instead of calling setSetting method.
The JPanel is already under the control of a layout manager, setting the size and position of the buttons is irrelevant, as they will changed once the panel is validated.
Try, instead, adding the panel AFTER you've populated it with buttons..
UPDATED with Example
Without further evidence, we are only guessing...You now have two people who have no issues.
Panel panel = new Panel();
for (int i = 0; i < Setting.length; i++) {
for (int j = 0; j < Setting.width; j++) {
jButton b = new jButton(i + "");
panel.add(b);
}
}
this.add(panel);
public class BadBoy {
public static void main(String[] args) {
new BadBoy();
}
public BadBoy() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
int buttonCount = (int) Math.round(Math.random() * 20);
int columnCount = (int) Math.round(Math.random() * 20);
JPanel buttonPane = new JPanel(new GridLayout(0, columnCount));
for (int i = 0; i < buttonCount; i++) {
JButton b = new JButton(i + "");
buttonPane.add(b);
}
frame.add(buttonPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ButtonPane extends JPanel {
public ButtonPane() {
}
}
}
I am guessing that this extens or is some kind of frame?
First step is to pack the frame by doing this.pack(); sets the frame size ti just fit all objects.
I assume you have set it to visible?
Now you should be able to see the buttons.
If you want a different layout use panel.setLayout(new SomeLayout);
Try to use setBounds(x,y,width,heigth) method
setBound method
for (int i = 0; i < 1; i++) {
for (int j = 0; j <1; j++) {
JButton b = new JButton("button");
b.setBounds(500, 500, 100, 20);
this.add(b);
}
}
this.repaint();
this.validate()

Categories