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
Related
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());
}
}
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'm using a tabbed pane and can't get the tab to show the GUI that I want. I plan to have different Panel objects for each different tab so that I can setup their layouts with more versatility. Right now I don't have any listeners or functions, and am strictly trying to get the components to show up.
Edit: Code is now in the question, not a link.
Here is the code for the UI for the "General":
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
public class GeneralGUI extends JPanel{
public GeneralGUI() {
JPanel topPanel = new JPanel();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JLabel subjectNum = new JLabel("Subject Street #:");
JLabel subjectStreet = new JLabel("Subject Street Name:");
JTable compTable = new JTable();
JTable subjectTable = new JTable();
JButton getRPT = new JButton("Get RPT file");
JButton getOrder = new JButton("Get Order/Contract");
JButton subjectDocs = new JButton("Get Subject Docs");
JButton compDocs = new JButton("Get Comp Docs");
panel1.add(subjectNum);
panel1.add(subjectStreet);
panel1.add(compTable);
panel2.add(getRPT);
panel2.add(getOrder);
panel2.add(subjectDocs);
panel2.add(compDocs);
panel2.add(subjectTable);
topPanel.add(panel1);
topPanel.add(panel2);
topPanel.setVisible(true);
}
}
Here is the code for the tabbed pane code:
import javax.swing.JTabbedPane;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
public class AppraisalTabs extends JPanel {
public AppraisalTabs() {
super(new GridLayout(1, 1));
JTabbedPane tabbedPane = new JTabbedPane();
GeneralGUI genGUI = new GeneralGUI();
// JComponent panel1 = makeTextPanel("General");
tabbedPane.addTab("General", genGUI);
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
JComponent panel2 = makeTextPanel("Docs");
tabbedPane.addTab("Docs", panel2);
tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
JComponent panel3 = makeTextPanel("Subject");
tabbedPane.addTab("Subject", panel3);
tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
JComponent panel4 = makeTextPanel("Comps");
panel4.setPreferredSize(new Dimension(410, 300));
tabbedPane.addTab("Comps", panel4);
tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
JComponent panel5 = makeTextPanel("Report");
panel4.setPreferredSize(new Dimension(800, 800));
tabbedPane.addTab("Report", panel5);
tabbedPane.setMnemonicAt(4, KeyEvent.VK_5);
//Add the tabbed pane to this panel.
add(tabbedPane);
//The following line enables to use scrolling tabs.
tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
}
protected JComponent makeTextPanel(String text) {
JPanel panel = new JPanel(false);
JLabel filler = new JLabel(text);
filler.setHorizontalAlignment(JLabel.CENTER);
panel.setLayout(new GridLayout(1, 1));
panel.add(filler);
return panel;
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Appraisal Helper");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add content to the window.
frame.add(new AppraisalTabs(), BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
My problem is that once I run the code the tabbed pane shows up, as well as the correctly-titled tabs, but the "General" tab isn't showing anything at all. I tried to setup the buttons and everything in it but it's still blank.
Any ideas?
I'm trying to build a very simple connect 4 game using Swing.
The main game works as intended, but when I use it as a component in a larger GUI, I can no longer interact with it.
This is the main GUI code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainLayout extends JFrame {
public MainLayout(){
// TOP PANEL, series of button using FlowLayout
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 30, 10));
topPanel.setBackground(Color.BLUE);
JButton newGameBtn = new JButton("New Game");
topPanel.add(newGameBtn);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new BorderLayout(5,5));
this.getContentPane().setBackground(Color.cyan);
this.setTitle("Connect 4");
JPanel grid = new JPanel(new GridLayout(6,7,3,3));
grid.setBackground(Color.blue);
board comp = new board(new Dimension(7,6), new Dimension(60, 60));
comp.setFocusable(true);
comp.setEnabled(true);
this.getContentPane().add(topPanel, BorderLayout.NORTH);
this.getContentPane().add(comp, BorderLayout.CENTER);
this.setSize(420,430);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MainLayout mainWindow = new MainLayout();
mainWindow.setVisible(true);
}
}
The board component uses keyboard input to move a square around.
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)