So this problem is really giving me a headache because for some reason last night when i was working on it, my code ran perfectly and my textfields would show up without a problem...
Go to bed, wake up, time to work on it again aaaaaand bam. Now my JtextFields only show up when i highlight them or click them or something...I was wondering what could be wrong?
My code is really just messy and crappy at this point while i figure out a better way to design my program...
I thought it was just eclipse but netbeans is giving me the same issue.
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.awt.*;
import javax.swing.border.*;
public class DiffuserCalc {
//create the class data fields
private double Qts;
private double Qes;
private double Vas;
JFrame ProgramBounds = new JFrame();
JLabel label1= new JLabel("Qts");
JLabel label2= new JLabel("Qes");
JLabel label3= new JLabel("Fs");
JLabel label4= new JLabel("BL");
JLabel label5= new JLabel("Xmax");
JLabel label6= new JLabel("Fs");
JLabel label7= new JLabel("Vas");
JLabel label8= new JLabel("Diameter");
JLabel label9= new JLabel("Pmax (RMS)");
JTextField QtsParam = new JTextField("Value");
JTextField QesParam = new JTextField("Value");
JTextField FsParam = new JTextField(" ");
JTextField BLParam = new JTextField(" ");
JTextField XmaxParam = new JTextField(" ");
Font myFont = new Font("Tahoma", Font.BOLD, 20);
DiffuserCalc()
{
ProgramBounds.setTitle("Box Designer");
JPanel ParameterMenu = new JPanel();
JPanel FieldInputs = new JPanel();
ParameterMenu.setBounds(30, 0, 1180, 120);
FieldInputs.setBounds(0,0, 1280, 720);
ProgramBounds.add(ParameterMenu);
ProgramBounds.add(FieldInputs);
ProgramBounds.setSize(1280,720);
// LAYOUT
ParameterMenu.setLayout(new FlowLayout(FlowLayout.CENTER, 60, 10));
FieldInputs.setLayout(null);
Border lineBdr = BorderFactory.createLineBorder(Color.BLACK);
Border BlackBorder = BorderFactory.createTitledBorder(lineBdr, " T/S Parameters ", TitledBorder.CENTER, TitledBorder.TOP, myFont, Color.black);
//FIELD PROPERTIES
label1.setFont(myFont);
label2.setFont(myFont);
label3.setFont(myFont);
label4.setFont(myFont);
label5.setFont(myFont);
label6.setFont(myFont);
label7.setFont(myFont);
label8.setFont(myFont);
label9.setFont(myFont);
// PARAMETER BOUNDS
int XLoc = 150;
int YLoc = 70;
QtsParam.setBounds(XLoc, YLoc, 40, 20);
QesParam.setBounds(XLoc+95, YLoc, 40, 20);
FsParam.setBounds(XLoc+190, YLoc, 40, 20);
// ADD FIELDS
ParameterMenu.add(label1);
ParameterMenu.add(label2);
ParameterMenu.add(label3);
ParameterMenu.add(label4);
ParameterMenu.add(label5);
ParameterMenu.add(label6);
ParameterMenu.add(label7);
ParameterMenu.add(label8);
ParameterMenu.add(label9);
ParameterMenu.setBorder(BlackBorder);
FieldInputs.add(QtsParam);
FieldInputs.add(QesParam);
FieldInputs.add(FsParam);
FieldInputs.add(BLParam);
FieldInputs.add(XmaxParam);
// set everything proper
QtsParam.requestFocus();
ParameterMenu.setVisible(true);
FieldInputs.setVisible(true);
ProgramBounds.setVisible(true);
}
public double BoxDimension(int x, int y)
{
return x;
}
public static void main(String[] args) {
DiffuserCalc MainProgram = new DiffuserCalc();
}
}
Your code only sets the bounds for 3 text fields but you add 5 text fields to the panel.
Don't use a null layout!!!
Use a proper layout manager and then you don't have to worry about making mistakes like this.
Also, follow Java naming conventions. Variable names do NOT start with an upper case character.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
public class DiffuserCalc {
//create the class data fields
private double qts;
private double qes;
private double vas;
private JFrame programBounds = new JFrame();
private JLabel label1= new JLabel("Qts");
private JLabel label2= new JLabel("Qes");
private JLabel label3= new JLabel("Fs");
private JLabel label4= new JLabel("BL");
private JLabel label5= new JLabel("Xmax");
private JLabel label6= new JLabel("Fs");
private JLabel label7= new JLabel("Vas");
private JLabel label8= new JLabel("Diameter");
private JLabel label9= new JLabel("Pmax (RMS)");
private JTextField qtsParam = new JTextField("Value");
private JTextField qesParam = new JTextField("Value");
private JTextField fsParam = new JTextField("");
private JTextField bLParam = new JTextField("");
private JTextField xmaxParam = new JTextField("");
private Font myFont = new Font("Tahoma", Font.BOLD, 20);
DiffuserCalc()
{
programBounds.setTitle("Box Designer");
JPanel parameterMenu = new JPanel();
JPanel labelPanel = new JPanel();
JPanel fieldInputs = new JPanel();
// LAYOUT
programBounds.setLayout(new BorderLayout());
parameterMenu.setLayout(new BorderLayout());
fieldInputs.setLayout(new FlowLayout(FlowLayout.LEFT));
fieldInputs.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
labelPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
labelPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
programBounds.add(parameterMenu, BorderLayout.NORTH);
parameterMenu.add(labelPanel, BorderLayout.NORTH);
parameterMenu.add(fieldInputs, BorderLayout.SOUTH);
// programBounds.add(fieldInputs);
programBounds.setSize(1280,720);
Border lineBdr = BorderFactory.createLineBorder(Color.BLACK);
Border BlackBorder = BorderFactory.createTitledBorder(lineBdr, " T/S Parameters ", TitledBorder.CENTER, TitledBorder.TOP, myFont, Color.black);
//FIELD PROPERTIES
label1.setFont(myFont);
label2.setFont(myFont);
label3.setFont(myFont);
label4.setFont(myFont);
label5.setFont(myFont);
label6.setFont(myFont);
label7.setFont(myFont);
label8.setFont(myFont);
label9.setFont(myFont);
// ADD FIELDS
labelPanel.add(label1);
labelPanel.add(label2);
labelPanel.add(label3);
labelPanel.add(label4);
labelPanel.add(label5);
labelPanel.add(label6);
labelPanel.add(label7);
labelPanel.add(label8);
labelPanel.add(label9);
parameterMenu.setBorder(BlackBorder);
qtsParam.setColumns(3);
fieldInputs.add(qtsParam);
qesParam.setColumns(3);
fieldInputs.add(qesParam);
fsParam.setColumns(2);
fieldInputs.add(fsParam);
bLParam.setColumns(2);
fieldInputs.add(bLParam);
xmaxParam.setColumns(2);
fieldInputs.add(xmaxParam);
// set everything proper
qtsParam.requestFocus();
programBounds.pack();
programBounds.setVisible(true);
}
public double BoxDimension(int x, int y)
{
return x;
}
public static void main(String[] args) {
DiffuserCalc MainProgram = new DiffuserCalc();
}
}
So I rewrote the class for you to be more according to the Java style standard. Next not using a Layout manager is asking for trouble. And even though your requirements are like you say it's still better to put the effort to use a Layout manager as you'll keep running into problems like these. Read more about layout managers here. Furthermore don't call setVisible on JPanels that you added to a frame. When you call setVisible on the JFrame it will call setVisible on all of it child components.
Next call the method setColumns on the JTextField instead of initializing it with spaces for more consistent and predictable behaviour.
Related
I am trying to make the interface of a program using Java Swing. I have a container where I add 3 JPanels with some components. The problem is that when I expand the frame all those 3 JPanels come on the first row one next to another.
Here is my code:
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.border.LineBorder;
public class GraphicRefact extends JFrame {
private Container container;
private JButton button2;
private JButton button1;
private JTextField textField01;
private JLabel label01;
private JButton button03;
private JButton button04;
private JTextField textField03;
private JLabel label03;
private JButton button02;
private JButton button01;
private JTextField textField02;
private JLabel label02;
public static void main(String[] args) {
new GraphicRefact();
}
public GraphicRefact() {
initializeComponents();
setTitle("Title");
setSize(500, 150);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
container = new JPanel();
JPanel panel01 = new JPanel();
panel01.add(label01);
panel01.add(textField01);
panel01.add(button2);
panel01.add(button1);
panel01.setBorder(new LineBorder(Color.BLACK, 3));
container.add(panel01);
JPanel panel02 = new JPanel();
panel02.add(label02);
panel02.add(textField02);
panel02.add(button02);
panel02.add(button01);
container.add(panel02);
JPanel panel03 = new JPanel();
panel03.add(label03);
panel03.add(textField03);
panel03.add(button03);
panel03.add(button04);
container.add(panel03);
add(container);
}
private void initializeComponents() {
button1 = new JButton("Open");
button2 = new JButton("Close");
textField01 = new JTextField("Choose the path...");
label01 = new JLabel("Choose File: ");
button01 = new JButton("Button01");
button02 = new JButton("Button02");
textField02 = new JTextField("Choose the path...");
label02 = new JLabel("Choose Dir:");
button03 = new JButton("Button03");
button04 = new JButton("Button03");
textField03 = new JTextField("Choose the path...");
label03 = new JLabel("Choose Dir:");
}
}
Here is how the program looks before and after I expand the frame.
Before:
After:
So, even after I expand the frame, I want the program to leave those 3 JPanels on the middle of cotainer.
Thank you!
You can set the gridLayout and put those elements inside.
JPanel jp = new JPanel();
GridLayout gl = new GridLayout(3,4); //3 rows, 4 columns
jp.setLayout(gl);
After you do this, just put your elements inside layout, by order.
jp.add(label1);
jp.add(button1);
//etc...
You have to use a proper LayoutManager. Look at the examples there. BoxLayout seems to be what you want.
I can't see where you have defined any positions for anything, if you need to read how that's done you can start here
Positioning a JPanel in a JFrame at specific position
The inbuilt layout manger of java swing are not that useful.
You should use this
frame.setLayout(null);
component.setLocation(x, y);
frame.add(component);
In class today we put together a basic GUI for calculating the distance between two points. Neither the instructor nor my classmates could figure out why this GUI won't process. The code given to us was a framework and we just edited the old code to develop this. I compared my work to that of two other students and theirs worked while mine didn't.
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Graphics;
import java.text.DecimalFormat;
import java.awt.Color;
import java.awt.Font;
import java.lang.Math;
public class D2 extends JFrame
{
//****************************************
//** GUI Structure
//** Title: Holston Middle School
//** Weight prompt (jlabel, jtext)
//** planet pulldown
//** Weight on planet (jlabel, jtext)
//** calculate button
//****************************************
public JTextField entry1, entry2, entry3, entry4, output1;
public JLabel label1, label2, label3, label4, label5;
public JButton CalculateButton;
public String mtitle, cmessage;
public D2()
{
setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));
label1 = new JLabel("x1");
add(label1);
entry1 = new JTextField(8);
add(entry1);
setEnabled(true);
setVisible(true);
label2 = new JLabel("x2");
add(label2);
entry2 = new JTextField(8);
add(entry2);
setEnabled(true);
setVisible(true);
label3 = new JLabel("y1");
add(label3);
entry3 = new JTextField(8);
add(entry3);
setEnabled(true);
setVisible(true);
label4 = new JLabel("y2");
add(label4);
entry4 = new JTextField(8);
add(entry4);
setEnabled(true);
setVisible(true);
label5 = new JLabel("Distance");
add(label5);
output1 = new JTextField(8);
add(output1);
setEnabled(false);
setVisible(true);
CalculateButton = new JButton("Calculate");
add(CalculateButton);
CalculateButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
String entry1string = entry1.getText();
Double e1value = Double.valueOf(entry1string);
String entry2string = entry2.getText();
Double e2value = Double.valueOf(entry2string);
String entry3string = entry3.getText();
Double e3value = Double.valueOf(entry3string);
String entry4string = entry4.getText();
Double e4value = Double.valueOf(entry4string);
String wmessage = "You selected ";
String wtitle = "Pop Up Box";
if (true) JOptionPane.showMessageDialog(null, wmessage, wtitle, JOptionPane.PLAIN_MESSAGE);
double distance = (Math.pow((e1value - e2value), 2) + Math.pow((e3value - e4value), 2));
DecimalFormat fmt = new DecimalFormat("####.##");
String outstring = fmt.format(distance);
output1.setText("");
output1.setText(outstring);
}//** actionPerformed
}); //** Action Listener
} //** D2 constructor
public static void main(String[] args)
{
D2 frame = new D2();
frame.setTitle("Distance Calculator");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 200);
frame.setBackground(Color.CYAN);
frame.getContentPane().setBackground(Color.lightGray);
frame.setVisible(true);
} //** main
} //** class
Inserting print statements and setting the value of label1 to another value results in no change in the GUI. Any help?
During creation of output1 you wrote setEnabled(false);. Possibly you meant that output1 controll should be disabled. But instead of that you disabled the whole container, thus all elements are not editable\clickable. To fix the behaviour set this property directly to control:
output1 = new JTextField(8);
add(output1);
output1.setEnabled(false);
output1.setVisible(true);
Hope this will help.
P.S. It seems that you also need to improve calculation itself by adding Math.sqrt (if I understood your idea correctly):
double distance = Math.sqrt(Math.pow((e1value - e2value), 2) + Math.pow((e3value - e4value), 2));
#Mikita is right. You could also consider adding a JPanel in your JFrame or at least add all your components (JButtons, JTextfields etc) into the ContentPane of the JFrame.
See the Using Top-Level Containers tutorial and this FlowLayout sample.
getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));
label1 = new JLabel("x1");
getContentPane().add(label1);
entry1 = new JTextField(8);
getContentPane().add(entry1);
or
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 20));
label1 = new JLabel("x1");
panel.add(label1);
entry1 = new JTextField(8);
panel.add(entry1);
getContentPane().add(panel);
So I tried to create an empty border and was required to import javax.swing.border.EmptyBorder;
However I had already imported javax.swing.*;
How come I was required to import the prior import? Doesn't the .* import everything from the swing package.
My source code is listed below:
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
/*
public class Gui extends JFrame {
//row1
JPanel row1 = new JPanel();
JButton reset = new JButton("Reset");
JButton play = new JButton("Play");
//row2
JPanel row2 = new JPanel();
JLabel option = new JLabel("Guess: ", JLabel.RIGHT);
JTextField text1 = new JTextField("0");
JTextField text2 = new JTextField("0");
JTextField text3 = new JTextField("0");
//row3
JPanel row3 = new JPanel();
JLabel answerL = new JLabel("Answer: ", JLabel.RIGHT);
JTextField answerB = new JTextField("", 0);
*/
public Gui(){
/* super("Guess My Number");
setSize(500, 800);
GridLayout masterLayout = new GridLayout(4, 1);
setLayout(masterLayout);
FlowLayout layout1 = new FlowLayout(FlowLayout.LEFT);
row1.setLayout(layout1);
row1.add(reset);
row1.add(play);
add(row1);
GridLayout layout2 = new GridLayout(1, 4, 30, 30);
row2.setLayout(layout2);*/
row2.setBorder(new EmptyBorder(0,100,0,200));
/*row2.add(option);
row2.add(text1);
row2.add(text2);
row2.add(text3);
add(row2);
GridLayout layout3 = new GridLayout(1,1, 10, 10);
row3.setLayout(layout3);
row3.add(answerL);
row3.add(answerB);
add(row3);
setVisible(true);
}
public static void main(String[] args){
Gui game = new Gui();
}
}
*/
There's no relationship between nested packages in Java.
javax.swing.* will only import classes directly found in javax.swing, javax.swing.border is considered a different unrelated package altogether from a language standpoint.
So we're supposed to be making a reservation screen for our Airline. After the user inputs his/her information and clicks on Reserve my code needs to show her the information back in on a separate frame. I have the frame set up, I just need to transfer the information IN the JTextField to the frame on JLabel. I heard I need to make it into a variable so I can use it in multiple places. I'm new to Java so please don't use words I might not be familiar with. Thank you and here is my code. I have 3 classes.
First Class:
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TicketMan {
public static void main(String[] args) {
JFrame frame = new JFrame ("Airport");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
TicketManBot panel = new TicketManBot();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true); } }
Second Class:(The class the fields are on.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class TicketManBot extends JPanel {
private JLabel name;
private JLabel dest;
private JLabel depc;
private JLabel dept;
private JLabel seat;
private JButton b;
Random rand = new Random();
private JTextField namef, destf, depcf, deptf;
public TicketManBot()
{
name = new JLabel ("Enter passenger's name:");
dest = new JLabel ("Destination: ");
depc = new JLabel ("Departure city: ");
dept = new JLabel ("Departure time: ");
seat = new JLabel ("Seat Number: " + rand.nextInt(100));
b = new JButton ("Make Reservation");
b.addActionListener (new results());
// the fields I need to move
namef = new JTextField (10);
destf = new JTextField (10);
depcf = new JTextField (10);
deptf = new JTextField (10);
add (name);
add (namef);
add (dest);
add (destf);
add (depc);
add (depcf);
add (dept);
add (deptf);
add (seat);
add (b);
setPreferredSize (new Dimension(200, 300));
setBackground (Color.gray);
}
private class results implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
int resultLabel;
String text = namef.getText();
JFrame results = new JFrame("Thank you for flying with JJ Air");
results.setVisible(true);
results.setSize (200, 300);
// I need to move the fields up there in front of these VVVVVV
JLabel nr = new JLabel ("Name of the passenger:");
JLabel dr = new JLabel ("Destination:");
JLabel depr = new JLabel ("Departure city:");
JLabel dpr = new JLabel ("Departure time:");
JLabel sr = new JLabel ("Seat number:");
JLabel t = new JLabel ("Thank you for flying with us");
JLabel label = new JLabel ("");
JPanel panel = new JPanel ();
results.add(panel);
panel.add (nr);
panel.add (dr);
panel.add (depr);
panel.add (dpr);
panel.add (sr);
panel.add (t);
}
}
}
Third Class:
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
public class results extends JPanel {
}
jLabel.setText(jTextField.getText());
Where jLabel is your label and jTextField your text field.
For example:
JLabel nr = new JLabel ("Name of the passenger:"+Namef.getText());
You should read up on the Java coding style guidelines by the way, it will help make your code more readable to others.
Jlabel is the label you want to set text to. jtextField is the tetxfield you want to get info from
jLabel.setText(jTextField.getText());
Also what you could do, is maybe gather all info from all textFields into Array and then use it to display whatever from array in desired jLabel. Or even better use Array to display data in nice looking Table :)
I have a panel, in which I want the content to displayed vertically. To do that, I'm using this line of code:
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
As I'm using textfields, then I would like them to take up one line. But by using the line of code specified above, textfields inside the panel get maximized and when I change the window size, the size of the textfield changes accordingly. I also tried removing it, but then the contents inside the panel get displayed horizontally and won't fit inside the panel.
Here is the image of the result:
And here is the code where the content of the panel gets created:
//Creates the form for data and button to save it.
final TextField name;
final TextField eMail;
final TextField dateOfBirth;
final TextField address;
JLabel nameLabel = new JLabel("Name:");
name = new TextField ();
JLabel eMailLabel = new JLabel("E-mail:");
eMail = new TextField ();
JLabel dateOfBirthLabel = new JLabel("Date of birth:");
dateOfBirth = new TextField ();
JLabel addressLabel = new JLabel("Address:");
address = new TextField ();
rightPanel.add(nameLabel);
rightPanel.add(name);
rightPanel.add(eMailLabel);
rightPanel.add(eMail);
rightPanel.add(dateOfBirthLabel);
rightPanel.add(dateOfBirth);
rightPanel.add(addressLabel);
rightPanel.add(address);
rightPanel.add(Box.createRigidArea(new Dimension(20, 20)));
JButton save = new JButton("Save");
rightPanel.add(save);
You need to fill the rest of the panel with something, use swing.Box
import javax.swing.Box;
rightPanel.add(Box.createVerticalGlue());
put the box in the position where you want the space to apear
More on that subject http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html#filler
You also need to limit maximum height of the input boxes (for each input call - create method probably):
input.setMaximumSize(new Dimension(Integer.MAX_VALUE, input.getMinimumSize().height));
You can put your panel in the NORTH part of a BorderLayout -- in the EAST or CENTER parts of a BorderLayout, the panel stretches up/down, but not in the North. And, of course, you can put it in its own JPanel with that BorderLayout, and then put THAT JPanel in another layout however you want.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GraphicsConfiguration;
import java.awt.HeadlessException;
import java.awt.TextField;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class RightPanel extends JFrame
{
TextField name;
TextField eMail;
TextField dateOfBirth;
TextField address;
JPanel rightPanel = new JPanel();
public static void main(String[] args)
{
RightPanel rp = new RightPanel();
rp.createUI();
rp.setVisible(true);
}
public void createUI()
{
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
//Creates the form for data and button to save it.
JLabel nameLabel = new JLabel("Name:");
name = new TextField ();
JLabel eMailLabel = new JLabel("E-mail:");
eMail = new TextField ();
JLabel dateOfBirthLabel = new JLabel("Date of birth:");
dateOfBirth = new TextField ();
JLabel addressLabel = new JLabel("Address:");
address = new TextField ();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.PAGE_AXIS));
rightPanel.add(nameLabel);
rightPanel.add(name);
rightPanel.add(eMailLabel);
rightPanel.add(eMail);
rightPanel.add(dateOfBirthLabel);
rightPanel.add(dateOfBirth);
rightPanel.add(addressLabel);
rightPanel.add(address);
rightPanel.add(Box.createRigidArea(new Dimension(20, 20)));
JButton save = new JButton("Save");
rightPanel.add(save);
JPanel doNotStretchPanel = new JPanel();
doNotStretchPanel.setLayout(new BorderLayout());
doNotStretchPanel.add(rightPanel, BorderLayout.NORTH);
this.add(doNotStretchPanel, BorderLayout.EAST);
pack();
}
}