Empty JFrame when adding JLabel & JTextField to it [duplicate] - java

This question already has answers here:
How to align JLabel-JTextField pairs vertically
(7 answers)
Arrange the Label with its respective field Swing
(6 answers)
Setting JLabels in rows and placing the equivalent JTextField right next to it
(2 answers)
Closed 5 years ago.
So I am supposed to make a very simple fillout form like name: ______, and they are supposed to be underneath each other , but when I add these JTextFields and JLabels to the JFrame I get an empty JFrame.
JFrame frame = new JFrame("Name's Item Orders Calculator");
JPanel panel = new JPanel();
BorderLayout layout = new BorderLayout(0,2);
JTextField nameField = new JTextField(15);
JTextField numberField = new JTextField(15);
JTextField costField = new JTextField(15);
JTextField amountField = new JTextField(15);
JLabel name = new JLabel("Item Name: ");
JLabel number = new JLabel("Number of: ");
JLabel cost = new JLabel("Cost: ");
JLabel amount = new JLabel("Amount owed: ");
panel.add(name, BorderLayout.WEST);
panel.add(number, BorderLayout.WEST);
panel.add(cost, BorderLayout.WEST);
panel.add(amount, BorderLayout.WEST);
panel.add(nameField, BorderLayout.EAST);
panel.add(numberField, BorderLayout.EAST);
panel.add(costField, BorderLayout.EAST);
panel.add(amountField, BorderLayout.EAST);
/*
panel.add(new JLabel("North"), BorderLayout.WEST);
panel.add(new JLabel("Another North"), BorderLayout.WEST);
*/
frame.pack();
frame.add(panel);
frame.setLayout(layout);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);

Related

Is it possible to change the height of each grid in a GridLayout?

I am trying to create a simple menu interface with 4 rows of various buttons and labels using GridLayout with FlowLayout inside each grid for organising the elements. However the space for the buttons and labels which should only take 1 line takes up a huge amount of space.
This is what my interface looks like minimized:
This is what it looks like maximized:
I am looking to set the maximum size of the labels panels/grid so that it only takes a small amount of space.
I am trying to make all the elements visible without anything being hidden with as small a window size as possible like this:
This is my code:
public class Window extends JFrame{
public Window() {
super("TastyThai Menu Ordering");
}
public static void main(String[] args) {
Window w = new Window();
w.setSize(500, 500);
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel title = new JLabel("TastyThai Menu Order", SwingConstants.CENTER);
title.setFont(title.getFont().deriveFont(32f));
//generate page title
Container titlePanel = new JPanel(); // used as a container
titlePanel.setBackground(Color.WHITE);
FlowLayout flow = new FlowLayout(); // Create a layout manager
titlePanel.setLayout(flow);// assign flow layout to panel
titlePanel.add(title); // add label to panel
w.getContentPane().add(BorderLayout.NORTH,titlePanel);
//generate row containers
Container r1 = new JPanel(new FlowLayout());
Container r2 = new JPanel(new FlowLayout());
Container r3 = new JPanel(new FlowLayout());
Container r4 = new JPanel(new FlowLayout());
//generate mains radio buttons
Container mains = new JPanel(new GridLayout(7, 0));
mains.setBackground(Color.RED);
JLabel mainsHeader = new JLabel("Mains");
mains.add(mainsHeader);
String[] mainsChoices = {"Vegetarian", "Chicken", "Beef", "Pork", "Duck", "Seafood Mix"};
JRadioButton[] mainsRadioButton = new JRadioButton[6];
ButtonGroup mainsButtons = new ButtonGroup();
for(int i = 0; i < mainsChoices.length; i++) {
mainsRadioButton[i] = new JRadioButton(mainsChoices[i]);
mains.add(mainsRadioButton[i]);
mainsButtons.add(mainsRadioButton[i]);
}
//generate noodles radio buttons
Container noodles = new JPanel(new GridLayout(7, 0));
noodles.setBackground(Color.GREEN);
JLabel noodlesHeader = new JLabel("Noodles");
noodlesHeader.setFont(noodlesHeader.getFont().deriveFont(24f));
noodles.add(noodlesHeader);
String[] noodlesChoices = {"Pad Thai", "Pad Siew", "Ba Mee"};
JRadioButton[] noodlesRadioButton = new JRadioButton[3];
ButtonGroup noodlesButtons = new ButtonGroup();
for(int i = 0; i < noodlesChoices.length; i++) {
noodlesRadioButton[i] = new JRadioButton(noodlesChoices[i]);
noodles.add(noodlesRadioButton[i]);
noodlesButtons.add(noodlesRadioButton[i]);
}
//generate sauces radio buttons
Container sauces = new JPanel(new GridLayout(7, 0));
sauces.setBackground(Color.BLUE);
JLabel saucesHeader = new JLabel("Sauce");
saucesHeader.setFont(saucesHeader.getFont().deriveFont(24f));
sauces.add(saucesHeader);
String[] saucesChoices = {"Soy Sauce", "Tamarind Sauce"};
JRadioButton[] saucesRadioButton = new JRadioButton[2];
ButtonGroup saucesButtons = new ButtonGroup();
for(int i = 0; i < saucesChoices.length; i++) {
saucesRadioButton[i] = new JRadioButton(saucesChoices[i]);
sauces.add(saucesRadioButton[i]);
saucesButtons.add(saucesRadioButton[i]);
}
//generate extras check boxes
Container extras = new JPanel(new GridLayout(7, 0));
extras.setBackground(Color.YELLOW);
JLabel extrasHeader = new JLabel("Extra");
extrasHeader.setFont(extrasHeader.getFont().deriveFont(24f));
extras.add(extrasHeader);
String[] extrasChoices = {"Mushroom", "Egg", "Broccoli", "Beansrpout", "Tofu"};
JCheckBox[] extrasBoxes = new JCheckBox[5];
for(int i = 0; i < extrasChoices.length; i++) {
extrasBoxes[i] = new JCheckBox(extrasChoices[i]);
extras.add(extrasBoxes[i]);
}
JLabel selectionPrice = new JLabel("Selection Price: $ ");
JLabel selectionPriceVal = new JLabel("_______________");
JButton addToOrder = new JButton("Add to Order");
JLabel totalPrice = new JLabel("Total Price: $ ");
JLabel totalPriceVal = new JLabel("_______________");
JButton clearOrder = new JButton("Clear Order");
JRadioButton pickUp = new JRadioButton("Pick Up");
JRadioButton delivery = new JRadioButton("Delivery");
ButtonGroup pickupDelivery = new ButtonGroup();
pickupDelivery.add(pickUp);
pickupDelivery.add(delivery);
JButton completeOrder = new JButton("Complete Order");
Container menuSelection = new JPanel(new GridLayout(4,0));
menuSelection.add(r1);
r1.add(mains);
r1.add(noodles);
r1.add(sauces);
r1.add(extras);
menuSelection.add(r2);
r2.add(selectionPrice);
r2.add(selectionPriceVal);
r2.add(addToOrder);
menuSelection.add(r3);
r3.add(totalPrice);
r3.add(totalPriceVal);
r3.add(clearOrder);
menuSelection.add(r4);
r4.add(pickUp);
r4.add(delivery);
r4.add(completeOrder);
w.getContentPane().add(BorderLayout.CENTER, menuSelection);
w.setVisible(true);
}
}
GridLayout does not support that. All rectangles have the same size.
Take a look at the GridBagLayout, which supports dynamic resizing and much more.

Adding Components to Frame using Absolute Positioning

I am creating a simple Tic Tac Toe Application in Swing using setBounds (null Layout).
My problem is that whichever component i add in the end, is not visible in the frame, or distorts the complete GUI.
My code would better explain this
import java.awt.*;
import javax.swing.*;
class ZeroKata
{
ButtonGroup p1group,p2group;
Font f;
JButton begin,b1,b2,b3,b4,b5,b6,b7,b8,b9;
JCheckBox p1K,p2K,p1Z,p2Z;
JFrame frame;
JLabel player1,player2,p1Name,p2Name,p1Symbol,p2Symbol,status,dummy; // dummy label for my problem
JPanel buttons;
JTextField name1,name2;
private void addComponents(Container parent,JComponent...c)
{
for(JComponent C:c)
parent.add(C);
}
public ZeroKata()
{
frame = new JFrame("Tic Tac Toe");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(900,650);
frame.setResizable(true);
frame.setVisible(true);
buttons = new JPanel();
buttons.setLayout(new GridLayout(3,3,10,10));
begin = new JButton("START GAME");
b1 = new JButton(" ");
b2 = new JButton(" ");
b3 = new JButton(" ");
b4 = new JButton(" ");
b5 = new JButton(" ");
b6 = new JButton(" ");
b7 = new JButton(" ");
b8 = new JButton(" ");
b9 = new JButton(" ");
p1K = new JCheckBox("X");
p1Z = new JCheckBox("O");
p2K = new JCheckBox("X");
p2Z = new JCheckBox("O");
p1group = new ButtonGroup();
p2group = new ButtonGroup();
p1group.add(p1K);
p1group.add(p1Z);
p2group.add(p2K);
p2group.add(p2Z);
name1 = new JTextField(30);
name2 = new JTextField(30);
f = new Font("Georgia",Font.PLAIN,38);
player1 = new JLabel (" << PLAYER 1 >>");
p1Name = new JLabel ("NAME : ");
p1Symbol = new JLabel ("SYMBOL : ");
player2 = new JLabel ("<< PLAYER 2 >>");
p2Name = new JLabel ("NAME : ");
p2Symbol = new JLabel ("SYMBOL : ");
status = new JLabel ("GAME STATUS -->> ");
dummy = new JLabel (" ");
addComponents(buttons,b1,b2,b3,b4,b5,b6,b7,b8,b9);
player1.setBounds(100,100,100,30);
p1Name.setBounds(120,150,100,30);
p1Symbol.setBounds(120,200,60,30);
player2.setBounds(100,250,100,30);
p2Name.setBounds(120,300,100,30);
p2Symbol.setBounds(120,350,50,30);
name1.setBounds(200,150,150,30);
p1K.setBounds(200,200,50,30);
p1Z.setBounds(250,200,50,30);
name2.setBounds(200,300,150,30);
p2K.setBounds(200,350,50,30);
p2Z.setBounds(250,350,50,30);
buttons.setBounds(500,100,250,250);
dummy.setBounds(20,20,30,30);
begin.setBounds(200,500,150,30);
frame.add(player1);
frame.add(p1Name);
frame.add(p1Symbol);
frame.add(player2);
frame.add(p2Name);
frame.add(p2Symbol);
frame.add(name1);
frame.add(name2);
frame.add(begin);
frame.add(buttons);
frame.add(p1K);
frame.add(p1Z);
frame.add(p2K);
frame.add(p2Z);
/* u need to add a dummy label also to let GUI work correctly, dont know whyx !
frame.add(dummy); */
}
public static void main(String...args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ZeroKata();
}
});
}
}
It is a simple code, I just don't know where I am going wrong .
Thanks in advance !
The default layout manager is a BorderLayout (see JFrame overview), set it to null to allow for absolute positioning:
frame.setLayout(null);
My problem is that whichever component i add in the end, is not
visible in the frame, or distorts the complete GUI. My code would
better explain this
you added JComponents to the already visible JFrame,
move frame.setVisible(true); as last code line, after all JComponents are added
Swing GUI should be started on Initial Threads

Swing sample form application

I have come up with the below code:
String[] labels = {"Name: ", "Fax: ", "Email: ", "Address: "};
int numPairs = labels.length;
JFrame frame = new JFrame("SpringDemo1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
Container contentPane = frame.getContentPane();
SpringLayout layout = new SpringLayout();
contentPane.setLayout(layout);
for (int i = 0; i < numPairs; i++)
{
JLabel lable = new JLabel(labels[i]);
contentPane.add(lable);
contentPane.add(new JTextField(15));
}
//Display the window.
frame.pack();
frame.setVisible(true);
Expectation:
What I am getting:
Default:
when resized:
The result is noway related to how code actually/normally looks like!
I also tried copy pasting and running the ready-made code: downloaded from here:
and this is how the result looks :
To put the components in the right place using SpringLayout, you should use the ( SpringUtilities class ), download it then include it in your project.
your code should be:
private static void createAndShowGUI() {
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
//Create and set up the window.
JFrame frame = new JFrame("SpringForm");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
p.setOpaque(true); //content panes must be opaque
frame.setContentPane(p);
//Display the window.
frame.pack();
frame.setVisible(true);
}
i hope that helps you!

Grid layout columns and rows not working

Basically I am trying to attach two panels onto my frame,
my frame uses BorderLayout and the two panels will be placed North and south.
I am done with the top panel but for the bottom one I cannot get it right.
I used GridLayout for the bottom one and it's supposed to look like this.
http://i47.tinypic.com/wa0lsz.png
So here is the code for the gridlayout
public class WeaponComp extends JPanel{
protected JPanel first = new JPanel();
public WeaponComp(){
setLayout(new GridBagLayout());
setPreferredSize(new Dimension(800,550));
GridBagConstraints c = new GridBagConstraints();
JLabel ntg = new JLabel("");
JLabel oldweap = new JLabel("OLD WEAPON");
JLabel newweap = new JLabel("NEW WEAPON");
JLabel onetwohand = new JLabel ("1H / 2H");
JLabel offhand = new JLabel ("Off Hand");
JLabel dps = new JLabel ("DPS :");
JLabel str = new JLabel ("Str :");
JLabel dex = new JLabel ("Dex :");
JLabel vit = new JLabel ("Vit :");
JLabel intel = new JLabel ("Int :");
JLabel manareg = new JLabel ("Mana Regen :");
JLabel aspd = new JLabel ("Attack Speed:");
JLabel critch = new JLabel ("Crit chance:");
JLabel critdmg = new JLabel ("Crit damage:");
JTextField dpstf = new JTextField(12);
JTextField strtf = new JTextField(5);
JTextField dextf = new JTextField(5);
JTextField vittf = new JTextField(5);
JTextField inteltf = new JTextField(5);
JTextField manaregtf = new JTextField(3);
JTextField aspdtf = new JTextField(3);
JTextField critchtf = new JTextField(3);
JTextField critdmgtf = new JTextField(3);
JTextField offdpstf = new JTextField(12);
JTextField offstrtf = new JTextField(5);
JTextField offdextf = new JTextField(5);
JTextField offvittf = new JTextField(5);
JTextField offinteltf = new JTextField(5);
JTextField offmanaregtf = new JTextField(3);
JTextField offaspdtf = new JTextField(3);
JTextField offcritchtf = new JTextField(3);
JTextField offcritdmgtf = new JTextField(3);
first.setLayout(new GridLayout(3,4));
first.setPreferredSize(new Dimension(750,150));
first.add(oldweap); first.add(ntg); first.add(newweap); first.add(ntg);
first.add(onetwohand); first.add(ntg); first.add(offhand); first.add(ntg);
first.add(dps); first.add(dpstf); first.add(dps); first.add(offdpstf);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0; c.gridy = 0;
add (first,c);
}
}
Here is the current result of my program
http://i50.tinypic.com/107p9uu.png
Thank you in advance for your time and answers
PS : and in case you're wondering, yes, it has something to do with diablo 3
But I am not that ambitious, this is for learning purpose and won't have many functionality.
GridLayout is a poor choice, because all cells automatically have the same size. I suggest using MigLayout instead: http://miglayout.com
The layout code would look like this:
first.setLayout(new MigLayout("wrap 2, fill"));
first.add(oldweap);
first.add(newweap);
first.add(onetwohand);
first.add(offhand);
first.add(dps);
first.add(dpstf);
first.add(dps);
first.add(offdpstf);
You might use GroupLayout1 or a nested layout2 for the bottom panels.
See How to Use GroupLayout for details. E.G.
E.G.

Why is my JFrame not showing?

I'm pretty sure I've done it this way before, but for some reason, the JFrame won't show up when I run it.
JLabel originalString = new JLabel("Original String: "
+ str.getMutator());
JLabel currentString = new JLabel("Current String: "
+ str.getMutator());
JLabel finalString = new JLabel("Final String: " + str.getTarget());
JPanel panel = new JPanel();
panel.add(originalString);
panel.add(currentString);
panel.add(finalString);
JFrame frame = new JFrame("Mutating String!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
Try to set size or check with the preferred size of your components probably because you call pack().
frame.setSize(x, y);
Your problem must be somewhere else (is the method called does it throw an exception ?) because your code works (I commented the str calls) :
http://img217.imageshack.us/img217/902/screenvlg.png
import javax.swing.*;
public class Test{
public static void main(String... args){
JLabel originalString = new JLabel("Original String: " /*+ str.getMutator()*/);
JLabel currentString = new JLabel("Current String: "/* + str.getMutator()*/);
JLabel finalString = new JLabel("Final String: " /* + str.getTarget()*/);
JPanel panel = new JPanel();
panel.add(originalString);
panel.add(currentString);
panel.add(finalString);
JFrame frame = new JFrame("Mutating String!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}

Categories