Show the hidden JFrame - java

When I run my JFrame it shows me in hidden size. I have to resize to see JFrame.
Why I cannot get fully sized JFrame.
I used: Pack(); setVisible(true); but it doesn't work.
Here is my code:
public class Mytest extends JFrame{
JLabel label=new JLabel();
JLabel label2=new JLabel();
Timer myTimer;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new Mytest().show();
}
public Mytest(){
getContentPane().setLayout(new GridBagLayout());
setTitle("test");
GridBagConstraints gridCon=new GridBagConstraints();
gridCon.gridx=0;
gridCon.gridy=0;
getContentPane().add(label,gridCon);
gridCon.gridx=0;
gridCon.gridy=1;
getContentPane().add(label2,gridCon);
myTimer = new Timer(1000,new ActionListener(){
public void actionPerformed(ActionEvent e){
myTimerActionPerformed(e);
}
});
pack();
myTimer.start();
setLocationRelativeTo(null);
}
private void myTimerActionPerformed(ActionEvent e){
Date today=new Date();
label.setText(DateFormat.getDateInstance(DateFormat.FULL).format(today));
label2.setText(DateFormat.getTimeInstance().format(today));
}
}

There are two basic problems...
The first is, when you create and add your JLabels, they have no content, therefore their preferred size is 0x0...
The second is the use of pack, from the JavaDocs
Causes this Window to be sized to fit the preferred size and layouts
of its subcomponents. The resulting width and height of the window are
automatically enlarged if either of dimensions is less than the
minimum size as specified by the previous call to the setMinimumSize
method. If the window and/or its owner are not displayable
yet, both of them are made displayable before calculating the
preferred size. The Window is validated after its size is being
calculated.
So, basically, you are adding two labels, whose total combined size is 0x0 and pack is doing exactly what it was designed to, packing the frame to meet the requirements of the layout manager.
You need to seed the values of the labels before you call pack, for example, add a method that updates the labels, for example...
public void updateLabels() {
Date today = new Date();
label.setText(DateFormat.getDateInstance(DateFormat.FULL).format(today));
label2.setText(DateFormat.getTimeInstance().format(today));
}
Then in your constructor, before you call pack, call this method...
updateLabels();
pack();
myTimer.start();
setLocationRelativeTo(null);
(You should also call this updateLabels method from the Timers actionPerformed method to keep it consistent).
This will seed the labels with some content, which pack and the layout manager can use to determine size of the window...
You should also use setVisible over show as show is deprecated and may be removed at some time in the future

You can maximize frame like this :
setExtendedState(JFrame.MAXIMIZED_BOTH);
or you can size frame as per your requirement like
setSize(500,500);
and you have to add below statement as i cant see this in your code
setVisible(true);

Related

Aligning JTextFields, JLabels, and JButtons in a JPanel [duplicate]

I have the following code where I try to place a JLabel in a custom location on a JFrame.
public class GUI extends JFrame
{
/**
*
* #param args
*/
public static void main(String args[])
{
new GUI();
}
/**
*
*/
public GUI()
{
JLabel addLbl = new JLabel("Add: ");
add(addLbl);
addLbl.setLocation(200, 300);
this.setSize(400, 400);
// pack();
setVisible(true);
}
}
It doesn't seem to be moving to where I want it.
The problem is that the LayoutManager of the panel is setting the location of the label for you.
What you need to do is set the layout to null:
public GUI() {
setLayout(null);
}
This will make it so the frame does not try to layout the components by itself.
Then call setBounds(Rectangle) on the label. Like so:
addLbl.setBounds(new Rectangle(new Point(200, 300), addLbl.getPreferredSize()));
This should place the component where you want it.
However, if you don't have a really great reason to lay out the components by yourself, it's usually a better idea to use LayoutManagers to work in your favor.
Here is a great tutorial on getting started with using LayoutManagers.
If you must go without a LayoutManager here is a good tutorial for going without one.
You put the location code under the frame and it will work but if you want it to work for sure
put the location code in a run while loop. That's what I did to figure it out and it works.

textfield not shown with proper size

I am new to Java and am trying to run this code. What could be error in the following code—my JTextField, txtfld, is shown just as a line instead of as a full text box?
public class calculator
{
public static void main(String s[])
{
JFrame j=new JFrame();
j.setSize(400,600);
JPanel p1=new JPanel();
JPanel p2=new JPanel();
p1.setSize(400, 100);
p2.setSize(400, 500);
p1.setLocation(0, 0);
p2.setLocation(0, 100);
p2.setLayout(new GridLayout(4,4));
j.add(p1);
j.add(p2);
JTextField txtfld=new JTextField();
txtfld.setSize(390, 92);
txtfld.setLocation(5, 2);
//txtfld.setVisible(true);
p1.add(txtfld);
j.setVisible(true);
}
}
JTextField txtfld=new JTextField();
You need to give a hint to the layout manager what the size should be.
So you should use something like:
JTextField txtfld=new JTextField(10);
Now the preferred size will be such that 10 "W" characters can be displayed in the text field before scrolling is required.
You should also pack() the frame before making it visible:
j.pack();
j.setVisible();
This will allow the frame to display all the components at their preferred sizes.
Also, get rid of all the setSize() and setLocation() statements. It is the job of the layout manager to set the size and location. Those values will be recalculated by the layout manager.
j.add(p1);
j.add(p2);
The default layout manager for a frame is a BorderLayout. So the above code will cause p2 to replace p1 on the frame.
Basically your entire code is wrong.
Start by reading the section from the Swing tutorial on How to Use Layout Managers for more information and working examples to get you started. Maybe start with the BorderLayout example, since this is the default layout of the frame you need to understand how it works first.

How to adjust parent container size by the child container?

More specifically, how to adjust JFrame size by its contentPane.
Here is the case, I am doing a 400*400 JPanel and I need it to fit in the JFrame. However if I set JFrame setSize(400, 400), some part of the JPanel would be hid due to the space occupied by the upper windows title bar.
I know I can just measure the border and the size of the title bar. I just want to know if there is better way to do.
Here is the solution that takes both Hovercraft Full Of Eels and MadProgrammer answer.
public class Window extends JFrame {
private Window() {
createUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Window();
}
});
}
private void createUI() {
setContentPane(buildMainPanel());
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
private JPanel buildMainPanel() {
JPanel mainPanel = new JPanel();
mainPanel.setPreferredSize(new Dimension(500, 640));
mainPanel.setLayout(null);
mainPanel.add(new Canvas(0, 0));
return mainPanel;
}
}
However if I set JFrame setSize(400, 400), some part of the JPanel would be hid due to the space occupied by the upper windows title bar.
You're making things too hard for yourself since the easiest solution is to simply not set the JFrame size. Instead call pack() on the JFrame after adding all components and before calling setVisible(true) and let it size itself to the optimum size for its components and layout managers.
Override the panel's getPreferredSize method and return new Dimension(400, 400).
On the frame call pack. When called, pack will ask the content pane for it's preferred size, which is normally calculated by the layout manager (recursively ask each container for it's preferred size).
This will size the window so that's viewable area meets (as much as its possible to do so) the preferred size of it's content.

set size of JPanel

i' m programming an application which works with swing components, i notice one thing on which i would an explanation
i have these classes:
this enum on which i instantiate the gui dimension
public enum GuiDimension {
WIDTH(700), HEIGHT(400);
private final int value;
private GuiDimension(int value) {
this.value = value;
}
public int getValue(){
return value;
}
}
this class that starts the application
private GamePanel gamePanel = new GamePanel();
public static void main(String[] args) {
new MainFrame();
}
public MainFrame() {
initGameFrame();
}
private void initGameFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(gamePanel);
setResizable(false);
setUndecorated(true);
pack();
setVisible(true);
setLocationRelativeTo(null);
}
}
and this class that set the size of the panel
public class GamePanel extends JPanel {
public GamePanel() {
setPreferredSize(new Dimension(GuiDimension.WIDTH.getValue(),GuiDimension.HEIGHT.getValue()));
//it makes other stuff that are not of interest for this contest
}
}
What I noticed is that, it is true that enums are not really integers but objects ,but when I return
GuiDimension.WIDTH.getValue()
GuiDimension.HEIGHT.getValue()
they return integers that can well be used for other purposes once it has been taken.
now if I insert this on:
SetSize (new Dimension (GuiDimension.WIDTH.getValue (), GuiDimension.HEIGHT.getValue ()));
or
SetSize (GuiDimension.WIDTH.getValue (), GuiDimension.HEIGHT.getValue ());
instead of this,which i inserted in the example
setPreferredSize(new Dimension(GuiDimension.WIDTH.getValue(),GuiDimension.HEIGHT.getValue()));
the frame is displayed with wrong dimension, and I do not understand why.
If GuiDimension.WIDTH.getValue () and GuiDimension.WIDTH.getValue ()) are correct for setPreferredSize (...),
why is not the same for setSize (int,int) and for setSize(Dimension) ?
when tested this simple code you can see that.
Most of the layout managers will ignore calls a component's size but will respect its preferredSize, and sometimes the minimum and maximum, and so when you call pack(), your size will change to what the layout managers and the constituent component preferred sizes think should be the best size.
Incidentally, per kleopatra (Jeanette), if you absolutely need to set a component's preferred size, you're better off overriding getPreferredSize() than by calling setPreferredSize(...). The latter can be overridden by calling setPreferredSize(...) on the same component elsewhere while the former can't.
As an aside, in your example code, you are using WIDTH twice and appear to be not using HEIGHT.
Edit
You had a comment that was deleted regarding pack and component sizes. My reply to it was:
The pack() method requests that the layout managers do their laying out of components, and its the layout managers that matter here -- what do they look at, the size vs. the preferredSizes. If you read the javadoc and tutorials for most of the layout managers, you'll see that they respect the preferred sizes most. Some, like BoxLayout, also look at the maximum size and minimum size as well.

Trying to add a JLabel, but it is stuck in the middle of Jframe

I am trying to add a JLabel but the problem is that it is eith stuck in the middle or to the left of the jframe.
Here is my code;
public class test extends JFrame{
public test(){
JLabel text = new JLabel("test")
text.setLocation(100,100);
setTitle("Help me");
setSize(500,500);
add(text);
}
}
public class Runner{
public static void main (String[] args){
test a = new test();
}
}
Every container has a layout manager that set the position and size of the elements it contains according to its own rules. JFrame default layout is BorderLayout, which put things by default on the left.
To position components absolutely, you have to set the layout manager to null and explicitely call repaint() on your JFrame every time you add/remove/modify your components. You also have to set the size of the components, not only their position (use for example setBounds to set them all in one call.
As an example, The following code does what you want:
public class Test extends JFrame {
public Test() {
// remove any layout manager.
setLayout(null);
setTitle("Help me");
setSize(500, 500);
JLabel text = new JLabel("test");
// set size and position of component.
text.setBounds(new Rectangle(100, 100, 200, 200));
// add component.
add(text);
// explicitely call repaint().
repaint();
}
public static void main(String[] args) {
new Test().setVisible(true);
}
}
For more informations, you can look at the Oracle tutorial on working without a layout manager.
Edit: I would still advise you to use normal layout managers to achieve what you want, as positioning everything absolutely is usually a pain.
add(text);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);

Categories