Need advice for making a Grid with Java Swing - java

I am attempting to use Java Swing to create a Grid that allows me to access specific panels if I need to. The frame pulls up but there are no panels. I would like some advice on how to make the panels display in the frame while still allowing me to access the specific panel through the two dimensional array.
x=0;
y=0;
z=0;
JPanel[][] coordinate = new JPanel[5][5];
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.setSize(550,550);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
panel.setBackground(Color.WHITE);
panel.setLayout(new GridLayout(5,5));
for(int i = 0; i<25; i++) {
if(z == 5) {
z = 0;
x = 0;
y++;
}
coordinate[x][y] = new JPanel();
coordinate[x][y].setBorder(BorderFactory.createLineBorder(Color.BLACK, 10));
panel.add(coordinate[x][y]);
z++;
x++;
}
frame.add(panel);

Related

Panel fills the window in Java swing

I've added two 10x10 grids in a window but I cannot get them to appear in a smaller size. They just fill the entire window. How do I place both of them neatly in the middle in a smaller size so that there's room for some labels and buttons? I've pasted the code below for reference.
public static void main(String[] args) {
window = new JFrame();
window.setTitle("Battleship.exe");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setPreferredSize(new Dimension(600, 600));
P1_container = new JPanel(new GridLayout(10,10));
P1_container.setBorder(BorderFactory.createLineBorder(Color.black, 5));
compContainer = new JPanel(new GridLayout(10,10));
compContainer.setBorder(BorderFactory.createLineBorder(Color.black, 5));
grid = new JPanel[10][10];
for (int i =0; i< 10; i++) {
for (int j =0; j< 10; j++) {
grid[i][j] = new JPanel();
grid[i][j].setBackground(Color.white);
grid[i][j].setBorder(BorderFactory.createLineBorder(Color.blue, 2));
grid[i][j].setPreferredSize(new Dimension(25,25));
P1_container.add(grid[i][j]);
}
}
enemyGrid = new JPanel[10][10];
for (int i =0; i< 10; i++) {
for (int j =0; j< 10; j++) {
enemyGrid[i][j] = new JPanel();
enemyGrid[i][j].setBackground(Color.white);
enemyGrid[i][j].setBorder(BorderFactory.createLineBorder(Color.red, 2));
enemyGrid[i][j].setPreferredSize(new Dimension(25, 25));
compContainer.add(enemyGrid[i][j]);
}
}
GridLayout layout = new GridLayout(1, 2);
layout.setHgap(150);
mainPanel = new JPanel(layout);
mainPanel.add(P1_container);
mainPanel.add(compContainer);
window.add(mainPanel);
window.pack();
window.setVisible(true);
}
Your code had 24 compile errors. Once I fixed the compile errors, I modified one line and commented out one line to get this GUI.
Here's the complete runnable code.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BattleshipGUI {
public static void main(String[] args) {
JFrame window = new JFrame();
window.setTitle("Battleship.exe");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// window.setPreferredSize(new Dimension(600, 600));
JPanel P1_container = new JPanel(new GridLayout(10,10));
P1_container.setBorder(BorderFactory.createLineBorder(Color.black, 5));
JPanel compContainer = new JPanel(new GridLayout(10,10));
compContainer.setBorder(BorderFactory.createLineBorder(Color.black, 5));
JPanel[][] grid = new JPanel[10][10];
for (int i =0; i< 10; i++) {
for (int j =0; j< 10; j++) {
grid[i][j] = new JPanel();
grid[i][j].setBackground(Color.white);
grid[i][j].setBorder(BorderFactory.createLineBorder(Color.blue, 2));
grid[i][j].setPreferredSize(new Dimension(25,25));
P1_container.add(grid[i][j]);
}
}
JPanel[][] enemyGrid = new JPanel[10][10];
for (int i =0; i< 10; i++) {
for (int j =0; j< 10; j++) {
enemyGrid[i][j] = new JPanel();
enemyGrid[i][j].setBackground(Color.white);
enemyGrid[i][j].setBorder(BorderFactory.createLineBorder(Color.red, 2));
enemyGrid[i][j].setPreferredSize(new Dimension(25, 25));
compContainer.add(enemyGrid[i][j]);
}
}
GridLayout layout = new GridLayout(0, 2);
layout.setHgap(150);
JPanel mainPanel = new JPanel(layout);
mainPanel.add(P1_container);
mainPanel.add(compContainer);
window.add(mainPanel);
window.pack();
window.setVisible(true);
}
}
The key to using Swing layout managers is to nest your containers.
Nest mainPanel into another JPanel, one that uses a layout that helps you achieve your goal, say a BorderLayout with mainPanel placed into the BorderLayout.CENTER position. Then add the other gui components to this same outer JPanel at other BorderLayout locations.
If you don't want the mainPanel to expand, then use a different outer layout that does not expand, such as FlowLayout.

java; basic way to add components in custom locations (jframe)

I need to use Custom Locations for my JFrame components, I have tried looking in Java's Document about Using the insets object for making a custom location but i dont really understand that well...
if you got any ways to add components in custom locations or a good tutorial/web/other that i can easily learn how to use custom locations.
if you haven't tried null layout, then check out this code, may be of help
public static void main(String[] args) {
SwingUtilities.invokeLater(NullLayout::new);
}
NullLayout() {
JFrame frame = new JFrame("Basket Game");
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
for (int i = 0; i < 4; i++) {
JPanel strip = new JPanel();
strip.setMaximumSize(new Dimension(Integer.MAX_VALUE, 50));
strip.setBorder(BorderFactory.createTitledBorder("Strip " + i));
strip.add(new JLabel("Strip " + i));
mainPanel.add(strip);
}
JPanel gamearea = new JPanel();
gamearea.setLayout(null);
mainPanel.add(gamearea);
for (int i = 0; i < 5; i++) {
int x = i * 100, y = i * 100;
JPanel basket = new JPanel();
basket.setSize(200, 50);
basket.setLocation(x, y);
basket.setBackground(Color.YELLOW);
basket.add(new JLabel("x = " + x + ", y = " + y));
gamearea.add(basket);
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(mainPanel);
frame.pack();
frame.setResizable(false);
frame.setSize(600, 600);
frame.setVisible(true);
}
}

Sudoku Gui Issues

I am required to create a Suduku Game Board that looks like this:
Here are the requirements I need for this assignment, but am having some issues.
Use two for loops to draw the text fields instead of brute-force of listing 81 text fields. You should do something like:
for (int k = 1; k <= 9; k++)
{
JPanel level2 = new JPanel();
….
for (int i = 1; i <= 9; i++)
{
JTextField text = new JTextField();
…
}
gridPanel.add(level2);
}
I need 2 classes in
an application class named TestSudoku and a work class named SudokuLayout.
Implement the following visual gadgets and write listeners for them. These gadgets have the following behaviors:
Button “Reset”---when the button is clicked, the program will clear the text area, then output the string “Reset button clicked!” to the text area.
Button “Hint”---when the button is clicked, the program will clear the text area, then output the string “Hint button clicked!” to the text area.
Combobox “Difficulty”---when an item is selected, the program will clear the text area, then output the selected item name to the text area.
implement the listeners using loosely coupled methods (private listener class or private adapter class).
This is what I currently have..
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
public class SudokuLayout extends JFrame {
public SudokuLayout() {
JPanel board = new JPanel(new GridLayout(9, 9));
add(board);
JPanel[][] squares = new JPanel[9][9];
Border border = BorderFactory.createLineBorder(Color.BLACK);
for (int row = 1; row < 9; row++) {
for (int col = 1; col < 9; col++) {
squares[row][col] = new JPanel();
board.add(squares[row][col]);
}
}
JPanel menu = new JPanel();
menu.add(new JButton("Reset"));
menu.add(new JButton("Hint"));
menu.add(new JButton("Solve"));
menu.add(new JButton("New Puzzle"));
add(menu);
}
public static void main(String[] args) {
/** Create a frame and set its properties*/
JFrame frame = new SudokuLayout();
frame.setTitle("Sudoku");
frame.setSize(600, 600);
frame.setLocationRelativeTo(null); //Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
The problem is that, with my current version, the right menu shows horizontally and I cannot see the grid. Moreover, I don't know how to add the output area.
When facing this kind of frames with Swing you need to divide the frame in sections and treat them separately. I mean, by looking at the image you can easily identify the Sudoku, the menu, and the output. Thus, your answer should try to first create each of them separately and then join them.
Considering this, you must notice:
There are 3 main components: sudoku, menu, and output
The 3 main components may use a BorderLayout since they are probably at WEST, EAST and SOUTH
The sudoku component is a 3x3 grid of 3x3 smaller grids (so you can change the black-border).
The menu component is a 5x1 grid with buttons in each position
The output component is a single text frame
So, you may need to change something to get the exact behaviour (button sizes and margins, options on the difficulty ComboBox) but your solution should look like this:
public class SudokuLayout extends JFrame {
public SudokuLayout() {
// Create panel for Sudoku
JPanel board = new JPanel();
board.setLayout(new GridLayout(3, 3));
board.setBorder(BorderFactory.createLineBorder(Color.BLACK));
for (int row = 0; row < 3; ++row) {
for (int col = 0; col < 3; ++col) {
JPanel box = new JPanel(new GridLayout(3, 3));
box.setBorder(BorderFactory.createLineBorder(Color.BLACK));
for (int cell = 0; cell < 9; ++cell) {
box.add(new JTextField(2));
}
board.add(box);
}
}
// Create difficulty combo box
JComboBox<String> difficultyChoices = new JComboBox<>(new String[] { "Hard", "Easy" });
difficultyChoices.setSelectedIndex(0);
// Create menu panel
JPanel menu = new JPanel();
menu.setLayout(new GridBagLayout());
GridBagConstraints menuConstraints = new GridBagConstraints();
menuConstraints.anchor = GridBagConstraints.WEST;
menuConstraints.weightx = 0.5;
menuConstraints.weighty = 0.5;
menuConstraints.gridwidth = 2;
menuConstraints.gridx = 2;
menuConstraints.gridy = 0;
menu.add(new JButton("Reset"), menuConstraints);
menuConstraints.gridx = 2;
menuConstraints.gridy = 1;
menu.add(new JButton("Hint"), menuConstraints);
menuConstraints.gridx = 2;
menuConstraints.gridy = 2;
menu.add(new JButton("Solve"), menuConstraints);
menuConstraints.gridx = 2;
menuConstraints.gridy = 3;
menu.add(new JButton("New Puzzle"), menuConstraints);
menuConstraints.weighty = 1.0;
menuConstraints.gridx = 2;
menuConstraints.gridy = 4;
menu.add(new JLabel("Difficulty:"), menuConstraints);
menuConstraints.fill = GridBagConstraints.HORIZONTAL;
menuConstraints.weightx = 0.5;
menuConstraints.weighty = 0.5;
menuConstraints.gridwidth = 2;
menuConstraints.gridx = 0;
menuConstraints.gridy = 5;
menu.add(difficultyChoices, menuConstraints);
// Create output panel
JTextArea output = new JTextArea(5, 20);
output.setEditable(false);
output.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLUE), "Output Area"));
// Join the 3 panels on the frame
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
cp.add(board, BorderLayout.WEST);
cp.add(menu, BorderLayout.EAST);
cp.add(output, BorderLayout.SOUTH);
}
public static void main(String[] args) {
// Create a frame and set its properties
JFrame frame = new SudokuLayout();
frame.setTitle("TestSudoku");
frame.setSize(600, 600);
frame.setLocationRelativeTo(null); // Center the frame
// Setup the window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
UPDATE: I update my answer with a GridBagLayout for the menu and a TextArea with border for the output.

JScrollPane is not Working in JPanel

I have to use JScrollPane in my Project but it is not working.
I have pasted my code where I use a JSCrollPane in my main JPanel.
frame = new JFrame();
frame.setBounds(100, 100, 1179, 733);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane_1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane_1.setBounds(0, 0, 1163, 694);
frame.getContentPane().add(scrollPane_1);
JPanel panel = new JPanel();
scrollPane_1.setViewportView(panel);
panel.setLayout(null);
Setting the layout to Null means you need to handle the placement manually --> Specify the pixel location and handle the size of the container.
A layout manager handles this placement for you. The manager calculates its preferred size based on its content. The ScrollPane uses this calculated size from the layout manager.
This means you should use a layout manager, place your components within it. The rest should work automatically.
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(500, 500);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(30, 15));
for (int row = 0; row < 30; row++) {
for (int col = 0; col < 15; col++) {
panel.add(new Button("Button" + row + "/" + col));
}
}
frame.getContentPane().add(new JScrollPane(panel));
frame.setVisible(true);
}
I am not sure which layout you are using, but you need to set your panel layout something like this
panel.setLayout(new FormLayout(
"default:grow",
"fill:default:grow"));

JList is not Showing Up

private static void initGUI(char[][] code){
int width = (int) (code[0].length * new JLabel().getFont().getSize2D());
int height = (int) (code.length * new JLabel().getFont().getSize2D()) + 200;
gridgui = new JLabel[code.length][code[0].length];
for(int x = 0; x < code.length; ++x){
for(int y = 0; y < code[0].length; ++y){
gridgui[x][y] = new JLabel();
gridgui[x][y].setText(""+code[x][y]);
gridgui[x][y].setBackground(Color.WHITE);
gridgui[x][y].setOpaque(true);
}
}
listModel = new DefaultListModel<Integer>();
listModel.addElement(5);
//Create the list and put it in a scroll pane.
stacklist = new JList<Integer>(listModel);
JScrollPane listScrollPane = new JScrollPane(stacklist);
listScrollPane.getViewport().setView(stacklist);
frame = new JFrame("Befunge 93! Wow!");
gridpanel = new JPanel();
gridpanel.setLayout(new GridLayout(gridgui.length, gridgui[0].length));
gridpanel.setPreferredSize(new Dimension(width, height));
for(int x = 0; x < gridgui.length; ++x){
for(int y = 0; y < gridgui[0].length; ++y){
gridpanel.add(gridgui[x][y]);
}
}
stackpanel = new JPanel();
stackpanel.setLayout(new GridLayout(100, height));
stackpanel.setPreferredSize(new Dimension(width, height));
stackpanel.add(listScrollPane);
JPanel container = new JPanel();
container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS));
container.add(gridpanel);
container.add(stackpanel);
frame.add(container);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
I would have put less and more compact code, but I honestly have no clue where the problem could be.
The issue is that the items in the JList stacklist don't show up. It just looks like this:
(source: mediafire.com)
(with the arrow pointing to the JList)
I've been troubleshooting this for hours and I fear it's something painfully obvious that will cause my to quit programming forever.
I think you need to understand how GridLayout works...
stackpanel.setLayout(new GridLayout(100, height));
Basic says, create me a grid which has 100 rows and height number of columns...This is reserving space for each cell...
If I change it to...
stackpanel.setLayout(new GridLayout(code.length, 1));
I get...
But I'm only guess at what it is you're trying to achieve...
You should also avoid using setPreferredSize where you can

Categories