Why isn't this JLabel in the center of this Java application? - java

newbie Java programmer here:
I hate asking questions every time I run into a problem, but I don't see what I should use to get the green "Hello World" label go right into the center of the JPanel. Here is my code:
package game;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Javagame extends JPanel implements ActionListener{
protected JButton b1;
private JLabel label;
public Javagame() {
b1 = new JButton("Button!");
b1.setActionCommand("change");
b1.addActionListener(this);
add(b1);
label = new JLabel("Hello World!", SwingConstants.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 20));
label.setForeground(new Color(0x009900));
add(label, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
if ("change".equals(e.getActionCommand())) {
label.setText("Hello Universe!");
b1.setActionCommand("changeBack");
}
if ("changeBack".equals(e.getActionCommand())) {
label.setText("Hello World!");
b1.setActionCommand("change");
}
}
private static void createWindow(){
JFrame frame = new JFrame("Javagame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(500,500));
Javagame newContentPane = new Javagame();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createWindow();
}
}
BorderLayout.CENTER doesn't seem to work in add(). Any help would be appreciated, thank you!

The JLabel is in the centered within the parent container, the text is aligned within the label.
Try...
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);

BorderLayout.CENTER doesn't seem to work
The default layout of a JPanel is a FlowLayout. You need to set the layout to a BorderLayout.
Also, you need to add the button to the NORTH of the BorderLayout.
Then the button will appear at the top and the label will be centered.

When adding the label use FlowLayout field.
//Code apove
label = new JLabel("Hello World!", SwingConstants.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 20));
label.setForeground(new Color(0x009900));
add(label, FlowLayout.CENTER);//!!
//Code under
Because you haven't changed the layout in your panel, don't use BorderLayout.
If you really want to use BorderLayout rarther than FlowLayout add just setLayout() command in it.
//Code apove
label = new JLabel("Hello World!", SwingConstants.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 20));
label.setForeground(new Color(0x009900));
setLayout(new BorderLayout()); //!!
add(label, BorderLayout.CENTER);
add(b1,BorderLayout.????); //Edited
//Code under
#Edit - add your button too after setLayout() method or set the layout in the beginning when you make you panel

Related

Panel not showing object [duplicate]

I have a JPanel and JButton on the JFrame.
on runtime add JLabel to JPanel When click JButton.
I use of the following code:
panel.setLayout(null);
jLabel _lbl=new jLabel();
_lbl.setText("Label");
panel.add(_lbl);
panel.validate();
but no display any JLabel in JPanel.
I see you create a JLabel called _lbl:
JLabel _lbl=new JLabel();
but you never add it to your panel. Instead you add a new JLabel with no text to your panel:
panel.add(new JLabel());
This would ofcourse construct an empty label which wont be visible.
Also try calling revalidate() and repaint() on your JPanel instance after adding the JLabel like so:
JLabel _lbl=new JLabel("Label");//make label and assign text in 1 line
panel.add(_lbl);//add label we made
panel.revalidate();
panel.repaint();
With this you may also need to call pack() on your frames instance so as to resize the JFrame to fit the new components.
Also please never use a null/Absolute layout this is very bad practice (unless doing animation) and may prove to be problematic and very hard to use.
Rather use a LayoutManager:
A Visual Guide to Layout Managers
or if you only have a single component on the JPanel simply call add(label); as it will stretch to the JPanel size.
UPDATE:
Here is a small sample. Simply adds JLabels to the JPanel each time JButton is pressed:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JavaApplication116 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JavaApplication116().createAndShowUI();
}
});
}
private void createAndShowUI() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents(frame);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
private void initComponents(final JFrame frame) {
final JPanel panel = new JPanel(new FlowLayout());
JButton button = new JButton("Add label");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JLabel _lbl = new JLabel("Label");//make label and assign text in 1 line
panel.add(_lbl);//add label we made
panel.revalidate();
panel.repaint();
frame.pack();//so our frame resizes to compensate for new components
}
});
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.getContentPane().add(button, BorderLayout.SOUTH);
}
}

Can't position Buttons or JLabels

I am new to working with GUI's in Java and I am having a problem moving my text and buttons around. No matter what coordinates I give my button or any of the other JLabel it doesn't move, I was wondering how I could fix it this in such a way that I can place my components where ever I want on the JPanel
public class IntroPage extends JFrame {
public static void main(String[] args) {
IntroPage main = new IntroPage();
main.setVisible(true);
}
private JPanel contentPane;
public IntroPage (){
//make sure the program exits when the frame closes
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Welcome");
contentPane = new JPanel();
setSize(400,700);
//This will center the JFrame in the middle of the screen
setLocationRelativeTo(null);
//Welcome Page stuff :D
JLabel ApplauseLabel = new JLabel("Welcome to U.X.Dot.X");
ApplauseLabel.setFont(new Font("Gill Sans MT", Font.PLAIN, 30));
ApplauseLabel.setLocation(100, 50);
contentPane.add(ApplauseLabel);
JLabel slogan = new JLabel("Register below");
slogan.setFont(new Font("Gill Sans MT", Font.PLAIN, 15));
slogan.setLocation(100, 400);
contentPane.add(slogan);
//FacebookSignUp.
JButton FBbutton = new JButton("Login With FaceBook");
FBbutton.setBackground(Color.BLUE);
FBbutton.setSize(50,50);
FBbutton.setLocation(20, 40);
FBbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Add JPanel to go to FB API. Much later
}
});
contentPane.add(FBbutton);
add(contentPane);
//make sure the JFrame is visible
setVisible(true);
}
}
You're ignoring the layout managers of your contentPane JPanel. Understand that it uses FlowLayout by default, and will ignore your setLocation and setBounds statements. Ror the JPanel to accept absolute positioning, you would have to give it a null layout via contentPane.setLayout(null).
Having said that, I do not advise you to do this! While null layouts, setLocation(...) and setBounds(...) might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
For example the following GUI
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import javax.swing.*;
public class IntroPage2 extends JPanel {
public static final String TITLE = "Welcome to U.X.Dot.X";
private JLabel welcomeLabel = new JLabel(TITLE, SwingConstants.CENTER);
private JButton fbButton = new JButton("Login With Facebook");
public IntroPage2() {
fbButton.setBackground(Color.BLUE);
fbButton.setForeground(Color.CYAN);
welcomeLabel.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 30));
int wlGap = 20;
welcomeLabel.setBorder(BorderFactory.createEmptyBorder(wlGap, wlGap, wlGap, wlGap));
JLabel registerBelowLabel = new JLabel("Register Below");
registerBelowLabel.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
JPanel centralPanel = new JPanel(new GridBagLayout());
centralPanel.setPreferredSize(new Dimension(300, 600));
centralPanel.add(registerBelowLabel);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(fbButton, BorderLayout.LINE_START);
topPanel.add(welcomeLabel, BorderLayout.CENTER);
setLayout(new BorderLayout());
int ebGap = 8;
setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
add(topPanel, BorderLayout.PAGE_START);
add(centralPanel, BorderLayout.CENTER);
}
private static void createAndShowGui() {
IntroPage2 mainPanel = new IntroPage2();
JFrame frame = new JFrame("Welcome");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
would create something like:

How to resize a JTextField within a JFrame?

I am just creating a simple GUI for practice I want to have a few text boxes within my JFrame but I the JTextField I created is taking up the whole frame. I tried doing .setSize but that didn't work.
JFrame
public static Component textbox(String x){
JLabel lbltAm= new JLabel(x);
JTextField tftAm = new JTextField(20);
lbltAm.setLabelFor(tftAm);
lbltAm.setFont(new Font("Serif", Font.PLAIN, 18));
tftAm.setSize(10, 10);
return tftAm;
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Tip Calculator");
//Add Textbox
frame.add(textbox("TipAmmount"));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.gray);
frame.setPreferredSize(new Dimension(250, 400));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
It's because you are not using any layout I suggest to use FlowLayout and GridBagLayout.
Instead of returning JTextField return a Panel object and add the JTextField and Jlabel Object into the panel.You can use any layout I've used BorderLayout
public static Component textbox(String x){
JPanel panel = new JPanel(new BorderLayout());
JLabel lbltAm= new JLabel(x);
JTextField tftAm = new JTextField(20);
lbltAm.setLabelFor(tftAm);
lbltAm.setFont(new Font("Serif", Font.PLAIN, 18));
tftAm.setSize(10, 10);
panel.add(lbltAm, BorderLayout.NORTH);
panel.add(tftAm, BorderLayout.CENTER);
return panel;
}
There are multiple layout using which you can layout components in a Panel. have a look
Its not a good practice to add components directly to JFrame
use it like this
frame.getContentPane().add(component)
or if using borderlayout you can add like this
frame.getContentPane().add(compnent, BorderLayout.CENTER);

How to make a button take you to another frame in GUI java?

I would like to go to another frame of Connect Four by clicking the "PLAY ME" button, but I am very confused on how to do so. Here, I have the code for the opening page of connect four and labels and buttons set up on the page.
Here is my code:
import java.awt.*;
import javax.swing.event.*;
import java.awt.Color.*;
import javax.swing.*;
import java.util.*;
public class Game implements ActionListener{
public Game(){
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(new Dimension(1000,1000));
frame.setTitle("Connect Four");
frame.setLayout(new BorderLayout());
JButton play = new JButton();
play.setPreferredSize(new Dimension(75,150));
play.setBackground(Color.RED);
play.setFont(new Font("Arial", Font.PLAIN, 40));
play.setForeground(Color.BLACK);
play.setText("CLICK ME TO PLAY");
frame.add(play, BorderLayout.SOUTH);
JPanel north = new JPanel(new BorderLayout());
JLabel title = new JLabel("Connect Four");
north.setBackground(Color.WHITE);
title.setFont(new Font("Arial", Font.PLAIN, 100));
title.setForeground(Color.RED);
title.setHorizontalAlignment(0);
title.setVerticalAlignment(1);
frame.add(north, BorderLayout.NORTH);
north.add(title);
JPanel intro = new JPanel(new GridLayout(10,1));
intro.setBackground(Color.WHITE);
JLabel instructions = new JLabel("Instructions");
instructions.setFont(new Font("Ariel", Font.PLAIN, 70));
JLabel instructionsPart1 = new JLabel("Both players will be assigned a color, either red or black.");
JLabel instructionsPart2 = new JLabel("Players will take turns placing the colored discs on to the board.");
JLabel instructionsPart3 = new JLabel("The OBJECTIVE is to get four of one colored discs in a row.");
instructionsPart1.setFont(new Font("Ariel", Font.PLAIN, 35));
instructionsPart2.setFont(new Font("Ariel", Font.PLAIN, 35));
instructionsPart3.setFont(new Font("Ariel", Font.PLAIN, 35));
intro.add(instructions);
intro.add(new JLabel(""));
intro.add(instructionsPart1);
intro.add(new JLabel(""));
intro.add(instructionsPart2);
intro.add(new JLabel(""));
intro.add(instructionsPart3);
intro.add(new JLabel(""));
frame.add(intro, BorderLayout.CENTER);
frame.add(intro);
}
}
Hide Your First Frame And Set Visiblity of second frame to true
btnplay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
second_add second = new second_add();
setVisible(false); // Hide current frame
second.setVisible(true);
}
});
Rather than changing the frame, change the panel. Instead of using JFrame's add() method, use setContentPane(Container container)
Instead of adding buttons and what not to the frame, create another wrapper panel and use the BorderLayout on that, and then add that panel to the frame:
Example:
JPanel wrapper = new JPanel(new BorderLayout());
wrapper.add(play, BorderLayout.SOUTH);
//etc.
frame.setContentPane(wrapper);
Then, to handle the button click, implement the ActionListener interface. Don't do it with the main class - you'll need more than one. Use an anonymous inner class, or a lambda expression. Example:
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setContentPane(someOtherJPanel);
}
});

add component to jpanel on runtime

I have a JPanel and JButton on the JFrame.
on runtime add JLabel to JPanel When click JButton.
I use of the following code:
panel.setLayout(null);
jLabel _lbl=new jLabel();
_lbl.setText("Label");
panel.add(_lbl);
panel.validate();
but no display any JLabel in JPanel.
I see you create a JLabel called _lbl:
JLabel _lbl=new JLabel();
but you never add it to your panel. Instead you add a new JLabel with no text to your panel:
panel.add(new JLabel());
This would ofcourse construct an empty label which wont be visible.
Also try calling revalidate() and repaint() on your JPanel instance after adding the JLabel like so:
JLabel _lbl=new JLabel("Label");//make label and assign text in 1 line
panel.add(_lbl);//add label we made
panel.revalidate();
panel.repaint();
With this you may also need to call pack() on your frames instance so as to resize the JFrame to fit the new components.
Also please never use a null/Absolute layout this is very bad practice (unless doing animation) and may prove to be problematic and very hard to use.
Rather use a LayoutManager:
A Visual Guide to Layout Managers
or if you only have a single component on the JPanel simply call add(label); as it will stretch to the JPanel size.
UPDATE:
Here is a small sample. Simply adds JLabels to the JPanel each time JButton is pressed:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JavaApplication116 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JavaApplication116().createAndShowUI();
}
});
}
private void createAndShowUI() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents(frame);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
private void initComponents(final JFrame frame) {
final JPanel panel = new JPanel(new FlowLayout());
JButton button = new JButton("Add label");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JLabel _lbl = new JLabel("Label");//make label and assign text in 1 line
panel.add(_lbl);//add label we made
panel.revalidate();
panel.repaint();
frame.pack();//so our frame resizes to compensate for new components
}
});
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.getContentPane().add(button, BorderLayout.SOUTH);
}
}

Categories