Java SWING: How to fix size of components in GridLayout - java

I am creating a simple Window in GridLayout and here is my code:
package com.company.app;
import javax.swing.*;
import java.awt.*;
public class SpamGUI {
public static void main(String[] args) {
System.out.println("Loading Program..");
JFrame frame = new JFrame("My awesome Program");
frame.setVisible(true);
frame.setSize(800, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 3));
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
JLabel lblTrainPath = new JLabel("Enter Training Folder Path");
lblTrainPath.setSize(100,10);
panel.add(lblTrainPath);
JTextField txtTrainPath = new JTextField();
txtTrainPath.setSize(100,10);
panel.add(txtTrainPath);
JButton btnTrainPath = new JButton("Select");
panel.add(btnTrainPath);
JLabel lblTrainPath3 = new JLabel("Enter Training3 Folder Path");
panel.add(lblTrainPath3);
JTextField txtTestPath = new JTextField();
panel.add(txtTestPath);
JButton btnTestPath = new JButton("Select");
panel.add(btnTestPath);
frame.add(panel);
}
}
It generates screen like this:
As you can see,it is not respecting size of components, showing quite broad on screens. Also when I run program from INtelliJ IDEA, it does not render components unless I resize screen.
I also want a fixed size window having component with custom size.
Please guide

The Font class allows you to specify font size.
So, to create a font you should code like this:
Font f = new Font("serif", Font.PLAIN, fontSize);
The fontSize parameter will determine the size of the Font
So, here enter font size you want ..after that set that font instance variable f to your JLabel instance variable like this:
lblTrainPath.setFont(f);
and for having component with custom size.
you should try pack() instead of frame.setSize(800,200)
and use this pack() after adding all the components to your frame and for fixed size window use setResizable(false)...

Related

Java GUI shows blank until resize

I have written a java gui code for many options available on it. the gui is also set visible true but it doesn't show until I pick its border and drag them to resize the gui window. After manually resizing it, it shows everything. Also, the textlabels and the textfields and buttons are not in new lines, they are placed one after one. Please tell me whats wrong with that: here is a part of code:
public static void initGUI(){
JFrame fr = new JFrame();
Container cont = fr.getContentPane();
cont.setLayout( new FlowLayout( ) );
FlowLayout layout = new FlowLayout();
cont.setLayout(layout);
frame.setSize(200,300) ;
frame.setVisible(true) ;
JTextField tName = new JTextField(30);
JTextField tCNIC = new JTextField(15);
JLabel nameLabel = new JLabel("Name:");
JLabel cnicLabel = new JLabel("CNIC #:");
cont.add(nameLabel);
cont.add(tName);
cont.add(cnicLabel);
cont.add(tCNIC);
JButton Cancel = new JButton ("Canel" );
JButton OK = new JButton ("OK" );
savebtn.setPreferredSize(new Dimension(150, 50));
retbtn.setPreferredSize(new Dimension(150, 50));
cont.add(savebtn);
cont.add(retbtn);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
frame.setVisible(true) ;
The above statement should be invoked AFTER all the components have been added to the frame. So it should be the last statement in your method.
Also, you should be invoking:
frame.pack();
instead of setSize(), before making the frame visible so all the components are displayed at their preferred size.
frame.setVisible(true);
This Statement should be invoked in the last of adding other components to the Frame.

JLabel not showing up on JPanel

For some reason even though I have implemented the validate method in my code, and added my JPanel to my JFrame. I am also trying to get my JLabel to have Comic Sans font and for it to be centered in the screen. Why is my JLabel not showing up on my JPane
package math_program;
import java.awt.Color;
import java.awt.Font;
import java.util.Random;
import javax.swing.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class Canvas
{
Images obj = new Images();
public void paintFrame()
{
//Instantiation of objects
Random gen = new Random();
JFrame frame = new JFrame();
JPanel panel = new JPanel();
//Text
JLabel problem = new JLabel();
frame.setVisible(true);
frame.setAlwaysOnTop(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE); //Make frame actually closeable
frame.setTitle("Math Owl: Alpha V:0.1 (coded by John)");
frame.setSize(800, 500);
frame.setLocationRelativeTo(null);
frame.add(panel); //Add JPanel to JFrame
panel.setVisible(true);
panel.setLayout(null);
panel.setBackground(Color.WHITE); //To see if text is even appearing
//Adding Components
problem.setFont(new Font("Comic Sans MS", Font.PLAIN, 20));
problem.setLocation(400,250);
problem.setText(gen.nextInt(11) + " + " + gen.nextInt(11));
panel.add(problem);
panel.validate();
}
}
Use a proper Layout Manager just as copeg said. Even the default Layout Manager (Flow Layout) will work. Just remove panel.setLayout(null); and your JLabel will show up.
Also when I try your snippet code there also problem on Images obj = new Images(); I assume you already have the Images class defined in your package somehow.
`
//frame.add(panel);
frame.setContentPane(panel);
//panel.setVisible(true); // not necessary code
//panel.setLayout(null); // not necessary code
panel.setBackground(Color.WHITE); //To see if text is even appearing
frame.getContentPane().add(problem);
The problem is that with null layout, you have to set both the location and the size of each component. You set only the location of the label, so you can fix it with problem.setSize(x, y);. With that being said, it's just wrong to take this approach. See what your whole GUI design for this frame looks like and choose an appropriate LayoutManager.
Try this:
public class MyCanvas {
public MyCanvas() {
Random gen = new Random();
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JLabel problem = new JLabel();
panel.setBackground(Color.WHITE);
problem.setFont(new Font("Comic Sans MS", Font.PLAIN, 20));
problem.setText(gen.nextInt(11) + " + " + gen.nextInt(11));
panel.add(problem); // Default FlowLayout
frame.add(panel); // Default BorderLayout at position CENTER
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Math Owl: Alpha V:0.1 (coded by John)");
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
new MyCanvas();
}
}
Notes:
frame.setVisible(true) should be the last call you make.
frame.setAlwaysOnTop(true) and frame.setResizable(false) are things you usually want to avoid from the user's perspective.
frame.setSize(...) should be replace with frame.pack().
frame.setLocationRelativeTo(null) should be called between pack() and setVisible(true).
No need for panel.setVisible(true), it does nothing for you.
No need for panel.validate() (should be revalidate()), it is only needed when changing the layout during runtime.
The class Canvas already exists, use a different name.
There two way
is you are using any layout manager then you can simply show the component by using setSize(new Dimension(width, height)
if you have set the layout manager to null then you must use
setBounds(x,y, width, height) (if you do this obviously no need to set size) to show the component
otherwise just do
setSize(new Dimension(width,height)
then setLocation(x,y)
if you want to dynamically calculate the position then you can set the initial locaion as setLocation(0,0)
afterwards when all the components are showing you can use your algorithm to recalculate x and y position and again setLocation(x,y)
for e.g.
label1=setSize(new Dimension(100,20)
label1.setLocation(0,0)
Label2=setSize(new Dimension(100,20)
Label2.setLocation((int)label1.getSize().getWidth()+10,20) and so on

remove image in Jlabel in java

I have a question and I know it may seem simple but I spent 3 hours and still I am having trouble:
I am trying to add and remove image in Jlabel in java dynamically I am trying this code but I cant see any image loding on label what is wrong with my code and what can I do else?
public static void main (String[] args)
{
ImageIcon icon = new ImageIcon ("1.gif");
JFrame frame = new JFrame ("Nested Panels");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
// Set up first subpanel
JPanel subPanel1 = new JPanel();
subPanel1.setPreferredSize (new Dimension(450, 100));
//subPanel1.setBackground (Color.green);
JLabel label1 ;
label1 = new JLabel ("Devil Left", icon, SwingConstants.CENTER);
label1.setHorizontalTextPosition (SwingConstants.LEFT);
label1.setVerticalTextPosition (SwingConstants.BOTTOM);
subPanel1.add (label1);
JPanel primary = new JPanel();
primary.setBackground (Color.blue);
primary.add (subPanel1);
frame.getContentPane().add(primary);
frame.pack();
frame.setVisible(true);
}
ImageIcon(String) assumes that the value is a File.
If the image is stored within the context of the Jar (or project if you're using NetBeans), then you will need to access the image via Java's resource management API, for example.
ImageIcon icon = new ImageIcon (YourProject.class.getResource("1.gif"));
If you're using Eclipse, the resource will need to be stored within the projects resource folder.

Swing: Showing a transparent Panel hovering over another Panel

I want to show a textArea showing some text (will show log lines) , and have an animated gif hoovering above it. I tried the solution described here , but all I get is a grey screen. Hints?
public class TestLayeredPanes {
private JFrame frame = new JFrame();
private JLayeredPane lpane = new JLayeredPane();
public TestLayeredPanes() {
frame.setPreferredSize(new Dimension(600, 400));
frame.setLayout(new BorderLayout());
frame.add(lpane, BorderLayout.CENTER);
//Build the animated icon
JLabel buildingIcon = new JLabel();
buildingIcon.setIcon(new ImageIcon(this.getClass().getResource(
"/com/ct/tasks/cmviewer/gui/progress_bar.gif")));
JPanel iconPanel = new JPanel();
iconPanel.add(buildingIcon);
//Build the textArea
JTextArea textLog = new JTextArea("Say something");
JPanel textPanel = new JPanel();
textPanel.add(new JScrollPane(textLog));
//Add the panels to the layered pane
lpane.add(textPanel, 0);
lpane.add(iconPanel, 1);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new TestLayeredPanes();
}
}
Try putting your animated GIF on the glass pane of your root pane:
http://download.oracle.com/javase/tutorial/uiswing/components/rootpane.html
JXLayer make easier to do that. Look at JXLayer samples.
You also can take a look at code of XSwingX
Since you started with a working example, why did you remove lines of code from the example you copied?
Layered panes don't use a layout manager therefore the size of your components are (0, 0), so there is nothing to display. The setBounds(...) method in the example are there for a reason.

Addin a JLabel in a frame?

I have created a JFrame, and now I want to add a JLabel and textfields in it. Please tell me how to do that. I have used the following code but its not working.
JFrame i_frame = new JFrame("Select Locations");
i_from = new JLabel("From");
i_frame.getContentPane().add(i_from);
i_frame.add(Box.createRigidArea(new Dimension(2,0)));
i_frame.setLocationRelativeTo(null);
i_frame.setSize(200,200);
i_frame.setVisible(true);
Problem is this code is showing frame window but it is not showing label in it. Please help.
That's your first question, later you'll ask:
How do I get the value from my text field
So, I suggest you to take a look at this tutorial
http://java.sun.com/docs/books/tutorial/uiswing/start/index.html
And ask us if you have questions from that tutorial. Using an IDE will simplify your life.
Here's a start anyway:
Code:
import javax.swing.*;
import java.awt.Color;
public class MyApp {
public static void main( String [] args ) {
JFrame frame = new JFrame();
frame.setBackground( new Color(0,0,0,64 ));
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
JPanel top = new JPanel();
top.add( new JLabel("What is your name"){{
setForeground(Color.white);
}});
top.add( new JTextField(10) );
frame.add( top );
frame.pack();
frame.setVisible( true );
}
}
EDIT
Dismiss this answer. It was posted when the question was rather ambiguous. I'm leaving it as CW for it may be helpful.
plus OSX frames with alpha background are too cool!
The main issue is the layout being used by the content pane (most likely JRootPane.RootLayout, A custom layout manager that is responsible for the layout of layeredPane, glassPane, and menuBar ) is not the best. This code should work;
JFrame i_frame = new JFrame("Select Locations");
JLabel i_from = new JLabel("From");
i_frame.getContentPane().setLayout(new FlowLayout());
i_frame.getContentPane().add(i_from);
i_frame.add(Box.createRigidArea(new Dimension(2,0)));
i_frame.setLocationRelativeTo(null);
i_frame.setSize(200,200);
i_frame.setVisible(true);
setting a different layout does the trick
The problem is that you are adding a second component (Box.createRigidArea) in the same layout position (BorderLayout.CENTER) as the Label.
JFrame.add() results in the same as JFrame.getContentPane().add()...
So the label is being replaced by the RigidArea.
Try this:
JFrame i_frame = new JFrame("Select Locations");
i_from = new JLabel("From");
i_frame.getContentPane().add(i_from);
// i_frame.add(Box.createRigidArea(new Dimension(2,0)));
i_frame.setLocationRelativeTo(null);
i_frame.setSize(200,200);
i_frame.setVisible(true);
to add more components, change the LayoutManager:
JFrame i_frame = new JFrame("Select Locations");
JLabel i_from = new JLabel("From");
Container pane = i_frame.getContentPane();
pane.setLayout(new BoxLayout(pane, BoxLayout.X_AXIS)); // any LayoutManager you need
pane.add(i_from);
pane.add(Box.createRigidArea(new Dimension(2,0))); // space after JLabel ?
i_frame.setSize(200,200); // better done before setLocationRelativeTo
i_frame.setLocationRelativeTo(null);
i_frame.setVisible(true);
Note: if you "just" want to add an empty border to your label, use a setBorder() instead of the RigidArea:
i_from.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
[]]
For adding JLabel to JFrame see the line of code see here
public class JLabelExample extends JFrame {
JLabel jLabel;
public JLabelExample() {
jLabel = new JLabel();
jLabel.setText("tutorialData.com");
jLabel.setForeground(Color.BLUE);
this.add(jLabel);
}
public static void main(String a[]) {
JLabelExample labelExample = new JLabelExample();
labelExample.setSize(250, 200);
labelExample.setTitle("tutorialData.com");
labelExample.setVisible(true);
}
}
Please refer more on JFrame

Categories