How do you set the bounds of a JLabel in a JFrame? - java

I use a JLabel to view an image in a JFrame. I load it from a file with an ImageIcon.
JFrame frame = new JFrame(String);
frame.setLocationByPlatform(true);
frame.setSize(500, 500);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel cpu = new JLabel(new ImageIcon(String));
cpu.setLocation(20, 20);
cpu.setSize(20, 460);
frame.add(cpu);
frame.setVisible(true);
I can't set location and size of the JLabel because it is done automatically.
I have to manually set these values because I want to truncate the image (vertical progress bar).

One way is to just paint the image:
final ImageIcon icon = new ImageIcon(path);
JPanel panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(icon.getImage(), 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
};
frame.add(panel);
The getWidth() and getHeight() in drawImage will force the image to stretch the size of the panel. Also the getPreferredSize() will give a size to the panel.
If want the panel to stay that size, then make sure it's parent container has a layout manager that will respect preferred sizes, like FlowLayout or GridBagLayout. If you want the panel to be stretched, the make sure it's parent container has a layout manager that disregards the preferred size, like BorderLayout or GridLayout
See Performing Custom Painting for more info on painting.
See Laying Out Components Within a Container to learn more about layout managers (which you should be using). Also see Why is it frowned upon to use a null layout in SWING? and What's wrong with the Null Layout in Java?

The size of your original is (58 x 510). If you want to display the image at a fixed size of 20 x 420, then you should scale your image to that size to you don't truncate any of the image. One way to do that is to use the Image.getScaledImage(...) method. Then you just add the scaled image to the label.
If you want to position your label (20, 20) from the top left of the panel, then you can add an EmptyBorder to the panel or the label.
Use the features of Swing.
Edit:
I want to truncate the image
Read your Image into a BufferedImage. Then you can use the getSubImage(...) method to get an image any size you want. Then you can use the sub image to create your ImageIcon and add it to a label.

The LayoutManager is auto-sizing your components, not allowing you to resize manually.
If you want to get away from this, you can turn off the LayoutManager.
frame.setLayout(null);
Please note that you should not use the null layout.

Related

JLabel wont change Width

I'm programming right now a Chomp Game for Uni. Everything works fine but the Label at the bottom. Its background is supposed to fill out the entire bottom. In the attachment you can see how it instead looks now. I tried setting the minimum and the preferred size of the label. The Height is changing but the width just stays adjusted to the text. How can I change that?
Note: The snippet only contains the setting up of the Frame and Panels in a custom method and not the main class.
private void init()
{
JFrame fenster = new JFrame();
this.spielfeld = new SpielfeldPanel(M, N);
this.anzeige = new SpielerAnzeigeLabel(this.spieler);
JPanel panel = new JPanel();
BoxLayout boxlayout = new BoxLayout(panel,BoxLayout.Y_AXIS);
panel.setLayout(boxlayout);
fenster.setTitle("Chomp");
fenster.setSize(1000,700);
panel.setPreferredSize(new Dimension(1000, 60));
Dimension d = new Dimension(getPreferredSize());
panel.setMinimumSize(d);
panel.add(spielfeld);
panel.add(anzeige);
fenster.add(panel);
this.spielfeld.setVisible(true);
this.anzeige.setVisible(true);
panel.setVisible(true);
fenster.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
A BoxLayout respects the width of the component to the label is displayed at its preferred width/height.
A JFrame uses a BorderLayout by default. So just add the label to the frame independently of the panel:
//panel.add(anzeige);
//fenster.add(panel);
fenster.add(panel, BorderLayout.CENTER);
fenster.add(anzeige, BorderLayout.PAGE_END);
The PAGE_END constraint respects the height but makes the width equal to the space available. Read the section from the Swing tutorial on How to Use BorderLayout for more information and examples.

Java JFrame setSize doesn`t work properly

I am making a JFrame with the size of 500x500 pixels.
I make a blue background and add a red square in the right-bottom corner from (490,490) to (500,500).
Image:
I don't see the red square on the screen.
I switched the frame from not resizable to resizable and if I make the window larger the red dot is there.
Is the frame size the same as application's window size?
How can I make the application's window to be the exactly 500x500?
Your content pane should override the getPreferredSize() method, returning a Dimension object with width and height of 500 pixels:
public class MyContentPane extends JPanel {
private Dimension dimension;
public MyContentPane() {
this.dimension = new Dimension(500, 500);
}
#Override
public Dimension getPreferredSize() {
return this.dimension;
}
}
// How to use your new class
SwingUtils.invokeLater(() -> {
JFrame frame = new JFrame("Title");
frame.setContentPane(new MyContentPane());
frame.pack();
frame.setVisible(true);
});
The size of your JFrame will be calculated by Swing by taking in consideration the preferred size of the components inside it.
The frame is the size of the entire window, including the title bar required by the OS. When drawing things in the JPanel in the JFrame, the (0, 0) coordinate is in the top left corner if the JPanel, which begins just below the title bar. It sounds like your title bar is taller than 10 pixels, so 490 as a y component is actually off the window, since the visible height of the JPanel is windowHeight - titleBarHeight.
Should user the following
#Override
PreferedSize()
Remember preferedSize method is method of the super class JFrame.
this may be useful for you?
JPanel aa = new JPanel(new GridBagLayout());
aa.setMaximumSize(new Dimension(500,500));
aa.setMinimumSize(new Dimension(490,490));
aa.setBorder(BorderFactory.createLineBorder(Color.black));

Java JPanel & JScrollPane

I working on a application that manage image's filters etc.
I want to have scroll bars when the image is to big to be display.
I put my customize panel that extend JPanel in a JScrollPane and I add it in my JFrame.
My image is displayed but not the whole image and the scroll bars are not there.
How to get the scroll-bars to appear?
Here is my code :
CustomePanel test = new ImagePanel(new File("test.jpg"));
test.setPreferredSize(new Dimension(400, 400));
JScrollPane tmp = new JScrollPane(test);
this.getContentPane().add(tmp);
It is likely that your initial preferred size does not match that of your Image. Rather than using setPreferredSize, override getPreferredSize to reflect the size of the image in ImagePanel:
#Override
public Dimension getPreferredSize() {
return new Dimension(image.getWidth(this), image.getHeight(this));
}
A JLabel would be a better approach here if the panel is not required as a container.
try to set the same preferred size to scroll pane as well and test it

JScrollPanes scrollbars not showing up

So, I have a grid layout which stores JScrollPane's in each cell. These are also put into an array for other purposes. The "View" extends "JPanel" so it's just a regular panel with image support. The application starts up with cell's filled with scrollPane's that contain the View which doesn't have a image yet.
At that point I see no scrollbar, but that doesn't matter since there is nothing inside the JPanel. As soon as I open an image and use drawImage in the paintComponenet of the JPanel I don't see scrollbar's showing up. Here's how I create the grid and the Scrollpane
private void createContentPane()
{
GridLayout gridLay = new GridLayout(GRID_ROWS, GRID_COLUMNS);
perspectiveTbl = new JScrollPane[NUM_PERSPECTIVE];
mainPane = new JPanel();
mainPane.setLayout(gridLay);
int idx = 0;
while(idx < perspectiveTbl.length)
{
perspectiveTbl[idx] = new JScrollPane(new View(modelImage));
mainPane.add(perspectiveTbl[idx]);
idx++;
}
this.getContentPane().add(mainPane, BorderLayout.CENTER);
}
I'm not exactly sure why the scrollbar's aren't showing up, should they have been set inside the panel for the image?
Here's an image of the application, as you can see the picture of the shoe does not receive scrollbar's so there is no way to view the rest of the picture:
Picture
You can either user not JPanel with image but usual JLabel with the image
or
call setPreferredSize() for the panels to reflect the image's size.
Thanks for the hint Stanislav, I actually figured it out and got it working an hour ago, but you did give the right path to fix it with the preferredSize attribute. I ended up re-implemented getPreferredSize with the size of the image inside the panel, added revalidate to the paint event so that the bars show up as soon as the image is loaded.
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
this.getViewScrollPane().revalidate();
}
public Dimension getPreferredSize()
{
if(image != null)
return new Dimension(image.getWidth(),image.getHeight());
else
return super.getPreferredSize();
}

java use size of JPanel to size components

Is it possible to use the size of a JPanel to set the size of components inside the JPanel? When I try to use getHeight() or getWidth() on the JPanel it always returns 0. I know that it gets it's size once the JFrame is packed, but how would one go about using the dimensions of the JPanel and applying it to a component inside it? Something like this
JPanel panel = new JPanel();
JLabel label = new JLabel();
label.setWidth(panel.getWidth());
panel.add(label);
EDIT:
See sample code below. What should I do if I want my Jlabel to be as wide as my JPanel? Is it wrong to use boxlayout in this case?
public class Main extends JFrame{
public Main(){
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.setBorder(BorderFactory.createLineBorder(Color.blue));
JLabel label = new JLabel();
label.setBorder(BorderFactory.createLineBorder(Color.red));
label.setText("label1");
label.setMinimumSize(panel.getPreferredSize());
label.setPreferredSize(panel.getPreferredSize());
panel.add(label);
add(panel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setSize(500,500);
setVisible(true);
}
public static void main(String[] args)
{
new Main();
}
}
Is it possible to use the size of a JPanel to set the size of components inside the JPanel?
This is the job of the layout manager.
When I try to use getHeight() or getWidth() on the JPanel it always returns 0
When the layout manager is invoked the Container will have a valid size so the layout manager can do its job properly.
There is no reason for you to be playing with sizes. Leave it to the layout managers to do their jobs.
Update:
What should I do if I want my Jlabel to be as wide as my JPanel? Is it wrong to use boxlayout in this case?
The BoxLayout attempts to respect the minimum/maximum size of the component. In you case you should be able to do something like:
JLabel label new JLabel("some text");
label.setBorder(....);
Dimension d = label.getPreferredSize();
d.width = 32767;
label.setMaximumSize( d );
Or maybe a simpler approach is to start with a BorderLayout. You can add the label to the NORTH. Then create another panel and add it to the CENTER.
Of course you can, but be careful that the result depends on the layout manager of your JPanel and on the number of its child components.
Setting the width ignores resizing. LayoutManagers typically ask components for their preferred widths and heights, and expand / contract items to maintain a visually appealing position after the frame has been resized. So, your best option is to leverage the layout manager and report a "preferred width".
You can use setPreferredWidth(...); but, if your preferred width is to change over the run of the program (due to window size changes), you will need to listen to the panel in question and update your button's preferred width as the panel's preferred width changes (this assumes it changes, which might not be true).

Categories

Resources