I am trying to learn Java Swing from a very old tutorial. As I was following the course I got stuck in a project where I was learning about GridBagLayout. When I called the function setLayout(new GridBagLayout());, Eclipse shows me 'GridBagLayout cannot be resolved to a type'. Even though I have imported java. awt. GridBagLayout.
Here's my code.
package com.swing11;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
public class FormPanel extends JPanel {
private JLabel nameLabel;
private JLabel occupationLabel;
private JTextField nameField;
private JTextField occupationField;
private JButton okButton;
public FormPanel() {
nameLabel = new JLabel("Name: ");
occupationLabel = new JLabel("Occupation: ");
nameField = new JTextField(10);
occupationField = new JTextField(25);
okButton = new JButton("Ok");
Dimension dim = getPreferredSize();
dim.width = 250;
setPreferredSize(dim);
Border innerBorder = BorderFactory.createTitledBorder("Add Person");
Border outterBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
setBorder(BorderFactory.createCompoundBorder(outterBorder, innerBorder));
setLayout(new GridBagLayout());
}
}
Related
this is my code
This code gives me a frame with text displayed inside it.
I may need to modify the text as necessary, and then there are two buttons. One pushes the code further, the other one closes the application.
What I want to do is add listener to okButt, within the createOverviewButtonsPanel method, that would retrieve the value of txtMenuOverview in order to pass it further is this even possible?
MenuOverviewFrame class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class MenuOverviewFrame extends JFrame{
private static final long serialVersionUID = -5908534022988507381L;
private static final Font FONT = new Font("Courier", Font.BOLD, 16);
private static final Font MENU_FONT = new Font(Font.MONOSPACED,Font.BOLD,14);
private static final Color BLUE_STEEL = new Color(70, 107, 176);
private static final Dimension INITIAL_SIZE = new Dimension(500, 300);
private static final Dimension MINIMUM_SIZE = new Dimension(275, 150);
public static void main(String[] args) {
System.setProperty("sun.java2d.cmm", "sun.java2d.cmm.kcms.KcmsServiceProvider");
SwingUtilities.invokeLater(() -> {
MenuOverviewFrame frame = new MenuOverviewFrame("Test test\ntest\ntest");
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
public MenuOverviewFrame(String menuOutput) {
super("Daily Menu");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
getContentPane().setBackground(Color.WHITE);
setSize(INITIAL_SIZE); // The initial frame size
setMinimumSize(MINIMUM_SIZE);
JTextArea txtMenuOverview = new JTextArea(menuOutput);
txtMenuOverview.setFont(MENU_FONT);
JScrollPane taScroll = new JScrollPane(txtMenuOverview);
add(taScroll);
JPanel overviewButtonsPanel = createOverviewButtonsPanel();
overviewButtonsPanel.setPreferredSize(new Dimension(overviewButtonsPanel.getPreferredSize().width, overviewButtonsPanel.getPreferredSize().height + 30));
getContentPane().add(overviewButtonsPanel, BorderLayout.SOUTH); // at the center
}
private JPanel createOverviewButtonsPanel() {
JPanel panel = new JPanel();
//panel.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 1));
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(0,0,0,20);
panel.setBackground(BLUE_STEEL);
JButton okButt = new JButton("Send menu");
JButton koButt = new JButton("Abort mission");
panel.add(okButt,gbc);
panel.add(koButt);
okButt.setVerticalAlignment(SwingConstants.CENTER);
return panel;
}
}
Thank you
I have to design a swing game where one side is a grid and the other side is somewhat of a display panel where I have several JLabels and a JButton. But no matter if I use setSize(); or setPrefferedSize (); or setBounds(); or even setPrefferedSize(new Dimension()); it will not become smaller but instead stretches the entirety of that section. Any JLabel/JButton aligned in the center takes up the entire center. How do I fix this?
This is the code to my class referencing to another class in the project containing the grid:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class Scoreboard extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
JLabel scoreLabel;
JLabel coord;
JLabel title;
JButton quit;
public Scoreboard (int score){
setLayout(new BorderLayout());
setSize(490,400);
setPreferredSize(getSize());
setBackground(Color.BLUE);
title = new JLabel();
title.setIcon(new ImageIcon("C:\\Users\\Rachel\\Workspace\\Assignment2\\Planet1.png"));
title.setSize(200,200);
title.setHorizontalAlignment(SwingConstants.CENTER);
add (title,BorderLayout.NORTH);
scoreLabel = new JLabel("Score: "+Integer.toString(score));
scoreLabel.setSize(200,200);
scoreLabel.setBackground(Color.BLUE);
scoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
scoreLabel.setFont(new Font("Source Sans Pro", Font.BOLD, 40));
scoreLabel.setForeground(Color.WHITE);
add(scoreLabel, BorderLayout.CENTER);
coord = new JLabel ("Click the aliens!");
coord.setSize(200,400);
coord.setBackground(Color.RED);
coord.setHorizontalAlignment(SwingConstants.CENTER);
coord.setFont(new Font("Source Sans Pro", Font.BOLD, 20));
coord.setForeground(Color.WHITE);
add(coord,BorderLayout.SOUTH);
JButton quit = new JButton ("Quit Game");
quit.setBounds(20,30,50,30);
quit.setHorizontalAlignment(SwingConstants.CENTER);
add(quit, BorderLayout.CENTER);
}
}
The following code does not solve the problem. Instead it shows some tips related to your question, as well as some others.
In general try to avoid "manually control" components layout, but use the right layout managers.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
public class Scoreboard extends JPanel{
JLabel scoreLabel;
JLabel coord;
JLabel title;
JButton quit;
private final int W = 490;
private final int H = 400;
public Scoreboard (int score){
setLayout(new BorderLayout());
setPreferredSize(new Dimension(W, H));
setBackground(Color.BLUE);
title = new JLabel("My Title");
//if you use images in your SO posted code use web links
//title.setIcon(new ImageIcon("C:\\Users\\Rachel\\Workspace\\Assignment2\\Planet1.png"));
//title.setSize(200,200); run the code without it and see it has no effect
title.setHorizontalAlignment(SwingConstants.CENTER);
add (title,BorderLayout.NORTH);
scoreLabel = new JLabel("Score: "+Integer.toString(score));
scoreLabel.setSize(200,200);
scoreLabel.setBackground(Color.BLUE);
scoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
scoreLabel.setFont(new Font("Source Sans Pro", Font.BOLD, 40));
scoreLabel.setForeground(Color.WHITE);
//this is directly related to your question. You can't add 2 components
//to the center.
//instead add a JPanel to the center, apply a layout manager to it,
//and add scorelabel and quit button to that JPanel
add(scoreLabel, BorderLayout.CENTER);
coord = new JLabel ("Click the aliens!");
//coord.setSize(200,400); run the code without it and see it has no effect
coord.setBackground(Color.RED);
coord.setOpaque(true); //if you want the color show
coord.setHorizontalAlignment(SwingConstants.CENTER);
coord.setFont(new Font("Source Sans Pro", Font.BOLD, 20));
coord.setForeground(Color.WHITE);
add(coord,BorderLayout.SOUTH);
JButton quit = new JButton ("Quit Game");
//no need to set bounds. That is what the layout manager does
//quit.setBounds(20,30,50,30);
quit.setHorizontalAlignment(SwingConstants.CENTER);
add(quit, BorderLayout.CENTER);
}
//add main to your questions to make it runnable
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
JPanel panel = new Scoreboard(50);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
I'm new to Swing and I'm trying to create an inlog screen with some textfield and buttons. When I run it, I get an empty screen, but once I resize the window, it starts working ... Does anyone know why?
code:
package ui_view;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextField;
public class InlogView extends JFrame{
GridBagConstraints constraints;
JPanel p = new JPanel();
JPanel bp = new JPanel();
JPanel img = new JPanel();
JButton inlogButton;
JButton cancelButton;
JLabel gebruikersNaam;
JTextField gebruikersInvoer;
JLabel wachtwoord;
JTextField wachtwoordInvoer;
BufferedImage image;
JLabel picLabel;
public InlogView(){
super("inlog");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(370,300);
add(img, BorderLayout.PAGE_START);
add(p, BorderLayout.CENTER);
add(bp, BorderLayout.PAGE_END);
setVisible(true);
setResizable(true);
}
public void maakInlogView() throws IOException{
p.setLayout(new GridBagLayout());
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
gebruikersNaam = new JLabel("gebruikersnaam: ");
changeConstraints(1,1,0,0);
p.add(gebruikersNaam, getConstraints());
gebruikersInvoer = new JTextField(10);
changeConstraints(1,1,1,0);
p.add(gebruikersInvoer, getConstraints());
wachtwoord = new JLabel("wachtwoord: ");
changeConstraints(1,1,0,1);
p.add(wachtwoord, getConstraints());
wachtwoordInvoer = new JTextField(10);
changeConstraints(1,1,1,1);
p.add(wachtwoordInvoer, getConstraints());
inlogButton = new JButton("Aanmelden");
cancelButton = new JButton("Cancel");
bp.add(inlogButton);
bp.add(cancelButton);
image = ImageIO.read(new File("doc/14_1.png"));
picLabel = new JLabel(new ImageIcon(image));
img.add(picLabel);
}
protected void changeConstraints(int height, int width, int gridx, int gridy) {
constraints.gridheight = height;
constraints.gridwidth = width;
constraints.gridx = gridx;
constraints.gridy = gridy;
}
protected GridBagConstraints getConstraints() {
return constraints;
}
public static void main(String args[]) throws IOException{
InlogView inlog = new InlogView();
inlog.maakInlogView();
}
}
Call setVisible(true) in maakInlogView() and not in the constructor.
you have to call validate() on the JFrame or JPanel
in your case just add validate() after setResizable(true)
I tried creating simple GUI using JFrame with below code.
package sorting_array_gui;
package sorting_array_gui;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
public class userwindow extends JFrame {
private static final long serialVersionUID = 1L;
public userwindow() {
super("A Programm to Sort Your Array");
setSize(1000,600);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
JPanel p1= new JPanel();
JButton b1= new JButton("Click Here");
p1.add(b1);
JTextField t1= new JTextField();
p1.add(t1);
JLabel l1= new JLabel("This is a Lable");
p1.add(l1);
add(p1,BorderLayout.CENTER);
}
}
When I added JTextfield , JPlane misbehaved and even JButton and JLabel stoped showing.
Why is that happening.
"When I added JTextfield , JPlane misbehaved and even JButton and JLabel stoped showing."
I don't get this behavior with your code. But you should note the below.
setVisible(true); should be that last thing you do after adding all components.
public userwindow() {
super("A Programm to Sort Your Array");
JPanel p1= new JPanel();
JButton b1= new JButton("Click Here");
p1.add(b1);
JTextField t1= new JTextField();
p1.add(t1);
JLabel l1= new JLabel("This is a Lable");
p1.add(l1);
add(p1,BorderLayout.CENTER);
pack(); <--- PACK frame
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true); <--- LAST
}
Also, you should set a size to your text field using the constructor that sets the column size
JTextField t1 = new JTextField(20);
Also, you should use pack() instead of setSize(). If you just pack(), everything should be visible, as the preferred sizes of all the components are respected.
Also note, if you want to add any other components to the JFrame you need to specify a BorderLayout position for each component, with no positions being used more than once.
See Laying out Components Within a Container
I am developing a Java application and would like some help in positioning some Labels and TextFields.
Here is my code:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.FlowLayout;
public class AuctionClient
{
public AuctionClient()
{
JFrame GUIFrame = new JFrame();
JPanel GUIPanel = new JPanel();
JLabel LabelUserName = new JLabel("UserName:");
JTextField TextFieldUserName = new JTextField(" ");
JLabel LabelPassword = new JLabel("Password:");
JTextField TextFieldPassword = new JTextField(" ");
GUIFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUIFrame.setTitle("Auction Client");
GUIFrame.setSize(500,250);
GUIFrame.setLocationRelativeTo(null);
GUIPanel.add(LabelUserName);
GUIPanel.add(TextFieldUserName);
GUIPanel.add(LabelPassword);
GUIPanel.add(TextFieldPassword);
GUIFrame.add(GUIPanel, BorderLayout.NORTH);
GUIFrame.setVisible(true);
}
}
With the above code, the LabelPassword and TextFieldPassword is on the same line as the LabelUsername and TextFieldUsername. Can I please have some help to position the LabelPassword and TextFieldPassword on a new line. Is it possible to specify X,Y coordinates to position objects on a JFrame?
Here is an image to show you how the objects are currently being shown:
http://canning.co.nz/Java/Positioning_Image.png
You should never try to position components with coordinates. Rather use appropriate LayoutManager's and use logical conditions and constraints to position your components.
Here is one example using GridBagLayout:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class AuctionClient {
public AuctionClient() {
JFrame guiFrame = new JFrame();
JPanel guiPanel = new JPanel(new GridBagLayout());
JLabel userNameLabel = new JLabel("UserName:");
JTextField userNameTextField = new JTextField(30);
JLabel passwordLabel = new JLabel("Password:");
JTextField passwordTextField = new JPasswordField(30);
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Auction Client");
guiFrame.setSize(500, 250);
guiFrame.setLocationRelativeTo(null);
GridBagConstraints labelGBC = new GridBagConstraints();
labelGBC.insets = new Insets(3, 3, 3, 3);
GridBagConstraints fieldGBC = new GridBagConstraints();
fieldGBC.insets = new Insets(3, 3, 3, 3);
fieldGBC.gridwidth = GridBagConstraints.REMAINDER;
guiPanel.add(userNameLabel, labelGBC);
guiPanel.add(userNameTextField, fieldGBC);
guiPanel.add(passwordLabel, labelGBC);
guiPanel.add(passwordTextField, fieldGBC);
guiFrame.add(guiPanel, BorderLayout.NORTH);
guiFrame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new AuctionClient();
}
});
}
}
GridLayout, SpringLayout, GridBagLayout can do that by default
easiest coud be GridLayout(2, 2, 10, 10),
but every JComponents are resizable with its container
have to change horizontal alingment for JLabel (setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); or setHorizontalAlignment(JLabel.RIGHT);)
determine (JTextField TextFieldUserName = new JTextField(20)) initial Dimension for any of LayoutManager