Java help: JLabel's - java

I created this program that displays 2 photos and some facts (JLabel) about myself. However, the facts about myself are to the right of the pages. I would like the facts (JLabels) to be right under the pictures stacked, like a title and bullet points under the title, any help?
Ignore the import for sound. Eventually, I want the program to play a tune.
import java.awt.*;
import sun.audio.*;
import javax.swing.*;
public class AudioandImage extends JFrame {
public ImageIcon image1;
public JLabel label1;
public ImageIcon image2;
public JLabel label2;
public JLabel name;
public JLabel facts;
public JLabel born;
public JLabel es;
public JLabel sport;
public JLabel lastly;
AudioandImage() {
setLayout (new FlowLayout());
image1 = new ImageIcon(getClass().getResource("losangeles.jpg"));
label1 = new JLabel(image1);
add(label1);
image2 = new ImageIcon(getClass().getResource("elsalvador.jpg"));
label2 = new JLabel(image2);
add(label2);
name = new JLabel("My name is Erik Landaverde");
add(name);
facts = new JLabel("Some facts about myself:");
add(facts);
born = new JLabel("I was born and raised in South Central Los Angeles");
add(born);
es = new JLabel("Have a Salvadorean background");
add(es);
sport = new JLabel("My favorite sport is soccer");
add(sport);
lastly = new JLabel("Lastly... I am a programmer!");
add(lastly);
}
public static void main(String[] args) {
AudioandImage gui = new AudioandImage();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.pack();
gui.setTitle("A Little About Myself");
}
}

The desired result can be accomplished by assigning a different layout to your JFrame to FlowLayout() BorderLayout for example,
setLayout (new BorderLayout()); // asign layout to JFrame
add(label1,BorderLayout.PAGE_START); //Add JLabel 1 to Jframe
add(label2,BorderLayout.CENTER); //Add JLabel 2 to Jframe
name = new JLabel("<html><ul>My name is : Erik Landaverde "
+ "<li/>Some facts about myself: </li> "
+ "<li/>I was born and raised in South Central Los Angeles</li>"
+ "<li/>Have a Salvadorean background</li>"
+ "<li/>My favorite sport is soccer</li>"
+ "<li/>Lastly... I am a programmer!</li></ul></html>", SwingConstants.CENTER);
add(name,BorderLayout.PAGE_END); //Add JLabel 3 to Jframe
for the label in March added it into one because only contained what I
format strings with <html> </html> and line with <ul><li>content</li></ul>

Flow layout is not suited for the way you want to display the labels. See https://docs.oracle.com/javase/tutorial/uiswing/layout/flow.html for tutorial on flow layout.
You can also find tutorial to BorderLayout from above link. You could use this layout here. Create a JPanel with your labels using GridLayout with 1 column. Then place it in CENTER or SOUTH of the JFrame using BroderLayout.
Another approach could be to write your text as a single HTML and set it in JTextPane etc.

Use Below code for GridBagLayout
Test() {
setLayout(new GridBagLayout());
image1 = new ImageIcon(getClass().getClassLoader().getResource("image.jpg"));
label1 = new JLabel(image1);
add(label1, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
name = new JLabel("My name is Erik Landaverde");
add(name, new GridBagConstraints(0, 2, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
facts = new JLabel("Some facts about myself:");
add(facts, new GridBagConstraints(0, 3, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
born = new JLabel("I was born and raised in South Central Los Angeles");
add(born, new GridBagConstraints(0, 4, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
es = new JLabel("Have a Salvadorean background");
add(es, new GridBagConstraints(0, 5, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
sport = new JLabel("My favorite sport is soccer");
add(sport, new GridBagConstraints(0, 6, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
lastly = new JLabel("Lastly... I am a programmer!");
add(lastly, new GridBagConstraints(0, 7, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
}
public static void main(String[] args) {
Test gui = new Test();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.pack();
gui.setTitle("A Little About Myself");
}

Related

setting componenets by using GridBagLayout

I am using GridBagLayout to locate components on panel but it is not working like it has to be. Location of components is not affecting by changing x and y values somebody please help explain what mistake i am making here Thanks in advance :)
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;
public class LMS extends JFrame {
JPanel mainPanel;
JLabel RegNum, Name, FatherNam, MotherNam, DateBirth, BloodGrp, Email, Gender, RegDate, Desig, photo;
JTextField RegNuumText, FatherNamText, MotherNamText, EmailText, DesigText;
JList BloodGrpList;
JSpinner DateSpi;
// Constructor
public LMS() {
this.setTitle("Library Managment System");
this.setVisible(true);
this.setSize(700, 600);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
// this.setResizable(false);
mainPanel = new JPanel();
// GridBagLayout bag = new GridBagLayout();
mainPanel.setLayout(new GridBagLayout());
// Creating Labels
RegNum = new JLabel("Registration Number");
Name = new JLabel("Full Name");
FatherNam = new JLabel("Father's Name");
MotherNam = new JLabel("Mother's Name");
DateBirth = new JLabel("Date Of Birth");
BloodGrp = new JLabel("Blood Group");
Email = new JLabel("Email");
Gender = new JLabel("Gender");
RegDate = new JLabel("Registration Date");
Desig = new JLabel("Designation");
photo = new JLabel("Photo");
// creating Text Fields
RegNuumText = new JTextField(30);
FatherNamText = new JTextField();
MotherNamText = new JTextField();
EmailText = new JTextField();
DesigText = new JTextField();
// mainPanel.add(RegNum);
addComp(mainPanel, RegNum, 0, 0, 2, 1, GridBagConstraints.EAST, GridBagConstraints.NONE);
addComp(mainPanel, RegNuumText, 0, 1, 2, 1, GridBagConstraints.WEST, GridBagConstraints.NONE);
this.add(mainPanel);
}
private void addComp(JPanel thePanel, JComponent comp, int xPos,
int yPos, int compWidth, int compHeight, int place, int stretch) {
GridBagConstraints gridConstraints = new GridBagConstraints();
gridConstraints.gridx = xPos;
gridConstraints.gridy = yPos;
gridConstraints.gridwidth = compWidth;
gridConstraints.gridheight = compHeight;
gridConstraints.weightx = 1;
gridConstraints.weighty = 1;
gridConstraints.insets = new Insets(5, 5, 5, 5);
gridConstraints.anchor = place;
gridConstraints.fill = stretch;
thePanel.add(comp, gridConstraints);
}
public static void main(String[] args) {
new LMS();
}
}
GridBagLayout is not the easiest one, you have to play a little with it. Maybe these lines help you to achieve what you wanted. They will put the label in the upper left corner and the Textfield right behind it.
Note, that there are panels defined as place holders - they will fill the empty space.
addComp(mainPanel, RegNum, 0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE);
addComp(mainPanel, RegNuumText, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE);
addComp(mainPanel, new JPanel(), 2, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL);
addComp(mainPanel, new JPanel(), 0, 2, 1, 1, GridBagConstraints.WEST, GridBagConstraints.VERTICAL);
You also need to change your helper method a little:
gridConstraints.weightx = stretch == GridBagConstraints.NONE || stretch == GridBagConstraints.VERTICAL ? 0 : 1;
gridConstraints.weighty = stretch == GridBagConstraints.NONE || stretch == GridBagConstraints.HORIZONTAL ? 0 : 1;
I think this should do the trick. Maybe you should define two or three helper methods, so you don't need to set all parameters every time. From my experience, very rarely you will need to define the anchor and only some times you might want to stretch components. Most of the time, for me, it is just puting stuff into the right bags (x, y, sometimes: width, height).
Edit: maybe it would help to put setVisible() at the end of the definition, not the beginning.

Java : divide the screen

I try to do a simple swing window, but with the layout it's not easy...
I mean I just want a window with 3 panels :
header with 20% of window in height
content with 60% of window in height
footer with 20% of window in height
But I can't succeed to have what I want. I used a gridLayout(3,1) but I can't specify the height.
public class Window extends JFrame implements Serializable {
private JPanel _header;
private JPanel _content;
private JPanel _footer;
public Window() {
GridLayout grid = new GridLayout(3,1);
setLayout(grid);
_header = new JPanel();
_header.setBackground(Color.GRAY);
getContentPane().add(_header);
_content = new JPanel();
JScrollPane jsp = new JScrollPane(_content, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
getContentPane().add(jsp);
_footer = new JPanel();
_footer.setBackground(Color.GRAY);
getContentPane().add(_footer);
pack();
validate();
setTitle("Chat client");
setVisible(true);
setSize(500, 500);
setLocationRelativeTo(null);
}
Can you help me ?
Best regards
GridBagLayout is capable of dividing vertical or horizontal space proportionally.
Here's an example that displays a red JPanel in the top 20% of a window, a green JPanel in the middle 60%, and a blue JPanel in the bottom 20%:
JFrame window = new JFrame();
window.setLayout(new GridBagLayout());
JPanel top = new JPanel(), middle = new JPanel(), bottom = new JPanel();
top.setBackground(Color.red);
middle.setBackground(Color.green);
bottom.setBackground(Color.blue);
GridBagConstraints c = new GridBagConstraints();
// we want the layout to stretch the components in both directions
c.fill = GridBagConstraints.BOTH;
// if the total X weight is 0, then it won't stretch horizontally.
// It doesn't matter what the weight actually is, as long as it's not 0,
// because the grid is only one component wide
c.weightx = 1;
// Vertical space is divided in proportion to the Y weights of the components
c.weighty = 0.2;
c.gridy = 0;
window.add(top, c);
// It's fine to reuse the constraints object; add makes a copy.
c.weighty = 0.6;
c.gridy = 1;
window.add(middle, c);
c.weighty = 0.2;
c.gridy = 2;
window.add(bottom, c);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
Result:
GridLayout always spaces evenly. You could instead use GridBagLayout, the most evil of all the Java layout managers. I've given them "weights" of 20, 60, 20 so you can see which values are which. You can just as easily use 2, 6, 2, it doesn't matter it's just a ratio. Look at the GridBagLayout tutorial for more info.
Example
public class Window extends JFrame implements Serializable {
private JPanel _header;
private JPanel _content;
private JPanel _footer;
public Window() {
GridBagLayout grid = new GridBagLayout();
setLayout(grid);
_header = new JPanel();
_header.setBackground(Color.GRAY);
// <=== add with constraints here
getContentPane().add(_header, new GridBagConstraints(0, 0, 1, 1, 1, 20, GridBagConstraints.BASELINE, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
_content = new JPanel();
JScrollPane jsp = new JScrollPane(_content, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
// <=== add with constraints here
getContentPane().add(jsp, new GridBagConstraints(0, 1, 1, 1, 1, 60, GridBagConstraints.BASELINE, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
_footer = new JPanel();
_footer.setBackground(Color.GRAY);
// <=== add with constraints here
getContentPane().add(_footer, new GridBagConstraints(0, 2, 1, 1, 1, 20, GridBagConstraints.BASELINE, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
pack();
validate();
setTitle("Chat client");
setVisible(true);
setSize(500, 500);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Window();
}
});
}
}
Screenshot

Repeat WindowBuilder JLabel using Grid Layout

I want to repeat a JLabel "n" no. of times where "n" is given by user.
This implementation, using WindowBuilder's Grid layout, doesn't work, prints nothing at all.
What am I doing wrong?
JLabel lblNewLabel_1[]=new JLabel[20];
GridBagConstraints gbc_lblNewLabel_1[] = new GridBagConstraints[20];
for(int i=0;i<n;i++)
{
lblNewLabel_1[i] = new JLabel("Table #");
gbc_lblNewLabel_1[i].insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_1[i].gridx = 0;
gbc_lblNewLabel_1[i].gridy = 4+i;
frame.getContentPane().add(lblNewLabel_1[i], gbc_lblNewLabel_1[i]);
}
Full Method, my content pane is grid layout.
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 507, 432);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{57, 377, 0};
gridBagLayout.rowHeights = new int[]{60, 37, 35, 20, 0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
textField = new JTextField();
textField.setToolTipText("Max: 20");
textField.setText("0");
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource()==textField)
n = Integer.parseInt(arg0.getActionCommand());
}
});
JLabel lblNewLabel = new JLabel("Enter The Number of Tables");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 30));
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel.gridx = 1;
gbc_lblNewLabel.gridy = 1;
frame.getContentPane().add(lblNewLabel, gbc_lblNewLabel);
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 3;
frame.getContentPane().add(textField, gbc_textField);
textField.setColumns(10);
GridBagConstraints gbc_lblNewLabel_1[] = new GridBagConstraints[20];
for(int i=0;i<n;i++){
lblNewLabel_1[i] = new JLabel("Table #");
gbc_lblNewLabel_1[i].insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_1[i].gridx = 0;
gbc_lblNewLabel_1[i].gridy = 4+i;
frame.getContentPane().add(lblNewLabel_1[i], gbc_lblNewLabel_1[i]);
}
}
The default layout for a JFrame is a BorderLayout.
If you want to use a GridBagLayout then you need to set the layout of the content pane to use a GridBagLayout.
I suggest you read the section from the Swing turial on How to Use GridBagLayout for more explanation and working examples.
If you want to use a GridLayout, then you also need to set the layout manager of the content pane to a GridLayout and you don't use any constraints. Again, read the tutorial for examples.

GUI pack and setVisible error

Im writing this for fun, this is not homework so please help me all you can. I am trying to make a "dice" that spits out various ski tricks that you can do and i cannot get my gui to come up or work.
public SkiDice20(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = new JPanel();
panel1.setLayout(new GridBagLayout());
addItem(panel1, new JLabel("Name: "), 0, 0, 1, 1, GridBagConstraints.EAST);
addItem(panel1, newName, 1, 0, 2, 1, GridBagConstraints.WEST);
System.out.print(newName.getText());
Box slayBox = Box.createVerticalBox();
slayGroup.add(jump);
slayGroup.add(rail);
slayGroup.add(slope);
slayBox.add(jump);
slayBox.add(rail);
slayBox.add(slope);
slayBox.setBorder(BorderFactory.createTitledBorder("What are you Slaying?"));
addItem(panel1, slayBox, 0, 3, 1, 1, GridBagConstraints.NORTH);
Box skillBox = Box.createVerticalBox();
skillGroup.add(gaper);
skillGroup.add(nser);
skillGroup.add(am);
skillGroup.add(pro);
skillBox.add(gaper);
skillBox.add(nser);
skillBox.add(am);
skillBox.add(pro);
skillBox.setBorder(BorderFactory.
createTitledBorder("Skill?"));
addItem(panel1, skillBox, 1, 3, 1, 1, GridBagConstraints.NORTH);
Box buttonBox = Box.createHorizontalBox();
buttonBox.add(okButton);
buttonBox.add(Box.createHorizontalStrut(20));
buttonBox.add(completeButton);
addItem(panel1, buttonBox, 2, 4, 1, 1, GridBagConstraints.NORTH);
this.add(panel1);
this.pack();
this.setVisible(true);
And this is my main method.
public static void main(String[] args) {
String input = JOptionPane.showInputDialog ( "Number of people Skiing?" );
numberOfPeople = Integer.parseInt(input);
new SkiDice20();
checkSelection();
for (int i = 0; i < numberOfPeople; i++){
}
}
I am getting an error on these three lines and nothing else
this.add(panel1);
this.pack();
this.setVisible(true);
I know the cooardinates are screwed up right now, i took the code from an old project that i did but i forgot how i got this to work. Thank you for any help it is greatly appreciated
Needed to extend SkiDice20. After that it worked.

How to make an input form in Java code (not Netbeans using JForm)?

I want to make an input form in Java so that the user can enter details.
Something like this:
My code
import java.awt.GridLayout;
import javax.swing.*;
class JOptionPaneTest {
public static void main(String[] args) {
String[] items = {"One", "Two", "Three", "Four", "Five"};
JComboBox combo = new JComboBox(items);
JTextField field1 = new JTextField("1234.56");
JTextField field2 = new JTextField("9876.54");
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(combo);
panel.add(new JLabel("Field 1:"));
panel.add(field1);
panel.add(new JLabel("Field 2:"));
panel.add(field2);
int result = JOptionPane.showConfirmDialog(null, panel, "Test",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
System.out.println(combo.getSelectedItem()
+ " " + field1.getText()
+ " " + field2.getText());
} else {
System.out.println("Cancelled");
}
}
}
My output form:
I think I must change my layout to something like BorderLayout. Any ideas how to get the look of the form at the top of the question?
Yes, you have to change layout. Have a look at SpringLayout and this example:
(source: sun.com)
String[] labels = {"Name: ", "Fax: ", "Email: ", "Address: "};
int numPairs = labels.length;
//Create and populate the panel.
JPanel p = new JPanel(new SpringLayout());
for (int i = 0; i < numPairs; i++) {
JLabel l = new JLabel(labels[i], JLabel.TRAILING);
p.add(l);
JTextField textField = new JTextField(10);
l.setLabelFor(textField);
p.add(textField);
}
//Lay out the panel.
SpringUtilities.makeCompactGrid(p,
numPairs, 2, //rows, cols
6, 6, //initX, initY
6, 6); //xPad, yPad
SpringLayout works fine for this simple form, but there is third party libraries that has more features. I.e. MiG Layout.
Another way to create a form using GridBagLayout, producing the following result:
Code:
JPanel addressPanel = new JPanel();
Border border = addressPanel.getBorder();
Border margin = new EmptyBorder(10, 10, 10, 10);
addressPanel.setBorder(new CompoundBorder(border, margin));
GridBagLayout panelGridBagLayout = new GridBagLayout();
panelGridBagLayout.columnWidths = new int[] { 86, 86, 0 };
panelGridBagLayout.rowHeights = new int[] { 20, 20, 20, 20, 20, 0 };
panelGridBagLayout.columnWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
panelGridBagLayout.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0,
Double.MIN_VALUE };
addressPanel.setLayout(panelGridBagLayout);
addLabelAndTextField("City:", 0, addressPanel);
addLabelAndTextField("Street:", 1, addressPanel);
addLabelAndTextField("State:", 2, addressPanel);
addLabelAndTextField("Phone:", 3, addressPanel);
addLabelAndTextField("Mail:", 4, addressPanel);
The helper method addLabelAndTextField:
private void addLabelAndTextField(String labelText, int yPos,
Container containingPanel) {
JLabel label = new JLabel(labelText);
GridBagConstraints gridBagConstraintForLabel = new GridBagConstraints();
gridBagConstraintForLabel.fill = GridBagConstraints.BOTH;
gridBagConstraintForLabel.insets = new Insets(0, 0, 5, 5);
gridBagConstraintForLabel.gridx = 0;
gridBagConstraintForLabel.gridy = yPos;
containingPanel.add(label, gridBagConstraintForLabel);
JTextField textField = new JTextField();
GridBagConstraints gridBagConstraintForTextField = new GridBagConstraints();
gridBagConstraintForTextField.fill = GridBagConstraints.BOTH;
gridBagConstraintForTextField.insets = new Insets(0, 0, 5, 0);
gridBagConstraintForTextField.gridx = 1;
gridBagConstraintForTextField.gridy = yPos;
containingPanel.add(textField, gridBagConstraintForTextField);
textField.setColumns(10);
}
You are currently using a GridLayout, which can be fine for your need.
However, you should initialize it with the actual number of rows and columns you will need. In your case:
new GridLayout(0, 2);
0 for rows means there is not limit, and you have 2 columns, one for the labels, and one for the input component. See the Java tutorial for more information on GridLayouts.
(source: sun.com)
Note however that the GridLayout will make all "cells" to be the same size, which can be a problem for the labels.
However, Jonas is right, a SpringLayout is probably more adapted to your need.
You can do this with DesignGridLayout. The following snippet should work (sorry I could not test it I am not on my dev station right now):
DesignGridLayout layout = new DesignGridLayout(panel);
layout.row().grid(streetAddressLabel).add(streetAddressField);
layout.row().grid(cityLabel).add(cityField);
layout.row().grid(stateLabel).add(stateSpinner);
layout.row().grid(zipLabel).add(zipField);
layout.emptyRow();
layout.row().right().add(setAddressButton, clearAddressButton);
Then you would use JDialog (rather than JOptionPane) to display your panel.

Categories