JButton in JPanel - java

I don't know why my grids cover my button I try to solve it out but I can't. Can anyone tell me why? Is it because, I put all together in BorderLayout? Any one can more the Play Button to the Right hand side of it ?
public game() {
make();
JPanel p = new JPanel();
frame.setLayout(new BorderLayout());
resetButton = new JButton("Play");
p.add(playButton, BorderLayout.EAST);
frame.add(p);
}
public void make(){
frame = new JFrame("Gamer");
frame.setTitle("Gamer");
JPanel m = new JPanel(new GridLayout(9,9));
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
grids[i][j] = new JButton();
m.add(grids[i][j]);
}
}
frame.add(m, BorderLayout.CENTER);
frame.setResizable(false);
frame.setSize(width, heigth);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

Essentially, you are adding both the m (grid) and button panel to the CENTER position of the BorderLayout
Here
frame.add(m, BorderLayout.CENTER);
and
p.add(playButton, BorderLayout.EAST);
frame.add(p); // adding to the CENTER position
The default position within the BorderLayout is the CENTER position. By simply using frame.add(p, BorderLayout.EAST);, you can can move the button to the right...
Beware, there are issues with using setResizable where it will change the border size of the frame, changing the available space for your frames content, always call this before defining the size of the frame, which should be done with pack
You really want to avoid modifying the content of the frame after it's been made visible if you can, as this not only affects the space the content might like, but also needs you to revalidate and repaint the container.
Better, create the frame, then pass it to the game and make methods instead...

Try to use frame.add(p,BorderLayout.SOUTH)
Here is an example.
The code:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class game {
JFrame frame;
JButton grids[][] = new JButton[9][9];
public game() {
make();
JPanel p = new JPanel();
JButton resetButton = new JButton("reset");
JButton playButton = new JButton("Play");
p.add(playButton);
p.add(resetButton);
frame.add(p,BorderLayout.SOUTH);
frame.setVisible(true);
}
public void make() {
frame = new JFrame("Gamer");
frame.setTitle("Gamer");
JPanel m = new JPanel(new GridLayout(9, 9));
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
grids[i][j] = new JButton();
m.add(grids[i][j]);
}
}
frame.add(m, BorderLayout.CENTER);
frame.setResizable(false);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
game gameObj = new game();
}
}
The effect:
Besides that,the first letter of the class name should be Capitalized.

Well, It is a matter of size. Literally, your grid and/or button are too big to fit where you want them to, so they leak into the next space. (i.e. BorderLayout.EAST will leak into BorderLayout.CENTER).
Try making your JFrame larger, and also try setting the preferred size of your JPanels to further assure a well built window.

You are using frame.add(p) - which may not add the panel to the correct area of the frame.
Try
frame.add(p, BorderLayout.SOUTH)
or whatever? i.e. not CENTER which would overwrite your grid.
Also note that the layout of the panel hasn't been set, so it will be a FlowLayout by default.
As MadProgrammer said, no need to set the layout of the frame - especially AFTER adding the grids!
Finally, it is good practice to only add to the getContentPane() of a frame.

Do you want this?
![enter image description here][1]import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class WelcomActivity {
JFrame frame;
JButton resetButton;
JButton playButton;
JButton[][] grids = new JButton[9][9];
int width = 600;
int heigth = 400;
public void game() {
make();
JPanel p = new JPanel();
playButton = new JButton("Play");
resetButton = new JButton("Reset");
p.add(playButton);
p.add(resetButton);
frame.getContentPane().add(p, BorderLayout.EAST);
}
public void make() {
frame = new JFrame("Gamer");
frame.setTitle("Gamer");
JPanel m = new JPanel(new GridLayout(9, 9));
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
grids[i][j] = new JButton();
m.add(grids[i][j]);
}
}
frame.setResizable(false);
frame.setSize(width, heigth);
frame.getContentPane().setLayout(new BorderLayout() );
frame.getContentPane().add(m, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args){
new WelcomActivity().game();
}
}

Related

JFrame large grid map

I'm trying to make a large grid map of 160x120 JButtons with JFrame but it's too much to fit on the window.
How can I overcome this?
public class DisplayTable extends JFrame {
public static void main() {
JFrame frame = new JFrame("puzzle layout");
//frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(3200, 800);
JPanel panel = new JPanel();
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
panel.setBorder(new EmptyBorder(0,0,0,0));
panel.setLayout(new GridLayout(12,16));
for(int i=0; i<120; i++) {
for(int j=0; j<160; j++) {
JButton temp = new JButton("1");
panel.add(temp);
}
}
frame.add(panel);
frame.setVisible(true);
}
}
Use a JScrollPane to wrap the panel ... also, you should use pack instead of setSize, but only after you've added all your components to the screen
See How to use scroll panes for more details

How to set flow layout?

hi i am trying to make java desktop application where i am trying to make jbutton bottom left i did following code i dont know where i am wrong my code is note working
here is my code
import java.awt.*;
import java.awt.event.*;
import javax.imageio.ImageIO;
import javax.swing.*;
new complete code
public class ApplicationCloseExample
{
private JButton[] buttons;
private void displayGUI()
{
final JFrame frame = new JFrame("Application Close Example");
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
for (int i = 5; i < 8; i++) {
buttons[i] = new JButton(Integer.toString(i));
bottomPanel.add(buttons[i]);
}
// JButton button = new JButton("Comment");
// bottomPanel.add(button);
// frame.getContentPane().add(contentPane, BorderLayout.CENTER);
frame.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ApplicationCloseExample().displayGUI();
}
});
}
}
How can i achieve this
I'm going to assume the null pointer exception is something to do with your buttons array. Check that you have initialised it properly.
private JButton[] buttons = new JButton[8];
I copied your code into a test project and ran it after some modifications:
public static void main(String[] args) {
final JFrame frame = new JFrame("Application Close Example");
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
for (int i = 5; i < 8; i++) {
buttons[i] = new JButton(Integer.toString(i));
bottomPanel.add(buttons[i]);
}
frame.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
This produced a frame with three buttons aligned to the bottom left of the window.
There is an elegant solution that I'll give you but maybe it serves. Use WindowsBuilder and adds several buttons and then you look like is placing code. So make yourself an idea of the pattern that follows a setLayout with Flow.

Keep BoxLayout From Expanding Children

I want to stack some JComponents vertically inside a JPanel so they stack at the top and any extra space is at the bottom. I'm using a BoxLayout. The components will each contain a JTextArea that should allow the text to wrap if necessary. So, basically, I want the height of each of these components to be the minimum necessary for displaying the (possibly wrapped) text.
Here's a contained code example of what I'm doing:
import javax.swing.*;
import java.awt.*;
public class TextAreaTester {
public static void main(String[] args){
new TextAreaTester();
}
public TextAreaTester(){
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel,BoxLayout.PAGE_AXIS));
panel.setPreferredSize(new Dimension(100,400));
for(int i = 0; i<3; i++){
JPanel item = new JPanel(new BorderLayout());
JTextArea textarea = new JTextArea("this is a line of text I want to wrap if necessary");
textarea.setWrapStyleWord(true);
textarea.setLineWrap(true);
textarea.setMaximumSize( textarea.getPreferredSize() );
item.add(textarea,BorderLayout.NORTH);
panel.add(item);
}
panel.add(Box.createGlue());
frame.add(panel);
frame.setVisible(true);
frame.pack();
}
}
The child JPanels are expanding to fill the vertical space. I tried using glue because I thought that's what glue was for, but it seems to do nothing at all. Any help?
Note: I have found questions that look almost identical, but none with answers I can apply.
One solution: nest JPanels with the outer JPanel using Borderlayout and adding the BoxLayout using JPanel to this one BorderLayout.NORTH, also known as BorderLayout.PAGE_START:
Edit for Kleopatra:
import javax.swing.*;
import java.awt.*;
public class TextAreaTester {
public static void main(String[] args) {
new TextAreaTester();
}
public TextAreaTester() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
// panel.setPreferredSize(new Dimension(100,400));
for (int i = 0; i < 3; i++) {
JPanel item = new JPanel(new BorderLayout());
// item.setLayout(new BoxLayout(item,BoxLayout.LINE_AXIS));
JTextArea textarea = new JTextArea(
"this is a line of text I want to wrap if necessary", 3, 35);
textarea.setWrapStyleWord(true);
textarea.setLineWrap(true);
// textarea.setMaximumSize(textarea.getPreferredSize());
// item.setMaximumSize( item.getPreferredSize() );
item.add(new JScrollPane(textarea), BorderLayout.NORTH);
panel.add(item);
}
panel.add(Box.createGlue());
JPanel mainPanel = new JPanel(new BorderLayout()) {
private final int prefW = 100;
private final int prefH = 400;
#Override
public Dimension getPreferredSize() {
return new Dimension(prefW, prefH);
}
};
// mainPanel.setPreferredSize(new Dimension(100, 400));
mainPanel.add(panel, BorderLayout.PAGE_START);
frame.add(mainPanel);
frame.setVisible(true);
// frame.getContentPane().add(jp);
frame.pack();
}
}
Alternatively, you can use Box.Filler. Just replace your call to panel.add(Box.createGlue()) with
panel.add(new Box.Filler(new Dimension(0, 0),
new Dimension(0, Short.MAX_VALUE),
new Dimension(0, Short.MAX_VALUE)));
If you want to achieve the same for a horizontal layout, just use Short.MAX_VALUE for width instead of height in the Dimension call.

Adding JPanels to JPanel array

I have declared an array:
private javax.swing.JPanel[] panelArray = new javax.swing.JPanel[3];
I also have 3 panels: panel0, panel1 and panel2. Can I add these panels to the array? i.e
panelArray[0] = panel0;
panelArray[1] = panel1;
panelArray[2] = panel2;
And then manipulate the arrays like this?
boolean[] myBools; .... then set them as true/false
for(int i=0; i<3; i++)
{
if(myBools[i])
panelArray[i].setVisible(true)
}
Because that does not work for me
On my side it's working fine, in this program :
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class MyPanel
{
private JPanel[] panelArray = new JPanel[3];
private boolean[] myBools = new boolean[]{false, false, false};
private int counter = 0;
private int prvPanelCounter = 0;
private Timer timer;
private ActionListener timerAction = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
counter++;
if (counter > 2)
counter = 0;
myBools[counter] = true;
for (int i = 0; i < 3; i++)
{
if (myBools[i])
{
panelArray[i].setVisible(myBools[i]);
panelArray[prvPanelCounter].setVisible(myBools[prvPanelCounter]);
myBools[i] = false;
prvPanelCounter = i;
break;
}
}
}
};
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("Locate Mouse Position");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel0 = new JPanel();
panel0.setOpaque(true);
panel0.setBackground(Color.BLUE);
JPanel panel1 = new JPanel();
panel1.setOpaque(true);
panel1.setBackground(Color.RED);
JPanel panel2 = new JPanel();
panel2.setOpaque(true);
panel2.setBackground(Color.DARK_GRAY);
panelArray[0] = panel0;
panelArray[1] = panel1;
panelArray[2] = panel2;
JComponent contentPane = (JComponent) frame.getContentPane();
contentPane.setLayout(new GridLayout(0, 1));
frame.add(panel0);
frame.add(panel1);
frame.add(panel2);
panel0.setVisible(myBools[counter]);
panel1.setVisible(myBools[counter]);
panel2.setVisible(myBools[counter]);
frame.setSize(300, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
timer = new Timer(1000, timerAction);
timer.start();
}
public static void main(String\u005B\u005D args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new MyPanel().createAndDisplayGUI();
}
});
}
}
What you want to do can be done, but here's a few points to bear in mind:
Make sure you initialise the JPanels before referencing them.
The statement "panelArray[i].setVisible(true)" needs a semicolon after it.
None of these panels will be visible unless you add them to another component, such as a JFrame.
Rather than state javax.swing.JPanel, you could just import the JPanel at the top of the page and refer to it as simply JPanel.
Your "if" statement is unnecessary. Just do .setVisible(myBools[i]);
Hope these were of some help to you.
Yes, you can. Did you really not initialize the myBools array with new ?

Empty JPanel not positioning correctly in relation to other JPanels

I am using swing to build a GUI with 4 JPanels inside a JPanel using the BorderLayout manager:
A row of labels
A column of JButtons
A display area (it is a class that extends JPanel and has nothing added to it and is used as a drawing area)
Another column of buttons
My code looks like this:
JPanel middle = new JPanel();
middle.setLayout(new BorderLayout());
middle.add(midLabels,BorderLayout.NORTH);
middle.add(pickupButtons,BorderLayout.WEST);
middle.add(simulation,BorderLayout.CENTER);
middle.add(dropButtons,BorderLayout.EAST);
The simulation panel is just an extended JPanel that overrides paintComponent to draw an image. The problem is, the simulation area is on the left and not in the middle:
What I actually want is:
Edit, here is an example, do I need to use a different layout manager to get the empty JPanel positioned correctly?:
import java.awt.*;
import javax.swing.*;
public class Test extends JFrame {
final static int MAXFLOORS = 8;
public Test() {
setLayout(new BorderLayout());
setTitle("Simulator");
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 500);
JPanel simulation = new JPanel();
JPanel dropButtons = new JPanel();
JPanel pickupButtons = new JPanel();
pickupButtons.setLayout(new GridLayout(MAXFLOORS, 1));
dropButtons.setLayout(new GridLayout(MAXFLOORS, 1));
setLayout(new BorderLayout());
add(simulation,BorderLayout.CENTER);
add(dropButtons,BorderLayout.EAST);
add(pickupButtons,BorderLayout.WEST);
for (int i = MAXFLOORS; i != 0; i--) {
JButton pb = new JButton("F" + i);
dropButtons.add(pb);
JButton db = new JButton("F" + i);
dropButtons.add(db);
}
repaint();
}
public static void main(String[] args) {
new Test();
}
}
Look at your code:
for (int i = MAXFLOORS; i != 0; i--) {
final JButton pb = new JButton("F" + i);
dropButtons.add(pb);
final JButton db = new JButton("F" + i);
dropButtons.add(db);
}
You're adding onto dropButtons twice, instead of pickupButtons.

Categories