I am trying to build a sudoku board. For now i am just trying to get the board to draw, i have tried just drawing lines but was told this was better....i have not gotten this to work as of yet. any hints on what i am doing wrong
import java.awt.Component;
import java.awt.GridLayout;
import javax.swing.*;
public class SudokuView4 extends JPanel {
int rows = 3;
int col = 3;
public JPanel container = new JPanel(new GridLayout(rows*col,rows*col));
public SudokuView4(SudokuBase sb) {
// TODO Auto-generated constructor stub
for(int r = 0; r < rows; r++){
for(int c = 0; c < col; c++){
//container.add(Region(rows,col));
//add(build);
//build.setSize(50, 50)
Region();
container.setVisible(true);
}
}
}
//class Region extends JPanel {
public void Region( ) {
//setLayout(new GridLayout(3,3));
//JPanel grid = new JPanel(new GridLayout(3,3));
//grid.setSize(50, 50);
for(int r1 = 0; r1 < rows; r1++){
for(int c1 = 0; c1 < col; c1++){
//JPanel grid = new JPanel();
JButton build = new JButton();
container.add(build);
//container.setVisible(true);
}
}
}
}
The JPanel container needs to be placed inside of a JFrame and updated once the buttons are added. This is if your goal is to run a Java application.
import java.awt.Component;
import java.awt.GridLayout;
import javax.swing.*;
public class SudokuView4 extends JPanel {
int rows = 3;
int col = 3;
public JPanel container = new JPanel(new GridLayout(rows*col,rows*col));
// added main for testing
public static void main(String [] args){
SudokuView4 sudoku = new SudokuView4();
}
public SudokuView4(/*SudokuBase sb*/) {
// TODO Auto-generated constructor stub
JFrame frame = new JFrame();
frame.add(container);
for(int r = 0; r < rows; r++){
for(int c = 0; c < col; c++){
//container.add(Region(rows,col));
//add(build);
//build.setSize(50, 50)
Region();
container.setVisible(true);
}
}
frame.setSize(300,300);
frame.setVisible(true);
}
//class Region extends JPanel {
public void Region( ) {
//setLayout(new GridLayout(3,3));
//JPanel grid = new JPanel(new GridLayout(3,3));
//grid.setSize(50, 50);
for(int r1 = 0; r1 < rows; r1++){
for(int c1 = 0; c1 < col; c1++){
//JPanel grid = new JPanel();
JButton build = new JButton();
container.add(build);
//container.setVisible(true);
}
}
}
}
Related
So I have a method makeBoard. I want to create a class called Board and move the makeBoard method into class Board, where it still adds the returned panel to the content pane of JFrame. Im not sure how to get the JPanel from Board class onto the JFrame content pane on the reversi class. Not sure how to proceed about this.
package reversi;
import java.io.*;
import java.util.*;
import java.lang.*;
import java.awt.*;
import javax.swing.*;
public class Reversi
{
public JFrame frame;
private JLabel userName1 = new JLabel("Enter First player: ");
private JLabel userName2 = new JLabel("Enter Second player: ");
private JTextField textUsername1 = new JTextField(15);
private JTextField textUsername2 = new JTextField(15);
private JButton startButton = new JButton("START");
private JButton [][] squares = new JButton[8][8];
public Reversi()
{
makeFrame();
makeMenuBar();
}
private void makePlayerPanel()
{
JPanel userInterface = new JPanel(new GridBagLayout());
userInterface.setBackground(Color.LIGHT_GRAY);
userInterface.setBorder(BorderFactory.createBevelBorder(0));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
userInterface.add(userName1, c);
c.gridx = 1;
userInterface.add(textUsername1, c);
c.gridx = 0;
c.gridy = 1;
userInterface.add(userName2, c);
c.gridx = 1;
userInterface.add(textUsername2, c);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
c.anchor = GridBagConstraints.SOUTH;
userInterface.add(startButton, c);
userInterface.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Players/Scoreboard"));
JPanel wrapper = new JPanel();
wrapper.add(userInterface);
frame.add(wrapper, BorderLayout.LINE_END);
frame.pack();
}
private void makeBoard()
{
JPanel board = new JPanel();
board.setBackground(Color.GRAY);
board.setBorder(BorderFactory.createBevelBorder(1));
board.setPreferredSize(new Dimension(750, 700));
board.setLayout(new GridLayout(8,8));
for(int i = 0; i< 8; i++){
for (int j = 0; j < 8; j++)
{
squares[i][j] = new JButton();
squares[i][j].setBackground(Color.GREEN);
board.add(squares[i][j]);
}
}
frame.add(board, BorderLayout.CENTER);
frame.pack();
}
public void makeFrame()
{
frame = new JFrame("Reversi Game");
frame.setSize(800,800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
makeBoard();
makePlayerPanel();
}
}
i did it like this:
public class Board {
private JButton [][] squares = new JButton[8][8];
public JFrame frame;
public JPanel makeBoard()
{
JPanel board = new JPanel();
board.setBackground(Color.GRAY);
board.setBorder(BorderFactory.createBevelBorder(1));
board.setPreferredSize(new Dimension(750, 700));
board.setLayout(new GridLayout(8,8));
for(int i = 0; i< 8; i++){
for (int j = 0; j < 8; j++)
{
squares[i][j] = new JButton();
squares[i][j].setBackground(Color.GREEN);
board.add(squares[i][j]);
}
}
return board;
}
}
in Reversi do like this:
Board b = new Board();
frame.add(b.makeBoard(), BorderLayout.CENTER);
frame.pack();
public class Board {
public void makeBoard(JPanel board)
{
board.setBackground(Color.GRAY);
board.setBorder(BorderFactory.createBevelBorder(1));
board.setPreferredSize(new Dimension(750, 700));
board.setLayout(new GridLayout(8,8));
for(int i = 0; i< 8; i++){
for (int j = 0; j < 8; j++)
{
squares[i][j] = new JButton();
squares[i][j].setBackground(Color.GREEN);
board.add(squares[i][j]);
}
}
frame.add(board, BorderLayout.CENTER);
frame.pack();
}
}
In Reversi class
public class Reversi
{
....
Board board = new Board();
board.makeBoard(new JPanle());
}
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.
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:
I need to update the text of different labels throughout the program.
Example: If my grid layout is (12,12) and I need to change the texts of a label at (2,5) how can I do this?
Maybe even a way to erase the label and add a new one at the same position.
Create a 2D array of JLabel
JLabel[][] labels = new JLabel[12][12];
// populate and add to container with GridLayout(12, 12)
...
// change property
JLabel label = labels[2][5];
label.setText(..)
"Maybe even a way to erase the label and add a new one at the same position."
No need, just change the properties of the existing one
UPDATE
See example here. Pay close attention to the method createButtonsPanel. Its where I access the label from the grid.
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestLabelGrid {
public TestLabelGrid() {
JLabel[][] labelGrid = createLabelGrid(6, 6);
JPanel labelPanel = createPanel(labelGrid);
JPanel buttonPanel = createButtonsPanel(labelGrid);
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(2, 1));
frame.add(labelPanel);
frame.add(buttonPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createPanel(JLabel[][] labels) {
int rows = labels.length;
int cols = labels[0].length;
JPanel panel = new JPanel(new GridLayout(rows, cols));
for (JLabel[] rowOfLabels: labels) {
for (JLabel label : rowOfLabels) {
panel.add(label);
}
}
return panel;
}
private JLabel[][] createLabelGrid(int rows, int cols) {
JLabel[][] labels = new JLabel[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
labels[i][j] = new JLabel("( " + i + " , " + j + " )");
}
}
return labels;
}
private JPanel createButtonsPanel(final JLabel[][] labels) {
int rows = labels.length;
int cols = labels[0].length;
JButton[][] buttons = new JButton[rows][cols];
JPanel panel = new JPanel(new GridLayout(rows, cols));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
String text = "( " + i + " , " + j + " )";
JButton button = new JButton(text);
buttons[i][j] = button;
final int jTemp = j;
final int iTemp = i;
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JLabel label = labels[iTemp][jTemp];
label.setForeground(Color.BLUE);
}
});
panel.add(button);
}
}
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new TestLabelGrid();
}
});
}
}
You can save a reference to each of your Labels, or perhaps use container.getComponents(), but I am unsure if that method has any guarantee on the order of the components in the array.
To swap components, you can instead add a container at each of the locations of the GridLayout, and change what component the container at that position contains.
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()