How to place an array of JPanels into JScrollPane? - java

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.

Related

How to Create JPanels in a Loop and insert them in JPanel Array [] []

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();
}
});
}

Java JPanels not visible in Frame

Can someone please explain why my frame only shows p2 and not p1?
This happens to me often and I know I'm missing something.
public class Exercise_16_4 extends JFrame {
private static final long serialVersionUID = 1L;
JLabel[] labels = new JLabel[3];
JTextField[] textFields = new JTextField[3];
JButton[] buttons = new JButton[4];
String[] buttonText = {"Add", "Subtract", "Multiply", "Divide"};
String[] labelText = {"Number 1", "Number 2", "Result"};
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
public Exercise_16_4() {
for (int i = 0; i < labels.length; i++) {
labels[i] = new JLabel(labelText[i]);
textFields[i] = new JTextField();
p1.add(labels[i]);
p1.add(textFields[i]);
}
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton(buttonText[i]);
p2.add(buttons[i]);
}
add(p1);
add(p2);
}
public static void main(String[] args) {
Exercise_16_4 frame = new Exercise_16_4();
frame.setTitle("Exercise 16.4");
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}//main
}//class
The default layout manager for the content pane of a JFrame is a BorderLayout.
By default when you add a component to the frame is will be added to the CENTER of the BorderLayout. The problem is only one component can be added so only the last one added is displayed.
You can try something like:
add(p1, BorderLayout.NORTH);
Or you can create a JPanel add the p1, p2 components to the panel and then add the panel to the frame.
Read the section from the Swing tutorial on Layout Managers for more information and examples of using layout managers as well as examples that show you how to create the GUI on the Event Dispatch Thread.

GridBagLayout within JScrollPane not resizing properly

I have a JPanel with a GridBagLayout inside of a JScrollPane. I also have an 'add' button within the JPanel which, when clicked, will be removed from the JPanel, adds a new instance of a separate component to the JPanel, then adds itself back to the JPanel. This sort of makes a growing list of components, followed by the 'add' button.
Adding new components works fine, the JPanel stretches to accommodate the new components, and the JScrollPane behaves as expected, allowing you to scroll through the entire length of the JPanel.
This is how the add works:
jPanel.remove(addButton);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
jPanel.add(new MyComponent(), c);
jPanel.add(addButton, c);
jPanel.validate();
jPanel.repaint();`
Removal works by clicking a button inside the added components themselves. They remove themselves from the JPanel just fine. However, the JPanel keeps it's stretched-out size, re-centering the list of components.
This is how removal works:
Container parent = myComponent.getParent();
parent.remove(myComponent);
parent.validate();
parent.repaint();`
The question is, why does my GridBagLayout JPanel resize when adding components, but not when removing components?
You have to revalidate and repaint the JScrollPane, here is an example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingTest {
public static void main(String[] args) {
final JPanel panel = new JPanel(new GridBagLayout());
for (int i = 0; i < 25; i++) {
JTextField field = new JTextField("Field " + i, 20);
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridy = i;
panel.add(field, constraints);
}
final JScrollPane scrollPane = new JScrollPane(panel);
JButton removeButton = new JButton("Remove Field");
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (panel.getComponentCount() >= 1) {
panel.remove(panel.getComponentCount() - 1);
scrollPane.revalidate();
scrollPane.repaint();
}
}
});
JFrame frame = new JFrame("Swing Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(640, 480);
frame.setLocation(200, 200);
frame.getContentPane().add(scrollPane);
frame.getContentPane().add(removeButton, BorderLayout.SOUTH);
frame.setVisible(true);
}
}

Update Grid in GridLayout

I have an array of objects laid out through a GridLayout in a JPanel. I need to be able to recreate the object in an index in the array and have the GridLayout update to reflect this. As of yet, I cannot find anyway to "refresh" or redraw the GridLayout. Is it possible to refresh a GridLayout without creating the entire GridLayout or JPanel? Assume I do not have access to JFrame.
import javax.swing.*;
import java.awt.*;
public class Test
{
public static void main(String args[])
{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5,5));
JLabel[][] labels = new JLabel[5][5];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
labels[j][i] = new JLabel("("+j+", "+i+")");
panel.add(labels[j][i]);
}
}
labels[0][0] = new JLabel("Hello World");
//Without doing it this way (cause my objects can't do this)
//labels[0][0].setText("Hello World!");
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
}
I don't understand why you can't just update the text on the label.
Why do you need to "recreate the object"? It makes no sense. But if you really need to do this then the code would be something like:
panel.remove(0);
panel.add(theNewLabel, 0);
panel.revalidate();
panel.repaint();

grid layout panels in a jframe

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);

Categories

Resources