How Returns Xxxsize from Jcomponent(S) Added to the Jlabel

How returns XxxSize from JComponent(s) added to the JLabel

The default preferred size calculation is to use the layout manager to determine the preferred size of a component. This means the layout manager iterates through all the child components to determine the preferred size of each. For a JPanel, which is meant to be used as a Container this calculation is used.

However, for other Swing components, the getPreferredSize() method is always overridden to provide a reasonable size for the given component.

In the case of a JLabel, the preferred size calculation takes into account the text and the icon used. Since you didn't provide either the preferred size is zero. Of course if you manually override this calculation by using the setPreferredSize() method then the component will have a preferred size.

So even though Swing allows you to add components to any component and use a layout manager to layout the child components, these child components are not used in the preferred size calculation.

This is not just a Nimbus issue.

Is there a way to set a JLabel's PreferredSize to the size of its components?

I'm curious as to why you're using a JLabel as a container, however...

Something like, overriding the JLabel's getPreferredSize method...

@Overrride
public Dimension getPreferredSize() {
LayoutManager lm = getLayout();
return lm.preferredLayoutSize(this);
}

would get you started. This does not take into account the requirements of any borders, you'd need to add those in as well, if it was important to you...

This also assumes, that you've applied a layout manager to the JLabel

Why to add JPanel to a JLabel, under what circumstance, this situation can arise?

An animated image as a BG for the GUI. I use HTML to resize this one (x3), but if it is already the desired size, you could set it directly as the Icon of the label.

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

class LabelAsBackground {

public static final String HTML =
"<html>" +
"<style type'text/css'>" +
"body, html { padding: 0px; margin: 0px; }" +
"</style>" +
"<body>" +
"<img src='http://pscode.org/media/starzoom-thumb.gif'" +
" width=320 height=240>" +
"";

LabelAsBackground() {
JFrame f = new JFrame("Animated Image BG");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JLabel contentPane = new JLabel(HTML);
contentPane.setLayout(new GridLayout());
JPanel gui = new JPanel(new GridLayout(3,3,15,15));
gui.setOpaque(false);
contentPane.add(gui);
gui.setBorder(new EmptyBorder(20,20,20,20));
for (int ii=1; ii<10; ii++) {
gui.add( new JButton("" + ii));
}
f.setContentPane(contentPane);
f.pack();
//f.setResizable(false); // uncomment to see strange effect..
f.setVisible(true);
}

public static void main(String[] args) {
//Create the frame on the event dispatching thread
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
LabelAsBackground lab = new LabelAsBackground();
}
});
}
}

Not sure if it is 'genuine' or not. That seems a subjective term that requires much clarification. I've never used this method and only just figured it out, fumbling around tonight. ;)

Displaying a JLabel on top of another JLabel

..I want to move it a later stage. But right now I want it to show first :)

There are two ways,

1st.

  • Put JLabel car to JPanel, drawing an Image by using paintComponent, instead of JLabel background (advantage JPanel is container with proper notifications for LayoutManager).

  • Put JLabel car to JLabel background, but JLabel haven't implemented any LayoutManager, have to set desired.

    1. Advantage all images in JLabel are static, with zero CPU and GPU inpact ad consumption in compare with paintComponent.
    2. Disadvantage JLabel isn't container and with proper notifications for LayoutManager, required a few code lones moreover in compare with JLabel placed in JPanel, for movement (AbsoluteLayout) is quite good solution.

2nd.

Draw both Images by using BufferedImage and Graphics.

How to put JButton on JLabel?

Thanks to all for reply to me and helping to me. I had done and solve my problem with the help of GridBagLayOut and GridBagConstraints as per my below code :

enter code here

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
*
* @author JAY
*/
public class HomePageOfApp {

private javax.swing.JLabel jLabel1;
private javax.swing.JButton aboutUsBtn;
private javax.swing.JPanel jPanel1;
private javax.swing.JButton powerBtn;
private javax.swing.JButton presetBtn;
private javax.swing.JButton settingBtn;
static JInternalFrame internalFrame = null;
private static final GridBagConstraints gbc;

static {
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
}

public HomePageOfApp() {
initComponents();
internalFrame = new JInternalFrame("Home Page", false, false, true, false);
internalFrame.setBounds(0, 0, 784, 434);
internalFrame.setLocation(0, 0);
internalFrame.setContentPane(wrapInBackgroundImage(jPanel1,
new ImageIcon(
getClass().getResource("/myImage1.jpg"))));
internalFrame.setVisible(true);
}

private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;

jPanel1 = new javax.swing.JPanel();
powerBtn = new javax.swing.JButton();
presetBtn = new javax.swing.JButton();
aboutUsBtn = new javax.swing.JButton();
settingBtn = new javax.swing.JButton();

jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setLayout(new java.awt.GridBagLayout());

powerBtn.setIcon(new javax.swing.ImageIcon("E:\\Image2_60.png")); // NOI18N
powerBtn.setBorderPainted(false);
powerBtn.setContentAreaFilled(false);
powerBtn.setFocusPainted(false);
powerBtn.setPressedIcon(new javax.swing.ImageIcon("E:\\Image2_50.png")); // NOI18N
powerBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
powerBtnActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.ipadx = -31;
gridBagConstraints.ipady = -8;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(106, 27, 0, 0);
jPanel1.add(powerBtn, gridBagConstraints);

presetBtn.setIcon(new javax.swing.ImageIcon("E:\\Image2_60.png")); // NOI18N
presetBtn.setBorderPainted(false);
presetBtn.setContentAreaFilled(false);
presetBtn.setFocusPainted(false);
presetBtn.setPressedIcon(new javax.swing.ImageIcon("E:\\Image2_50.png")); // NOI18N
presetBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
presetBtnActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 0;
gridBagConstraints.ipadx = -31;
gridBagConstraints.ipady = -8;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(106, 26, 0, 19);
jPanel1.add(presetBtn, gridBagConstraints);

aboutUsBtn.setIcon(new javax.swing.ImageIcon("E:\\Image2_60.png")); // NOI18N
aboutUsBtn.setBorderPainted(false);
aboutUsBtn.setContentAreaFilled(false);
aboutUsBtn.setFocusPainted(false);
aboutUsBtn.setPressedIcon(new javax.swing.ImageIcon("E:\\Image2_50.png")); // NOI18N
aboutUsBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aboutUsBtnActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.ipadx = -31;
gridBagConstraints.ipady = -8;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(42, 57, 32, 0);
jPanel1.add(aboutUsBtn, gridBagConstraints);

settingBtn.setIcon(new javax.swing.ImageIcon("E:\\Image2_60.png")); // NOI18N
settingBtn.setBorderPainted(false);
settingBtn.setContentAreaFilled(false);
settingBtn.setFocusPainted(false);
settingBtn.setPressedIcon(new javax.swing.ImageIcon("E:\\Image2_50.png")); // NOI18N
settingBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
settingBtnActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.ipadx = -31;
gridBagConstraints.ipady = -8;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(42, 27, 32, 0);
jPanel1.add(settingBtn, gridBagConstraints);

}

private void powerBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}

private void presetBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}

private void aboutUsBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}

private void settingBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}

/**
* Wraps a Swing JComponent in a background image. Simply invokes the overloded
* variant with Top/Leading alignment for background image.
*
* @param component - to wrap in the a background image
* @param backgroundIcon - the background image (Icon)
* @return the wrapping JPanel
*/
public static JPanel wrapInBackgroundImage(JComponent component,
Icon backgroundIcon) {
return wrapInBackgroundImage(
component,
backgroundIcon,
JLabel.TOP,
JLabel.CENTER);
}

/**
* Wraps a Swing JComponent in a background image. The vertical and horizontal
* alignment of background image can be specified using the alignment
* contants from JLabel.
*
* @param component - to wrap in the a background image
* @param backgroundIcon - the background image (Icon)
* @param verticalAlignment - vertical alignment. See contants in JLabel.
* @param horizontalAlignment - horizontal alignment. See contants in JLabel.
* @return the wrapping JPanel
*/
public static JPanel wrapInBackgroundImage(JComponent component,
Icon backgroundIcon,
int verticalAlignment,
int horizontalAlignment) {

// make the passed in swing component transparent
component.setOpaque(false);

// create wrapper JPanel
JPanel backgroundPanel = new JPanel(new GridBagLayout());
backgroundPanel.setBackground(new java.awt.Color(255, 255, 255));

// add the passed in swing component first to ensure that it is in front
backgroundPanel.add(component, gbc);

// create a label to paint the background image
JLabel backgroundImage = new JLabel(backgroundIcon);

// set minimum and preferred sizes so that the size of the image
// does not affect the layout size
backgroundImage.setPreferredSize(new Dimension(1, 1));
backgroundImage.setMinimumSize(new Dimension(1, 1));

// align the image as specified.
backgroundImage.setVerticalAlignment(verticalAlignment);
backgroundImage.setHorizontalAlignment(horizontalAlignment);

// add the background label
backgroundPanel.add(backgroundImage, gbc);

// return the wrapper
return backgroundPanel;
}
}

JButton on top of JLabel

First of all your question is way too complex with too much code. Your question is about display a button on top of an image. So create a frame with an image and add a button to the image. It should take about 20 lines of code to create a simple program that does this. Then once you understand the basic concept of how to do this you add the changes to your real program.

All the other code you posted is irrelevant to the problem and is completely unnecessary. Learn to simplify your problem when you ask a question.

Now I want to place a JButton on top of the JLabel (the pokertable) but I cant do centerPanel.add(boardCard1.BorderLayout.CENTER); because I already do this for the JLabel.

So you add the button to the label:

label.setLayout( new GridBagLayout() );
label.add(button, new GridBagConstraints());

As long as the component you want to display is smaller than the size of the image on the label the component will be centered in the image.

Can I have a textfield inside a label?

Use a 'composite component' by adding the required parts to a JPanel. E.G.

TimeBeforeClass

import java.awt.FlowLayout;
import javax.swing.*;

class TimeBeforeClass {

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPanel gui = new JPanel(new FlowLayout(FlowLayout.LEFT, 3,3));
gui.add(new JLabel("Open"));
gui.add(new JSpinner(new SpinnerNumberModel(15,0,20,1)));
gui.add(new JLabel("minutes before class"));
JOptionPane.showMessageDialog(null, gui);
}
});
}
}

Note that I swapped the 'textfield' for a JSpinner - a more suitable component for selecting 'time in minutes'.

jlabel icon right alignment and text left alignment

Standard JLabel cannot make a non-static spacing between icon and text, you can only specify iconTextGap in pixels, icon position relative to text and text alignment.

To make what you want you have a few options:

  1. Use some container with label at left side and icon in a separate label at right side
  2. Create specific JLabel UI that will paint icon in the way you want

Why to add JPanel to a JLabel, under what circumstance, this situation can arise?

An animated image as a BG for the GUI. I use HTML to resize this one (x3), but if it is already the desired size, you could set it directly as the Icon of the label.

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

class LabelAsBackground {

public static final String HTML =
"<html>" +
"<style type'text/css'>" +
"body, html { padding: 0px; margin: 0px; }" +
"</style>" +
"<body>" +
"<img src='http://pscode.org/media/starzoom-thumb.gif'" +
" width=320 height=240>" +
"";

LabelAsBackground() {
JFrame f = new JFrame("Animated Image BG");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JLabel contentPane = new JLabel(HTML);
contentPane.setLayout(new GridLayout());
JPanel gui = new JPanel(new GridLayout(3,3,15,15));
gui.setOpaque(false);
contentPane.add(gui);
gui.setBorder(new EmptyBorder(20,20,20,20));
for (int ii=1; ii<10; ii++) {
gui.add( new JButton("" + ii));
}
f.setContentPane(contentPane);
f.pack();
//f.setResizable(false); // uncomment to see strange effect..
f.setVisible(true);
}

public static void main(String[] args) {
//Create the frame on the event dispatching thread
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
LabelAsBackground lab = new LabelAsBackground();
}
});
}
}

Not sure if it is 'genuine' or not. That seems a subjective term that requires much clarification. I've never used this method and only just figured it out, fumbling around tonight. ;)

Need to display ImageIcon when Jbutton is pressed

The primary issue seems to be right here

try{
String path = "/Users/nabeelkhalid/git/s18semesterproject-b4-zigzag1/src/GUI/MatthewPhoto.jpg";
eastImg = new ImageIcon(path);

}catch(Exception ex){
System.out.print(ex);
}

The path is referencing a resource within the context of your src path. You should never reference src in your code, it won't exist once the program is exported (to a Jar or run on a different computer)

Instead, you should consider using Class#getResource to obtain a reference to the image and I'd personally use ImageIO.read over ImageIcon as a personal preference.

try{
String path = "/GUI/MatthewPhoto.jpg";
eastImg = new ImageIcon(ImageIO.read(this.getClass().getResource(path)));
}catch(Exception ex){
System.out.print(ex);
}

And, your next problem is, you're trying to add a JLabel to a JButton, expect, a JButton has not layout manager AND JButton already has support for display an image, so instead, you should be doing something more like...

JButton easterButt = new JButton("Pass CSE 116");
//JLabel eastLbl = new JLabel();
//added button to JLabel
//eastLbl.add(easterButt);
try {
String path = "/GUI/MatthewPhoto.jpg";
eastImg = new ImageIcon(ImageIO.read(this.getClass().getResource(path)));

} catch (Exception ex) {
System.out.print(ex);
}
//added label to Panel
dropDownPanel.add(easterButt);
easterButt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
easterButt.setIcon(eastImg);
}
});

You really should take a closer look at How to Use Buttons, Check Boxes, and Radio Buttons

Test Code

This is the code I used to test the solutions suggested above

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class mainView {

private static JFrame main; //main frame we add everything too
private static JPanel newGame; //panel for new game
private static JPanel dropDownPanel; //panel for the combobox

private static CardLayout clayout; //cardlayout for new game
private static JComboBox dropDown; //dropdown combobox
ImageIcon eastImg;

public void codeNameView() {
main = new JFrame("CodeNames");
main.setSize(600, 900);

//dropdown menu for quit and new game
String[] choice = {" ", "NewGame", "Quit"};
dropDown = new JComboBox(choice);

//below is the panel where we add new game and quit options too
dropDownPanel = new JPanel();
dropDownPanel.setSize(100, 100);
dropDownPanel.add(dropDown);
main.getContentPane().add(dropDownPanel, BorderLayout.NORTH);

//easter egg
JButton easterButt = new JButton("Pass CSE 116");
// JLabel eastLbl = new JLabel();
// //added button to JLabel
// eastLbl.add(easterButt);
try {
String path = "/GUI/MatthewPhoto.jpg";
eastImg = new ImageIcon(ImageIO.read(this.getClass().getResource(path)));

} catch (Exception ex) {
System.out.print(ex);
}
//added label to Panel
dropDownPanel.add(easterButt);
easterButt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
easterButt.setIcon(eastImg);
}
});

//action listener for dropdown combobox
dropDown.addActionListener(new ActionListener() {

/**
* Allows for the user to select New Game or Quit and have the game
* perform said action
*/
@Override
public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub
JComboBox cb = (JComboBox) e.getSource();
Object selectedOption = dropDown.getSelectedItem();

if (selectedOption.equals("Quit")) {
main.dispose();
} else if (selectedOption.equals("NewGame")) {

codeNameView();
System.out.print("yolo");

}
}

});
main.setVisible(true);

}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
System.out.println("Hello");
mainView x = new mainView();
x.codeNameView();
// create a instance on mainview to run instead of using static methods
}
});
}
}


Related Topics



Leave a reply



Submit