JLabel text Y paint coordinate - java

The default JLabel draws its text at the middle of its bounds. For example, if height of the label is 20, font height is 14, the Y coordinate would be (20 - 14)/2 = 3. Like this:
What should I do if want to align the text to the TOP of the JLabel bounds? Like this:
UPD:
public class LabelTest extends JFrame {
public LabelTest() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(500, 500);
setLocationRelativeTo(null);
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.X_AXIS));
contentPanel.add(Box.createHorizontalStrut(10));
final JLabel label1 = new JLabel("JLabel");
label1.setVerticalAlignment(SwingConstants.TOP); // by the answer of Kevin Workman, doesn't help
label1.setBorder(BorderFactory.createLineBorder(Color.RED));
label1.setFont(new Font("Arial", Font.PLAIN, 14));
contentPanel.add(label1);
setContentPane(contentPanel);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new LabelTest();
}
});
}
}

You should be packing the frame. If you so this, there should be no unused space in the label. If you want empty space, use an empty border
label.setBorder(new EmptyBorder(0, 0, 5, 0));
top, left, bottom, right
Also, don't set sizes, Use Layout Mangers and let them do the sizing for you. Setting sizes will give you. Setting sizes will give you a rigid look that may look and perform differently on different platforms. Layout Managers will allow your GUI to be more fluid and adaptable to different environments.
See Laying out Components Within a Container for more information on working with layouts
Also see Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

As always, the API is your best friend: http://docs.oracle.com/javase/7/docs/api/javax/swing/JLabel.html#setVerticalAlignment(int)
Edit- Based on your updated SSCCE, the problem is that your BoxLayout is shrinking the JLabel as small as it will go, so the vertical text position doesn't really matter. Try using a BorderLayout to check that.
The problem is that the insets of the JLabel are adding a small space to the top and bottom of the JLabel, so your text looks centered even though it's at the top. Here's a fix for the insets problem: How to change gap in swing label

Related

How to add image in Java Swing?

Help! How can I add image on my JFrame? This is my code
public class JavaApplication79 extends JFrame{
ImageIcon icon = new ImageIcon("Downloads/splash.jpg");
JLabel label = new JLabel(icon);
public JavaApplication79(){
add(label);
setLayout(null);
setSize(900,500);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]){
JavaApplication79 show = new JavaApplication79();
show.setVisible(true);
}
}
The problems start with the null layout. Because there is no layout to set the component size to it's preferred size, or any other size, the panel takes its default size of 0 x 0 pixels.
For 'top left' of frame I'd recommend FlowLayout.
For 'center' of frame - GridBagLayout is easy.
For 'centered & stretched' to fill the frame, GridLayout.
Learn about layouts in the Laying Out Components Within a Container lesson of the tutorial.
But an extra tip about combining layouts for different effects in different parts of the GUI. Use layout managers, or combinations of them along with layout padding and borders for white space.

Is there a way of moving JPanel in BorderLayout?

I am using a BorderLayout for the frame (the first one that "caught" my attention in the tuts) and a FlowLayout for the labels (the one I found appropriate for what I do), and the result shows up like this:
My objective is to push the "2*1" a little bit down, to sort of "center" it.
I looked around and found a lot of people saying to use a null layout, but then saying it's not the best alternative (even though my window is not resizable), and the other solution I found was using a combo of layouts (unless I misunderstood).
The question is the one on top of this, plus if not, what really is the best alternative? (The following is the code that makes this window (minus the vars and other methods, to simplify visualization).
public Frame() {
super("Jogo de Multiplicar!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setSize(300, 200);
setResizable(false);
getContentPane().setBackground(pink);
mensagem = new TransparentPanel();
operacao = new TransparentPanel();
//added stuff in mensagem and operacao
add(operacao);
add(mensagem, BorderLayout.SOUTH);
}
My objective is to push the "2*1" a little bit down, to sort of "center" it.
If you just want more space at the top then you can use a Border:
operacao.setBorder( new EmptyBorder(...) );
Read the section from the Swing tutorial on How to Use Borders for more information.
If you want to actually center it you can use a BoxLayout:
Box box = Box.createVerticalBox();
box.add( Box.createVerticalGlue() );
box.add( topPanel );
box.add( Box.createVerticalGlue() );
box.add( bottomPanel );
The tutorial also has a section on How to Use BoxLayout. Search the table of contents.
You could use MigLayout as your only LayoutManager. It's pretty mighty and usually offers everything that the other managers do too.
With this it's pretty simple to center the components:
public class MultiplyExample extends JFrame{
private static final long serialVersionUID = 1L;
JLabel testLabel = new JLabel("2*2 = 4");
public MultiplyExample(){
super("Example");
setBounds(300, 50, 200, 200);
// Set the MigLayout, so that columns and then rows get centered
setLayout(new MigLayout("center, center"));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(testLabel);
}
public static void main(String[] args) {
JFrame testFrame = new MultiplyExample();
testFrame.setVisible(true);
}
}
Result:
Here is a demo what the MigLayout has to offer:
http://www.miglayout.com/swingdemoapp.jnlp
Here is a quickstart-guide:
http://www.miglayout.com/QuickStart.pdf
If you have to use BorderLayout, you could put your components onto another panel and put this one into the center by using BorderLayout.CENTER:
pane.add(button, BorderLayout.CENTER);

Why does my JButton appear the full size of the JFrame?

I am a newbie, I have a question. I am trying to use Eclipse to write a Java windows application, in which I will have a main window, which will contain several things, like a dashboard sort of thing, and it will have buttons, for example to add a record to a database, and this button when pressed, will open a new relevant window on top.
I tried to start, I wrote this code in Java, and for some reason, the button is in the size of the frame...full screen ! How do I fix it ?
Can you suggest me better ideas for a design than what I specified ?
Thank you
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame jfrm = new JFrame("Frame1");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
jfrm.setSize(screenSize.width, screenSize.height);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel jlab = new JLabel("Hello");
jfrm.add(jlab);
JButton button = new JButton("Button");
button.setSize(new Dimension(50, 50));
button.setLocation(500, 350);
jfrm.getContentPane().add(button);
jfrm.setVisible(true);
}
Add a layout to the JFrame first. For example FlowLayout:
jfrm.setLayout(new FlowLayout());
"I tried to start, I wrote this code in Java, and for some reason, the button is in the size of the frame...full screen ! How do I fix it ?"
The reason the button stretches is because JFrame has a default BorderLayout that does not respect the preferred sizes of child components.
The solution is to set the Layout Manager to layout that does respect preferred sizes. The image blow from this example shows the most common Layout Managers and show visually which one respect the preferred size of child components.
Also, the BorderLayout is also the reason your JLabel does not show. By default, every component that is added to a BorderLayout without a position specified e.g. BorderLayout.SOUTH, will automatically be placed in the BorderLayout.CENTER position. Each position may only have one component. So when you add the JLabel it goes to the CENTER, but when you add the JButton, it also goes the CENTER, kicking out the JLabel.
If you've never encountered Layout Managers, this is probably all confusing to you. You should take the time to go over How to Layout Components Within a Container
You need to use some form of layoutmanager, you can use this information: http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
You must use Layout manager.
Use this code..
public static void main(String[] args)
{
JFrame jfrm = new JFrame("Frame1");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
jfrm.setSize(screenSize.width, screenSize.height);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel jlab = new JLabel("Hello");
jfrm.add(jlab);
JButton button = new JButton("Button");
button.setSize(new Dimension(50, 50));
button.setLocation(500, 350);
jfrm.add(button);
jfrm.setVisible(true);
jfrm.setLayout(new FlowLayout());
jfrm.pack();
you forgot to add pack(). so use this code to get Jlabel and JButtion side by side.
Thanks...

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).

Setting the size of panels

I have 3 panels. One is the main panel which holds 2 smaller panels.
For the main panel, I used
setPreferredSize(new Dimension(350, 190));
For the smaller left panel, I used
setPreferredSize(new Dimension(100, 190));
For the smaller right panel, I used
setPreferredSize(new Dimension(250, 190));
but the smaller panels remain the same size. How can I fix this?
This is the code I have in my main Panel.
import model.*;
import java.awt.*;
import javax.swing.*;
public class Panel extends JPanel
{
public Panel(Prison prison)
{
setup();
build(prison);
}
private void setup()
{
setBorder(BorderFactory.createLineBorder(Color.blue));
setLayout(new BorderLayout(1, 1));
setPreferredSize(new Dimension(350, 190));
}
private void build(Prison prison)
{
JTabbedPane tab = new JTabbedPane();
tab.addTab("Input", null, new InputPanel(), "Input");
tab.addTab("Display", null, new DisplayPanel(), "Display");
add(tab);
}
}
Don't do this.
The whole point of layout managers is to allow dynamic resizing, which is necessary not just for user-resizable windows but also changing texts (internationalization) and different default font sizes and fonts.
If you just use the layout managers correctly, they will take care of panel sizes. To avoid having your components stretched out all over the screen when the user increases the window size, have an outermost panel with a left-aligned FlowLayout and the rest of the UI as its single child - that will give the UI its preferred size and any surplus is filled with the background color.
It looks like you're using a GridLayout, or perhaps a FlowLayout, neither being what you want. You probably want to use a BoxLayout, which respects its components preferred sizes.
final JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.add(leftPanel);
p.add(mainPanel);
p.add(rightPanel);
also- that is the preferred size. if you don't want to allow resizing, you can also set the maximum sizes as well.
if you're able, you may want to check out the MIG layout, but BoxLayout is also easy to use and in the java toolkit already.
It's this one.
buttonPanel = new JPanel();
buttonPanel.setSize(new Dimension(30, 100));
Don't let the layout manager adjust your sizes.

Categories

Resources