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:
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.
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();
}
}
i want to add 10 jlabel and 10 jbutton unto each jpanel. Now there are 10 jpanels which i want to add to a frame, so the jframe should show 100 jlabel, 100 jbutton with 10 jpanels.
My problem is that the frame only shows 10 jlabel and 10 jbutton. i dunno where am wrong.
here is my code
public class MultiPanel extends JFrame {
private JPanel[] panel;
private JLabel[] label;
private JButton[] button;
public MultiPanel() {
panel = new JPanel[10];
label = new JLabel[10];
button = new JButton[10];
for (int i = 0; i < label.length; i++) {
label[i] = new JLabel(String.valueOf(i + 1));
button[i] = new JButton("B");
label[i].setSize(50, 50);
panel[i] = new JPanel();
panel[i].setLayout(new FlowLayout(FlowLayout.CENTER));
panel[i].add(label[i]);
panel[i].add(button[i]);
add(panel[i]);
}
setLayout(new GridLayout(1, 10));
setSize(720, 560);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
MultiPanel m_pnl = new MultiPanel();
}
}
public class MultiPanel extends JFrame {
public MultiPanel() {
int increment = 0;
while(increment < 10){
JPanel toAdd = new JPanel();
for (int i = 0; i < 10; i++) {
JLabel l = new JLabel(String.valueOf(i + 1));
JButton b = new JButton("B");
l.setSize(50, 50);
toAdd.setLayout(new FlowLayout(FlowLayout.CENTER));
toAdd.add(l);
toAdd.add(b);
}
add(toAdd);
increment++;
}
setLayout(new GridLayout(1, 10));
setSize(720, 560);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
MultiPanel m_pnl = new MultiPanel();
}
}
Your logic was faulty... Try this. You have an outer whileloop that will create 10 JPanels like you want. The inner for loop adds 10 JLabels and JButtons to each JPanellike you want. Then you just add all ten JPanels to the main JPanel which is slapped on the JFrame. I have compiled and run this and it works
Before you were only adding one label and button to each panel. You had 10 panels each with 1 button and one label
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()