I'm trying to get the ">>" button to be centered vertically, using a GroupLayout.
But as you can see it is putting it near the top. I've tried messing with the layout and can't seem to get it to work. Please help! =)
horizontal_group = layout.createParallelGroup GroupLayout::Alignment::CENTER
horizontal_group.addComponent tags_label
available_across_hor = layout.createSequentialGroup
available_down_hor = layout.createParallelGroup GroupLayout::Alignment::CENTER
available_down_hor.addComponent available_label
available_down_hor.addComponent available_pane
available_down_hor.addComponent new_tag_button
selected_down_hor = layout.createParallelGroup GroupLayout::Alignment::CENTER
selected_down_hor.addComponent selected_label
selected_down_hor.addComponent selected_pane
selected_down_hor.addComponent remove_tag_button
available_across_hor.addGroup available_down_hor
available_across_hor.addComponent move_button
available_across_hor.addGroup selected_down_hor
horizontal_group.addGroup available_across_hor
vertical_group = layout.createSequentialGroup
vertical_group.addComponent tags_label
available_across_ver = layout.createParallelGroup
available_down_ver = layout.createSequentialGroup
available_down_ver.addComponent available_label
available_down_ver.addComponent available_pane
available_down_ver.addComponent new_tag_button
selected_down_ver = layout.createSequentialGroup
selected_down_ver.addComponent selected_label
selected_down_ver.addComponent selected_pane
selected_down_ver.addComponent remove_tag_button
available_across_ver.addGroup available_down_ver
available_across_ver.addComponent move_button
available_across_ver.addGroup selected_down_ver
vertical_group.addGroup available_across_ver
layout.setHorizontalGroup horizontal_group
layout.setVerticalGroup vertical_group
Here is the solution:
package com.zetcode;
import java.awt.Container;
import java.awt.EventQueue;
import javax.swing.GroupLayout;
import static javax.swing.GroupLayout.Alignment.CENTER;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class GroupLayoutTags extends JFrame {
public GroupLayoutTags() {
initUI();
setTitle("Tags");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void initUI() {
Container pane = getContentPane();
GroupLayout gl = new GroupLayout(pane);
pane.setLayout(gl);
JLabel avLbl = new JLabel("Available");
JLabel tagsLbl = new JLabel("Tags");
JLabel selLbl = new JLabel("Selected");
JButton newBtn = new JButton("New");
JButton moveBtn = new JButton(">>");
JButton remBtn = new JButton("Remove");
JList leftList = new JList();
JScrollPane spleft = new JScrollPane(leftList);
JList rightList = new JList();
JScrollPane spright = new JScrollPane(rightList);
gl.setAutoCreateGaps(true);
gl.setAutoCreateContainerGaps(true);
gl.setHorizontalGroup(gl.createParallelGroup(CENTER)
.addComponent(tagsLbl)
.addGroup(gl.createSequentialGroup()
.addGroup(gl.createParallelGroup(CENTER)
.addComponent(avLbl)
.addComponent(spleft, 100, 200, Short.MAX_VALUE)
.addComponent(newBtn))
.addComponent(moveBtn)
.addGroup(gl.createParallelGroup(CENTER)
.addComponent(selLbl)
.addComponent(spright, 100, 200, Short.MAX_VALUE)
.addComponent(remBtn)))
);
gl.setVerticalGroup(gl.createSequentialGroup()
.addComponent(tagsLbl)
.addGroup(gl.createParallelGroup(CENTER)
.addGroup(gl.createSequentialGroup()
.addComponent(avLbl)
.addComponent(spleft, 100, 250, Short.MAX_VALUE)
.addComponent(newBtn))
.addComponent(moveBtn)
.addGroup(gl.createSequentialGroup()
.addComponent(selLbl)
.addComponent(spright, 100, 250, Short.MAX_VALUE)
.addComponent(remBtn)))
);
pack();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
GroupLayoutTags ex = new GroupLayoutTags();
ex.setVisible(true);
}
});
}
}
If find MigLayout manager easier to use than GroupLayout.
However with some practice, GroupLayout is also feasible.
Try create filler components:
Component topFiller = Box.createVerticalGlue();
Component bottomFiller = Box.createVerticalGlue();
and then add topFiller before the >> button, and bottomFiller after it for both horizontal and vertical group.
Related
I wrote a little something here. It's working if I don't backPanel.setLayout(new GridBagLayout);
But without the grid bag, the content stays in the top left I maximise the screen.
With the grid bag I only get the red backPanel in the frame. Well, there is a gray pixel in the middle of the screen. I'm assuming that's my panel, but I can't make it bigger. I tried setSize but it doesn't change. Also, I had the panel.setBounds(0, 0, getWidth(),getHeight());. I'm not sure why I removed it.
My main is in the other file. The only thing it does at the moment is to call the LoginFrame.
Here is the code:
package first;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class LoginFrame extends JFrame implements ActionListener {
private JTextField textField;
private JPasswordField passwordField;
public LoginFrame() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 300);
JPanel backPanel = new JPanel(new GridBagLayout());
backPanel.setBackground(Color.RED);
JPanel panel = new JPanel();
panel.setSize(500, 300);
panel.setBackground(Color.LIGHT_GRAY);
panel.setLayout(null);
JLabel label;
panel.add(label = new JLabel("Username:"));
label.setBounds(20, 100, 100, 25);
panel.add(textField = new JTextField());
textField.setBounds(140, 100, 200, 25);
panel.add(label = new JLabel("Password:"));
label.setBounds(20, 145, 100, 25);
panel.add(passwordField = new JPasswordField());
passwordField.setBounds(140, 145, 200, 25);
panel.add(label = new JLabel("CTC Bank"));
label.setFont(new Font("New Times Roman", Font.BOLD, 50));
label.setBounds(0, 0, getWidth(), 100);
label.setHorizontalAlignment(JLabel.CENTER);
JButton button;
panel.add(button = new JButton("Login"));
button.setBounds(140, 200, 100, 25);
button.addActionListener(this);
button = defaultActionKeyEnter(button, KeyEvent.VK_ENTER);
panel.add(button = new JButton("Register"));
button.setBounds(240, 200, 100, 25);
button.addActionListener(this);
button = defaultActionKeyEnter(button, KeyEvent.VK_ENTER);
//add(panel);
backPanel.add(panel);
add(backPanel, BorderLayout.CENTER);
revalidate();
repaint();
setLocationRelativeTo(null);
setVisible(true);
}
public static JButton defaultActionKeyEnter(JButton button, int desiredKeyCode) {
InputMap inputMap = button.getInputMap(JComponent.WHEN_FOCUSED);
KeyStroke spaceKeyPressed = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false);
KeyStroke spaceKeyReleased = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true);
KeyStroke desiredKeyPressed = KeyStroke.getKeyStroke(desiredKeyCode, 0, false);
KeyStroke desiredKeyReleased = KeyStroke.getKeyStroke(desiredKeyCode, 0, true);
inputMap.put(desiredKeyPressed, inputMap.get(spaceKeyPressed));
inputMap.put(desiredKeyReleased, inputMap.get(spaceKeyReleased));
inputMap.put(spaceKeyPressed, "none");
inputMap.put(spaceKeyReleased, "none");
return button;
}
// Unfinished code dont worry bout it...
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Login")) {
if (textField.getText().equals("Heinz")
&& (new String(passwordField.getPassword()).equals("password123"))) {
// color = Color.GREEN;
} else {
JOptionPane.showMessageDialog(this, "Wrong Username or Password", "Error", JOptionPane.WARNING_MESSAGE);
// color = Color.RED;
}
} else {
JOptionPane.showMessageDialog(this, "Cya");
dispose();
setVisible(false);
}
// panel.setBackground(color);
}
}
I have seen questions about this but none of the answers were helpful in my case.
Calling the following didn't help.
revalidate();
repaint();
Did I maybe add it in the wrong order?
And how does the code look like to you? Would you consider this clean?
The layout of backPanel will mis-calculate the dimensions of "panel" because "panel" does not participate in layout management properly, without a layout manager of its own.
One solution to this is to use setLayout(null) also on the "backPanel", or add "panel" directly to the JFrame.
With the first suggestion ("backPanel.setLayout(null);" just after it is created), plus the following main method:
public static void main(String[] args) {
new LoginFrame();
}
I get this:
I have to do a project in Java and thought a GUI Text Adventure would be cool. My Problem is that when I create a JPanel and move it further down on the screen, the panel first changes its size and then disappears completely at one point.
On the GameScreen there should be a panel for choice Options to be put on but it refuses to go further down than about half the size of the Screen.
Here's the code:
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Yeet {
JFrame epicOfYeet;
Container con;
JPanel titleNamePanel, startButtonPanel, mainTextPanel, choiceButtonPanel;
JLabel titleNameLabel;
Font titleFont = new Font("Times New Roman", Font.PLAIN, 90);
Font normalFont = new Font ("Times New Roman", Font.PLAIN, 55);
JButton startButton;
JButton choice1;
JButton choice2;
JButton choice3;
JButton choice4;
JTextArea mainTextArea;
TitleScreenHandler tsHandler = new TitleScreenHandler();
public static void main(String[] args) {
new Yeet();
}
public Yeet() {
epicOfYeet = new JFrame();
epicOfYeet.setSize(1200, 1000);
epicOfYeet.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
epicOfYeet.getContentPane().setBackground(Color.black);
epicOfYeet.setLayout(null);
con = epicOfYeet.getContentPane();
titleNamePanel = new JPanel();
titleNamePanel.setBounds(190, 100, 800, 230);
titleNamePanel.setBackground(Color.black);
titleNameLabel = new JLabel("EPIC OF YEET");
titleNameLabel.setForeground(Color.red);
titleNameLabel.setFont(titleFont);
startButtonPanel = new JPanel();
startButtonPanel.setBounds(400, 500, 400, 100);
startButtonPanel.setBackground(Color.black);
startButton = new JButton("START");
startButton.setBackground(Color.black);
startButton.setForeground(Color.white);
startButton.setFont(normalFont);
startButton.addActionListener(tsHandler);
startButton.setFocusPainted(false);
titleNamePanel.add(titleNameLabel);
startButtonPanel.add(startButton);
con.add(titleNamePanel);
con.add(startButtonPanel);
epicOfYeet.setVisible(true);
}
public void createGameScreen(){
titleNamePanel.setVisible(false);
startButtonPanel.setVisible(false);
mainTextPanel = new JPanel();
mainTextPanel.setBounds(100, 100, 1000, 400);
mainTextPanel.setBackground(Color.green);
con.add(mainTextPanel);
mainTextArea = new JTextArea("You come to your senses again.\nThe dewy grass you're laying on is gleaming with moonlight.\nYour body aches as you get up and catch a \nglimpse of your surroundings.\n");
mainTextArea.setBounds(100, 100, 1000, 250);
mainTextArea.setBackground(Color.blue);
mainTextArea.setForeground(Color.white);
mainTextArea.setFont(normalFont);
mainTextArea.setLineWrap(true);
mainTextPanel.add(mainTextArea);
choiceButtonPanel = new JPanel();
choiceButtonPanel.setBounds(300, 500, 600, 550);
choiceButtonPanel.setBackground(Color.red);
con.add(choiceButtonPanel);
}
public class TitleScreenHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent event) {
createGameScreen();
}
}
}
Here is a basic implementation using layout mangers, avoiding the bad practice of null layout manager.
It is not an optimal one, but should get you started:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Yeet {
JFrame epicOfYeet;
Container con;
JPanel titleNamePanel, startButtonPanel, mainTextPanel, choiceButtonPanel;
JLabel titleNameLabel;
Font titleFont = new Font("Times New Roman", Font.PLAIN, 90);
Font normalFont = new Font ("Times New Roman", Font.PLAIN, 55);
JButton startButton, coice1, choice2, choice3, choice4;
JTextArea mainTextArea;
TitleScreenHandler tsHandler = new TitleScreenHandler();
public static void main(String[] args) {
SwingUtilities.invokeLater(()->new Yeet());
}
public Yeet() {
epicOfYeet = new JFrame();
//epicOfYeet.setSize(1200, 1000); // do not set size. let layout manager calcualte it
epicOfYeet.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
epicOfYeet.getContentPane().setBackground(Color.black);
//epicOfYeet.setLayout(null); //aviod null layouts Jframe uses BorderLayout by default
con = epicOfYeet.getContentPane();
titleNamePanel = new JPanel();
//titleNamePanel.setBounds(190, 100, 800, 230);
titleNamePanel.setPreferredSize(new Dimension(800, 230));//set preferred size to be used by layout manager
titleNamePanel.setBackground(Color.black);
titleNameLabel = new JLabel("EPIC OF YEET");
titleNameLabel.setForeground(Color.red);
titleNameLabel.setFont(titleFont);
startButtonPanel = new JPanel();
//startButtonPanel.setBounds(400, 500, 400, 100);
startButtonPanel.setPreferredSize(new Dimension(400, 100));
startButtonPanel.setBackground(Color.black);
startButton = new JButton("START");
startButton.setBackground(Color.black);
startButton.setForeground(Color.white);
startButton.setFont(normalFont);
startButton.addActionListener(tsHandler);
startButton.setFocusPainted(false);
titleNamePanel.add(titleNameLabel);
startButtonPanel.add(startButton);
con.add(titleNamePanel, BorderLayout.PAGE_START); //set to top
con.add(startButtonPanel, BorderLayout.PAGE_END); //set to bottom
epicOfYeet.pack();
epicOfYeet.setVisible(true);
}
public void createGameScreen(){
//titleNamePanel.setVisible(false);
//startButtonPanel.setVisible(false);
con.remove(titleNamePanel);
con.remove(startButtonPanel);
mainTextPanel = new JPanel();
//mainTextPanel.setBounds(100, 100, 1000, 400);
mainTextPanel.setBackground(Color.green);
con.add(mainTextPanel); // added to center position of the BorderLayout (the default)
mainTextArea = new JTextArea(10, 20); //size in rows, cols
mainTextArea.setText("You come to your senses again.\nThe dewy grass you're laying on is gleaming with moonlight.\nYour body aches as you get up and catch a \nglimpse of your surroundings.\n");
//mainTextArea.setBounds(100, 100, 1000, 250);
mainTextArea.setBackground(Color.blue);
mainTextArea.setForeground(Color.white);
mainTextArea.setFont(normalFont);
mainTextArea.setLineWrap(true);
mainTextPanel.add(mainTextArea);
choiceButtonPanel = new JPanel();
//choiceButtonPanel.setBounds(300, 500, 600, 550);
choiceButtonPanel.setPreferredSize(new Dimension(600, 550));
choiceButtonPanel.setBackground(Color.red);
con.add(choiceButtonPanel, BorderLayout.PAGE_END);//add to bottom
epicOfYeet.pack();
}
public class TitleScreenHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent event) {
createGameScreen();
}
}
}
As the title, I want to create two buttons in java swing and these two buttons can overlap each other (as image). I searched the internet but I could not find it.
Thanks so much
You can simply do this by setting the JFrame layout to Absolute Layout, and adding a JButton on top of another JButton. Make sure the small button is on top of the other button in the navigator.
You can use an OverlayLayout here.
An SSCCE (with comments inside) would be:
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.OverlayLayout;
import javax.swing.SwingUtilities;
public class OverlayLayoutExample extends JFrame {
JPanel overlayoutPanel;
JButton jButton2, jButton1;
public OverlayLayoutExample() {
overlayoutPanel = new JPanel() {
#Override
public boolean isOptimizedDrawingEnabled() {
//Required to have always visible both components
return false;
}
};
OverlayLayout overlay = new OverlayLayout(overlayoutPanel);
overlayoutPanel.setLayout(overlay);
jButton1 = new JButton("jButton");
Dimension d1 = new Dimension(350, 100);
jButton1.setMaximumSize(d1);
jButton1.setAlignmentX(0.7f); //Some X-Y values, play with them
jButton1.setAlignmentY(0.65f); //Some X-Y values, play with them
jButton2 = new JButton("jButton2");
Dimension d2 = new Dimension(100, 25);
jButton2.setMaximumSize(d2);
jButton2.setAlignmentX(0.01f); //Some X-Y values, play with them
jButton2.setAlignmentY(0.01f); //Some X-Y values, play with them
overlayoutPanel.add(jButton2); //First the top component
overlayoutPanel.add(jButton1); //Then the above component
getContentPane().add(overlayoutPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(() -> new OverlayLayoutExample().setVisible(true));
}
}
More about isOptimizedDrawingEnabled() can be found here.
Preview:
You can do this using the layered pane of JFrame like this:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
public class ButtonOnTop
{
public static void main(String[] args)
{
JButton button1 = new JButton("jButton1");
button1.setBounds(30, 50, 260, 160);
JButton button2 = new JButton("jButton2");
button2.setBounds(150, 150, 100, 40);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLayeredPane layeredPane = f.getLayeredPane();
layeredPane.add(button1, Integer.valueOf(0));
layeredPane.add(button2, Integer.valueOf(1));
f.setBounds(300, 200, 400, 300);
f.setVisible(true);
}
}
I have made a student information page using GUI concept. I want to know that how can i add an image at a specific location using JLabel or any other method? What i want is a background image surrounding the whole Jframe and another image at specific location like at the top right. How can i achieve this?
i also found a code to add image using Jlabel but it doesn't work with my code as my setting the layout to null.
the code i found
String path = "Image1.jpg";
File file = new File(path);
BufferedImage image = ImageIO.read(file);
JLabel label = new JLabel(new ImageIcon(image));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(label);
f.pack();
f.setLocation(200,200);
f.setVisible(true);
Below is my code:
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class LoginPage
{
JFrame jf;
JLabel gender,hobbies,name_label,rollno_label,marks_label,city_label,address_label;
JTextField name_field,rollno_field,marks_field;
JRadioButton male,female;
ButtonGroup bg;
JCheckBox photography,music,sketching,coding;
JComboBox city_combo;
JTextArea adress_textarea;
JButton save, exit;
JMenuBar mbar;
JMenu file,edit,help;
JMenuItem open,save_item,edit_item,close,cut,copy,paste,find,replace,help_content,about,updates;
public LoginPage() //constructor
{
jf = new JFrame("Student Information");
name_label = new JLabel("Student's Name");
name_field = new JTextField();
rollno_label = new JLabel("Student's Roll Number");
rollno_field = new JTextField();
marks_label = new JLabel("Student's Total Marks Achieved");
marks_field = new JTextField();
gender = new JLabel("Gender");
male = new JRadioButton("Male");
female = new JRadioButton("Female");
bg = new ButtonGroup();
hobbies = new JLabel("Hobbies");
photography = new JCheckBox("Photography");
music = new JCheckBox("Music");
coding = new JCheckBox("Coding");
sketching = new JCheckBox("Sketching");
city_label = new JLabel("City");
city_combo = new JComboBox();
address_label = new JLabel("Residential Address");
adress_textarea = new JTextArea();
save = new JButton("Save");
exit = new JButton("Exit");
mbar = new JMenuBar();
file = new JMenu("File");
edit = new JMenu("Edit");
help = new JMenu("Help");
open = new JMenuItem("open");
save_item = new JMenuItem("Save");
edit_item = new JMenuItem("Edit");
close = new JMenuItem("Close");
cut = new JMenuItem("Cut");
copy = new JMenuItem("Copy");
paste = new JMenuItem("Paste");
find = new JMenuItem("Find");
replace = new JMenuItem("Replace");
about = new JMenuItem("About");
updates = new JMenuItem("Check for Updates");
help_content = new JMenuItem("Help Content");
}
void Display()
{
jf.setSize(1000, 700);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLayout(null);
jf.getContentPane().setBackground( Color.LIGHT_GRAY );
name_label.setBounds(50, 50, 150, 20);
name_field.setBounds(300, 50, 200, 20);
rollno_label.setBounds(50, 100, 150, 20);
rollno_field.setBounds(300, 100, 200, 20);
marks_label.setBounds(50, 150, 200, 20);
marks_field.setBounds(300, 150, 200, 20);
gender.setBounds(50, 200, 100, 20);
male.setBounds(300, 200, 80, 20);
female.setBounds(400, 200, 80, 20);
hobbies.setBounds(50, 250, 80, 20);
photography.setBounds(300, 250, 100, 20);
music.setBounds(420, 250, 80, 20);
sketching.setBounds(500, 250, 100, 20);
coding.setBounds(600, 250, 80, 20);
city_label.setBounds(50, 300, 100, 20);
city_combo.setBounds(300, 300, 100, 20);
address_label.setBounds(50, 350, 200, 20);
adress_textarea.setBounds(300, 350, 300, 100);
save.setBounds(300, 500, 100, 50);
exit.setBounds(600, 500, 100, 50);
bg.add(male);
bg.add(female);
city_combo.addItem("Select City");
city_combo.addItem("Chandigarh");
city_combo.addItem("Kurali");
city_combo.addItem("Mohali");
city_combo.addItem("Panchkula");
file.add(open);
file.add(save_item);
file.add(edit_item);
file.add(close);
edit.add(cut);
edit.add(copy);
edit.add(paste);
edit.add(find);
edit.add(replace);
help.add(about);
help.add(help_content);
help.add(updates);
mbar.add(file);
mbar.add(edit);
mbar.add(help);
jf.add(name_label);
jf.add(name_field);
jf.add(rollno_label);
jf.add(rollno_field);
jf.add(marks_label);
jf.add(marks_field);
jf.add(gender);
jf.add(male);
jf.add(female);
jf.add(hobbies);
jf.add(music);
jf.add(photography);
jf.add(sketching);
jf.add(coding);
jf.add(city_label);
jf.add(city_combo);
jf.add(address_label);
jf.add(adress_textarea);
jf.add(save);
jf.add(exit);
jf.setJMenuBar(mbar);
jf.setVisible(true);
}
public static void main(String[] args) {
new LoginPage().Display();
}
}
What i want is a background image surrounding the whole Jframe
Suggestions:
Create a class that extends JPanel,
override its paintComponent method
be sure to call the super's paintComponent method in your override
Draw your background image within this method using g.drawImage(...)
Either make this JPanel your JFrame's contentPane or add it to the contentPane BorderLayout.CENTER, and then add your GUI components to this JPanel
Make sure that some of the components are not-opaque, e.g., call setOpaque(false) on your JRadioButtons, and perhaps others, so that the background image shows up.
and another image at specific location like at the top right. How can i achieve this?
Use the same JPanel above, and draw the smaller image using an overload of drawImage(...) that precisely places the image where you want
Notes:
When I create background images for the GUI, I prefer to draw within a JPanel rather than a JLabel since the JLabel is not wired out of the box to act as a contentPane or a decent container.
I strongly advise you not to use null layouts and setBounds as this will lead to gui's that might look good on one platform, but not on another, that have JLabels whose text is not fully seen, that are very difficult to upgrade and maintain. Learn and use the layout managers.
Looks like you're using multiple JFrames. If so, please read: The Use of Multiple JFrames: Good or Bad Practice?
For example, here's one way to display an image as a background image as well as a smaller image in the right upper portion of the GUI, all within a JPanel:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class LoginPage3 extends JPanel {
public static final String BG_IMG_PATH = "https://upload.wikimedia.org/wikipedia/"
+ "commons/e/e9/Maesil_%28prunus_mume%29_washed_and_stemmed.jpg";
public static final String RU_IMG_PATH = "https://upload.wikimedia.org/wikipedia/"
+ "commons/thumb/5/5b/Escudo_de_San_Pedro_de_Atacama.svg/200px-Escudo_de_San_Pedro_de_Atacama.svg.png";
private BufferedImage backgroundImg;
private BufferedImage rightUpperImg;
public LoginPage3(BufferedImage bgImg, BufferedImage ruImg) {
this.backgroundImg = bgImg;
this.rightUpperImg = ruImg;
}
#Override
public Dimension getPreferredSize() {
if (backgroundImg == null || isPreferredSizeSet()) {
return super.getPreferredSize();
} else {
int w = backgroundImg.getWidth();
int h = backgroundImg.getHeight();
return new Dimension(w, h);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (backgroundImg != null) {
g.drawImage(backgroundImg, 0, 0, this);
}
if (rightUpperImg != null) {
int x = getWidth() - rightUpperImg.getWidth();
g.drawImage(rightUpperImg, x, 0, this);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
BufferedImage bg = null;
BufferedImage ru = null;
try {
bg = ImageIO.read(new URL(BG_IMG_PATH));
ru = ImageIO.read(new URL(RU_IMG_PATH));
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
LoginPage3 mainPanel = new LoginPage3(bg, ru);
JFrame frame = new JFrame("LoginPage3");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
For background image:
Load it as an icon, and create a JLabel with it. (See your first snippet)
Set the JLabel as the JFrame's content pane.
All you have to take care of, that Icon does not stretch, so you have to have an image that is exactly the same size as your JFrame (or larger).
As for the image at a given position, the JLabel creating and Icon loading process is the same, but after adding it to the JFrame you have to set position and size, just like for your other components, EG call setBounds()...
I would like to keep a panel I have created using an absolute layout in the center of my window even when the window is resized (if possible). I've come across a couple of suggestions here and [here][2] but no dice! Below is my sample code, any ideas or suggestions? I have no problems centered a single component like a JLable but I want to center a panel with many components!
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.JLabel;
public class TestPanel extends JFrame {
private JLabel lblSetupTitle;
private Border compoundBorder, outlineColorBorder, outlineBorder;
private JTextArea txtrManageData;
private JPanel childPanel;
public TestPanel()
{
setBackground(Color.white);
outlineColorBorder = BorderFactory.createLineBorder(Color.gray);
outlineBorder = BorderFactory.createEmptyBorder(20, 20, 20, 20);
compoundBorder = BorderFactory.createCompoundBorder(outlineColorBorder, outlineBorder);
lblSetupTitle = new JLabel("Setup");
lblSetupTitle.setBounds(443, 288, 44, 23);
txtrManageData = new JTextArea("Text Area Text");
txtrManageData.setBounds(393, 322, 142, 61);
childPanel = new JPanel();
childPanel.setLocation(89, 38);
childPanel.setSize(921, 452);
childPanel.setBorder(compoundBorder);
setupGUIElements();
setupPanel();
}
private void setupGUIElements()
{
txtrManageData.setBackground(null);
txtrManageData.setLineWrap(true);
txtrManageData.setWrapStyleWord(true);
}
private void setupPanel()
{
getContentPane().setLayout(new GridBagLayout()); // set layout of parent panel to GridBagLayout
childPanel.setLayout(null); // set layout of child panel to AbsoluteLayout
childPanel.add(lblSetupTitle);
childPanel.add(txtrManageData);
getContentPane().add(childPanel, new GridBagConstraints());
this.setSize(1020, 500);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TestPanel ex = new TestPanel();
ex.setVisible(true);
}
});
}
}
EDIT: Any tips, links, guidance on creating something like this
I'd nest layouts.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class ThreeButtonTextFieldCombo {
private JPanel ui = null;
ThreeButtonTextFieldCombo() {
initUI();
}
public final void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridBagLayout());
ui.setBorder(new TitledBorder("Parent Panel"));
JPanel controls = new JPanel(new GridLayout(1,0,10,10));
ui.add(controls);
controls.setBackground(Color.RED);
controls.setBorder(new TitledBorder("Child Panel"));
for (int ii=1; ii<4; ii++) {
addLabelAndField(controls, "String " + ii);
}
}
public JComponent getUI() {
return ui;
}
private void addLabelAndField(JPanel panel, String text) {
JPanel controls = new JPanel(new BorderLayout(3, 3));
controls.setBorder(new EmptyBorder(20,20,20,20));
JLabel l = new JLabel(text);
controls.add(l, BorderLayout.PAGE_START);
JTextArea ta = new JTextArea(text, 2, 8);
controls.add(new JScrollPane(ta));
panel.add(controls);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("Three Button/Text Field Combo");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
ThreeButtonTextFieldCombo tbtfc =
new ThreeButtonTextFieldCombo();
f.setContentPane(tbtfc.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
The first problem with your code is that you are adding your child panel using an empty instantiation of GridBagConstraints. I have never seen it used like that before.
getContentPane().add(childPanel, new GridBagConstraints());
Do not set any layout to content pane and just add it like this :
getContentPane().add(childPanel);
Now if you run it you will get the two components in the middle, where you defined them using the setBounds(..) method.
Like almost everyone commenting on your question, you should not use null layout, and use some other layout instead. I would use a GridBagLayout to organise the three buttons and three textfields in your diagram. You could then setBounds(..) on your child panel.
If you really must use absolute layout then you will have to do a bit of maths.
If your first label is like this :
labell1.setBounds(443, 288, 44, 23);
then your second label should be something like this :
labell2.setBounds(443 + someXDisplacement, 288, 44, 23);
..and third :
labell3.setBounds(443 + (someXDisplacement x 2), 288, 44, 23);
You get the picture.