Java Swing 13 GridLayout does not exist? - java

I can't seem to get a swing GridLayout to work in java 13. The error is that GridLayout cannot be resolved to a type in the following code:
import javax.swing.*;
public class GameFrame extends JFrame {
public static final void NewFrame() {
new GameFrame();
}
public GameFrame() {
this.setSize(1600, 800);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("The Game");
this.setVisible(true);
this.setResizable(false);
JPanel MainPanel = new JPanel();
MainPanel.setLayout(new GridLayout());
}
}

The issue is caused by the class not being imported.
import java.awt.GridLayout;
Since it is not in the swing package it doesn't get imported with the star import.
Also it is better to use explicit imports.

This might be related to the fact that panel is empty. Try running this code and it should work.
public class GridLayoutTest {
private static JButton[] arrayBtn;
public static void main(String[] args) {
// the frame that contains the components
JFrame frame = new JFrame("GridLayoutTest from JCG");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set the size of the frame
frame.setSize(350, 350);
// set the rows and cols of the grid, as well the distances between them
GridLayout grid = new GridLayout(5, 3, 10, 10);
// what layout we want to use for our frame
frame.setLayout(grid);
// add a text field with a specified text to the frame
JTextArea text = new JTextArea();
text.setText("Result");
text.setEditable(false);
frame.add(text);
// add buttons to the frame
frame.add(new JButton("+"));
frame.add(new JButton("="));
arrayBtn = new JButton[10];
// add JButtons dynamically
for(int i=0; i < arrayBtn.length; i++) {
arrayBtn[i] = new JButton(Integer.toString(i));
frame.add(arrayBtn[i]);
}
frame.setVisible(true);
}
}

Related

How can I properly adjust the size and location of a button in JFrame?

I am attempting to make a PC Application using Java and JFrame. I'm trying to format 2 transparent buttons, each sized half of the full screen shown (vertically). The top half of the screen will hold to option to debate someone and the bottom half of the screen will hold the option to spectate a debate if clicked on. Here is what I have so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame {
JButton b1;
JButton b2;
JPanel j1;
JPanel j2;
public BackgroundImageJFrame() {
setTitle("Background Color for JFrame");
setSize(340,563);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setLayout(null);
/*
One way
-----------------
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png"));
add(background);
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
background.add(l1);
background.add(b1);
*/
// Another way
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Users\\MLH-User\\Downloads\\Front.jpg")));
setLayout(new FlowLayout());
j1 = new JPanel();
j1.setLayout(null);
b1 = new JButton("Spectate");
//b1.setBounds(0,0,50,50);
b1.setOpaque(false);
b1.setContentAreaFilled(false);
b1.setBorderPainted(false);
j1.add(b1);
b2 = new JButton("Debate");
b2.setLocation(0,0);
b2.setOpaque(false);
b2.setContentAreaFilled(false);
b2.setBorderPainted(false);
j1.add(b2);
add(j1);
// Just for refresh :) Not optional!
setSize(339,562);
setSize(340,563);
}
public static void main(String args[]) {
new BackgroundImageJFrame();
}
}
This is some stuff I experimented with so far, can anyone help me out about where I went wrong?
You should use a layout manager. Here is an example with GridLayout:
public class Example extends JFrame {
private static final int SIZE = 300;
public Example() {
setLayout(new GridLayout(2, 1, 0, 5));
getContentPane().setBackground(Color.WHITE);
JButton debate = new JButton("DEBATE") {
public Dimension getPreferredSize() {
return new Dimension(SIZE, SIZE);
}
};
Font font = debate.getFont().deriveFont(30f);
debate.setFont(font);
// debate.setBorderPainted(false);
debate.setBackground(Color.BLUE.brighter());
debate.setForeground(Color.WHITE);
JButton spectate = new JButton("SPECTATE") {
public Dimension getPreferredSize() {
return new Dimension(SIZE, SIZE);
}
};
spectate.setFont(font);
// spectate.setBorderPainted(false);
spectate.setBackground(Color.RED.brighter());
spectate.setForeground(Color.WHITE);
add(debate);
add(spectate);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(() -> new Example());
}
}
Notes:
You have to realize that screen sizes vary. Setting SIZE to 300 was an arbitrary choice for presentation, screens might not have the required size. You can also set the insets or an empty border instead of specifying the size of the component directly.
You can consider creating a class for these buttons if you have more of them.
This is an example of setting the sizes. I don't know about the location part though.
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(4,4,4,4));
for(int i=0 ; i<16 ; i++){
JButton btn = new JButton(String.valueOf(i));
btn.setPreferredSize(new Dimension(40, 40));
panel.add(btn);
}
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);

JLabel doesn't show up

I'm working on a program but my JLabel doesn't show up. My JButton works perfectly (it appears) but for some reason the JLabel does not appear. I have checked on internet but I Haven't found anything.
package com.hinx.client;
import java.awt.Color;
import javax.swing.*;
public class Main {
public static void main(String [] args)
{
createWindow();
}
static void createWindow()
{
//Create panel
JPanel content = new JPanel();
content.setLayout(null);
//Build the frame
JFrame frame = new JFrame("Hinx - A marketplace for apps - Client ALPHA_0.0.1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700, 400);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.add(content);
frame.setVisible(true);
//Add the login button
JButton login = new JButton("Login");
login.setBounds(0, 342, 150, 30);
//Create login label
JLabel loginlabel = new JLabel("Login Area");
//Create login panel
JPanel loginpanel = new JPanel();
loginpanel.setLayout(null);
loginpanel.setBounds(0, 0, 150, 400);
loginpanel.setBackground(Color.gray);
loginpanel.add(login);
loginpanel.add(loginlabel);
content.add(loginpanel);
}
}
I have checked on internet but I Haven't found anything.
JFrame is visible before JComponents (frame.add(content);) are added / created
move code line frame.setVisible(true); (better everything about JFrame) to the end of constuctor
Set a layout for your panel. Per example :
loginpanel.setLayout(new BorderLayout());
You can learn more about layouts here.
Here's what I get :
Use layouts. FlowLayout should be fine in this case. Do not call setBounds() and do not set layout as a null.
Add label and button on JPanel
Then add JPanel on JFrame
Call pack() instead of setSize()
Call setVisible(true) in the end.
Good luck!
You are making setLayout null.
JPanel loginpanel = new JPanel();
loginpanel.setLayout(null);
Use this,
JPanel loginpanel = new JPanel();
loginpanel.setLayout(new BorderLayout());
Run the UI on the EDT instead of running on the main thread. Read this post.
Example:
public static void main(String [] args)
{
Runnable r = new Runnable() {
#Override
public void run() {
createWindow();
}
};
EventQueue.invokeLater(r);
}

How can I align elements in JPanels / JFrames?

I'm completely new to using the GUI in java, so I'm having a bit of trouble figuring out how to align everything that I need to. I have to panels in my JFrame that I need to align (One to the left, one to the right) and a few buttons in one of the panels that I need to be centered in the panel. Here is my code.
package application;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.nio.*;
import java.util.*;
public class Main extends JPanel
{
public static void main(String[] args)
{
//set the ui to the native OS
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e)
{
}
JFrame frame = new JFrame("Application Name");
Menu menu = new Menu();
JPanel iconPanel = new JPanel();
final JPanel grid = new JPanel(new FlowLayout());
JButton firewallButton = new JButton("Firewall");
JButton networkButton = new JButton("Network");
JButton printerButton = new JButton("Printer");
int iconPanelSizeX;
int iconPanelSizeY;
int gridSizeX;
int gridSizeY;
int gridPosition;
//frame setting
frame.setSize(800, 600);
frame.setMinimumSize(new Dimension(800, 600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
//add grid and iconPanel JPanels to the frame
frame.add(iconPanel);
iconPanel.add(firewallButton);
iconPanel.add(networkButton);
iconPanel.add(printerButton);
frame.add(grid);
//iconPanel settings
iconPanel.setBorder(BorderFactory.createLoweredSoftBevelBorder());
iconPanel.setBackground(Color.gray);
iconPanel.setLayout(new FlowLayout());
iconPanel.setSize(new Dimension(100, 600));
iconPanel.setVisible(true);
//grid setting
grid.setBackground(Color.red);
grid.setSize(new Dimension(700, 600));
grid.setVisible(true);
//this is for resizing components when the user resizes the window
int counter = 0;
while(counter == 0)
{
firewallButton.setSize(new Dimension(iconPanel.getWidth(), 50));
networkButton.setSize(new Dimension(iconPanel.getWidth(), 50));
printerButton.setSize(new Dimension(iconPanel.getWidth(), 50));
iconPanelSizeX = frame.getWidth() / 10;
iconPanelSizeY = frame.getHeight();
gridSizeX = (frame.getWidth() / 10) * 9;
gridSizeY = frame.getHeight();
iconPanel.setSize(new Dimension(iconPanelSizeX, iconPanelSizeY));
grid.setSize(new Dimension(gridSizeX, gridSizeY));
}
}
}
As you can see, the second JPanel (grid) doesn't line up with the right side of the frame, and the buttons inside iconTray don't center either. I realize these are both probably simple layout fixes, but I have no clue where to start.
For simple splitting of JFrame you can use GridLayout with 1 row and 2 colums.
frame.setLayout(new GridLayout(1,2,3,3)); //3,3 are gaps
frame.add(grid);
frame.add(iconPanel);
For centering components in panels you can use FlowLayout which is by default set on JPanels:
Doing it manualy:
grid.setLayout(new FlowLayout()); //Centered components
grid.setLayout(new FlowLayout(FlowLayout.LEFT,3,3)); //Components aligned to left
grid.setLayout(new FlowLayout(FlowLayout.RIGHT,3,3)); //Components aligned to right
This is how it looks:
Also, few observations:
Never call setXXXSize() methods for your components;
Try to avoid calling setSize(); for JFrame, call pack(); instead;
Call setVisible(true); in the end of code;
All your huge code can be "stripped" to this:
import javax.swing.*;
import java.awt.*;
public class Main extends JPanel
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Application Name");
JPanel iconPanel = new JPanel();
JPanel grid = new JPanel(new FlowLayout());
JButton firewallButton = new JButton("Firewall");
JButton networkButton = new JButton("Network");
JButton printerButton = new JButton("Printer");
frame.add(iconPanel);
iconPanel.add(firewallButton);
iconPanel.add(networkButton);
iconPanel.add(printerButton);
grid.setBackground(Color.GREEN);
frame.setLayout(new GridLayout(1,2,3,3));
frame.add(grid);
frame.add(iconPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
how to align buttons vertically?
This example uses a vertical Box in the WEST area of the frame's default BorderLayout:
import java.awt.*;
import javax.swing.*;
/** #see http://stackoverflow.com/a/14927280/230513 */
public class Main {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
display();
}
});
}
private static void display() throws HeadlessException {
JFrame frame = new JFrame("Application Name");
JButton firewallButton = new JButton("Firewall");
JButton networkButton = new JButton("Network");
JButton printerButton = new JButton("Printer");
//iconPanel settings
Box iconPanel = new Box(BoxLayout.Y_AXIS);
iconPanel.add(firewallButton);
iconPanel.add(networkButton);
iconPanel.add(printerButton);
iconPanel.setBackground(Color.gray);
iconPanel.setVisible(true);
frame.add(iconPanel, BorderLayout.WEST);
//grid setting
JPanel grid = new JPanel() {
#Override
// arbitrary placeholder size
public Dimension getPreferredSize() {
return new Dimension(320, 230);
}
};
grid.setBackground(Color.red);
frame.add(grid, BorderLayout.CENTER);
//frame setting
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
I suggest you take some time going through A Visual Guide to Layout Managers. This will help you become familiar with the layout managers which are available with the Standard API. It takes some experience and hard work to figure out which of these is the right tool to get the exact look you want. Once you become comfortable with what is available from the Standard API, you should also look around for third-party Layout Manager APIs which provide other options.
I have to panels in my JFrame that I need to align (One to the left,
one to the right) and a few buttons in one of the panels that I need
to be centered in the panel. Here is my code.
I realize these are both probably simple layout fixes, but I have no
clue where to start.
Use more complex layout than simple FlowLayout which you actually using. I suggest to you use
GridBagLayout
BoxLayout
Check references here

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.

JScrollPane won't work

Hey guys I wanted to create a JScrollPane but it won't work... and I don't know why... here's my code...
public class test extends JFrame{
public test(){
setSize(1000,600);
}
private static JButton[] remove;
private static JPanel p = new JPanel();
public static void main(String[]args){
p.setLayout(null);
JFrame t=new test();
remove = new JButton[25];
for(int i=0;i<25;i++){
remove[i]=new JButton("Remove");
remove[i].setBounds(243,92+35*i,85,25);
p.add(remove[i]);
}
JScrollPane scrollPane = new JScrollPane(p);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
t.add(scrollPane);
t.setVisible(true);
}
Umm and Im pretty sure the frame isn't big enough for these 25 buttons... But if i delete that p.setLayout(null); A horizontal scroll bar will be created automatically... I don't really know what is wrong with my code... Pls help thank you very much!
You need to set p's preferredSize for this to work.
p.setPreferredSize(new Dimension(800, 2000));
Or you could have p extend JPanel and then override the getPreferredSize() method to return the proper dimension.
And I agree -- get rid of your null layouts. Learn about and use the layout managers if you want to use Swing correctly and have robust Swing GUI's.
e.g.,
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Foo extends JFrame {
private static final int BUTTON_COUNT = 25;
public static void main(String[] args) {
JPanel btnPanel = new JPanel(new GridLayout(0, 1, 0, 20));
btnPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
AbstractAction removeAction = new AbstractAction("Remove") {
#Override
public void actionPerformed(ActionEvent evt) {
JButton src = (JButton) evt.getSource();
JPanel container = (JPanel) src.getParent();
container.remove(src);
container.revalidate();
container.repaint();
}
};
for (int i = 0; i < BUTTON_COUNT; i++) {
JButton removeBtn = new JButton(removeAction);
btnPanel.add(removeBtn);
}
JPanel borderPanel = new JPanel(new BorderLayout());
borderPanel.add(btnPanel, BorderLayout.NORTH);
JScrollPane scrollpane = new JScrollPane(borderPanel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollpane.setPreferredSize(new Dimension(400, 800));
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(scrollpane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
The issue is that a scroll pane checks the component inside it for a "preferred size" so a pane with a null layout has a preferred size of (0,0). Which it ignores.
You should do something along the lines of:
p.setPreferredSize(1000,600);
And you should see some scroll bars appear, I'm not sure how accurate they will be though.

Categories