So I have a Java GUI exercise from college to work on, about making a registration form.
I've [mistakenly] coded everything from beginning to end without testing, and found out that nothing actually appears on my GUI. The program was just a plain JFrame without anything inside, like in the picture above.
I've tried to find out why this happened, however I haven't found any clue why. So your help is appreciated.
So far, I haven't found any duplicate of this question. I found that my issue is somewhat different from other users. So, I'd like to apologize as if there's one duplicate or so.
Below is the code: (you may want to take a keen look at this)
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class RegistrationForm extends JFrame {
private JPanel panel;
private JPanel northPanel;
private JPanel eastPanel;
private JPanel westPanel;
private JPanel southPanel;
private JPanel centerPanel;
private JPanel formPanel;
private JPanel basicFormPanel;
private JPanel addressPanel;
private JPanel typePanel;
private JPanel cityPanel;
private JPanel agreementPanel;
private JPanel buttonPanel;
private JLabel formTitle;
private JLabel lblName;
private JLabel lblEmail;
private JLabel lblPhone;
private JLabel lblAddress;
private JLabel lblType;
private JLabel lblCity;
private JTextField name;
private JTextField email;
private JTextField phone;
private JScrollPane addressScroll;
private JTextArea address;
private ButtonGroup type;
private JRadioButton silver;
private JRadioButton gold;
private JRadioButton platinum;
private JComboBox<String> city;
private JCheckBox agreement;
private JButton submit;
private JButton reset;
public RegistrationForm() {
initElements();
initView();
initFormPanels();
}
public void initElements() {
panel = new JPanel();
northPanel = new JPanel();
eastPanel = new JPanel();
westPanel = new JPanel();
southPanel = new JPanel();
centerPanel = new JPanel();
formPanel = new JPanel();
basicFormPanel = new JPanel();
addressPanel = new JPanel();
typePanel = new JPanel();
cityPanel = new JPanel();
agreementPanel = new JPanel();
buttonPanel = new JPanel();
formTitle = new JLabel("Registration Form");
formTitle.setFont(new Font("Arial", Font.PLAIN, 32));
lblName = new JLabel("Name");
lblEmail = new JLabel("Email");
lblPhone = new JLabel("Phone");
lblAddress = new JLabel("Address");
lblType = new JLabel("Type");
lblCity = new JLabel("City");
name = new JTextField();
email = new JTextField();
phone = new JTextField();
address = new JTextArea();
addressScroll = new JScrollPane(address);
type = new ButtonGroup();
silver = new JRadioButton("Silver");
gold = new JRadioButton("Gold");
platinum = new JRadioButton("Platinum");
String[] cities = {"Jakarta", "Bandung", "Bogor"};
city = new JComboBox<String>(cities);
agreement = new JCheckBox("I agree with the terms and conditions");
submit = new JButton("Submit");
reset = new JButton("Reset");
}
public void initView() {
panel.setLayout(new BorderLayout());
panel.add(northPanel, BorderLayout.NORTH);
panel.add(eastPanel, BorderLayout.EAST);
panel.add(westPanel, BorderLayout.WEST);
panel.add(southPanel, BorderLayout.SOUTH);
panel.add(centerPanel, BorderLayout.CENTER);
northPanel.setBackground(Color.black);
northPanel.setPreferredSize(new Dimension(50, 50));
formTitle.setForeground(Color.white);
eastPanel.setBackground(Color.black);
westPanel.setBackground(Color.black);
southPanel.setBackground(Color.black);
centerPanel.setBackground(Color.gray);
formPanel.setBackground(Color.gray);
basicFormPanel.setBackground(Color.gray);
addressPanel.setBackground(Color.gray);
typePanel.setBackground(Color.gray);
cityPanel.setBackground(Color.gray);
agreementPanel.setBackground(Color.gray);
formPanel.add(basicFormPanel);
formPanel.add(addressPanel);
formPanel.add(typePanel);
formPanel.add(cityPanel);
formPanel.add(agreementPanel);
formPanel.add(buttonPanel);
centerPanel.add(formPanel);
buttonPanel.setBackground(Color.black);
buttonPanel.add(submit);
buttonPanel.add(reset);
southPanel.add(buttonPanel);
}
public void initFormPanels() {
// basic form panel
basicFormPanel.setLayout(new GridLayout(3, 3, 5, 5));
basicFormPanel.add(lblName);
basicFormPanel.add(name);
basicFormPanel.add(lblEmail);
basicFormPanel.add(email);
basicFormPanel.add(lblPhone);
basicFormPanel.add(phone);
// address panel
addressPanel.setLayout(new GridLayout(1, 2, 5, 5));
addressPanel.add(lblAddress);
addressPanel.add(addressScroll);
// type panel
typePanel.setLayout(new GridLayout(1, 2, 5, 5));
typePanel.add(lblType);
type.add(silver);
type.add(gold);
type.add(platinum);
buttonPanel.add(silver);
buttonPanel.add(gold);
buttonPanel.add(platinum);
typePanel.add(buttonPanel);
// city panel
cityPanel.setLayout(new GridLayout(1, 2, 5, 5));
cityPanel.add(lblCity);
cityPanel.add(city);
// agreement checkbox panel
agreementPanel.setLayout(new FlowLayout());
agreementPanel.add(agreement);
// button panel
buttonPanel.add(submit);
buttonPanel.add(reset);
// set preferred sizes
basicFormPanel.setPreferredSize(new Dimension(400, 100));
addressPanel.setPreferredSize(new Dimension(400, 90));
cityPanel.setPreferredSize(new Dimension(400, 30));
typePanel.setPreferredSize(new Dimension(400, 50));
agreementPanel.setPreferredSize(new Dimension(400, 30));
buttonPanel.setPreferredSize(new Dimension(400, 50));
}
public static void main(String[] args) {
RegistrationForm gui = new RegistrationForm();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(450, 450);
gui.setTitle("Registration");
gui.setLocationRelativeTo(null);
gui.setVisible(true);
}
}
Thanks for helping out. I hope I'll get this done very soon.
Looks like you need to add your root component you made (panel) to this.
public RegistrationForm() {
initElements();
initView();
initFormPanels();
this.add(panel);
}
Change:
panel.add(centerPanel, BorderLayout.CENTER);
To this to see something:
panel.add(centerPanel, BorderLayout.CENTER);
setContentPane(panel);
add this.add(panel) in RegistrationForm constructor.It worked for me.
Related
I have a JTextArea named as txtChat which is used as the chatting area in my chatbot. I have created a JScrollPane scroll = new JScrollPane(txtChat) and added my txtChat inside the JScrollPane. My JTextArea is being put inside a Panel which has BorderLayout, so I have added my scroll to the panel which contains my JTextArea chatPanel.add(scroll, BorderLayout.East). BUT IT IS NOT WORKING! Like when my conversation go longer, the scroll does not appear!
Sorry the code is quite long, so I just pasted the essential parts here.
public class GUI_V3 extends JFrame {
//mainPanel into Frame
private JPanel mainPanel = new JPanel();
//clock component
private JTextField timeF = new JTextField(8);
//Button component
private Box btnBox = Box.createHorizontalBox();
private JButton button1 = new JButton("Add Keywords");
private JButton button2 = new JButton("Help");
//Top menu bar
private JPanel topPanel = new JPanel();
//Typing Area
private JTextField txtEnter = new JTextField();
//Typing Panel
private JPanel typingPanel = new JPanel();
//Chat Area
private JTextArea txtChat = new JTextArea();
private JPanel chatPanel = new JPanel();
//Scroll
private JScrollPane scroll = new JScrollPane(txtChat);
private String name;
private Conversation_V3 convo = new Conversation_V3();
public GUI_V3(){
//Frame attributes
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1000,1000);
this.setVisible(true);
//this.setResizable(false);
this.setLocationRelativeTo(null);
this.setTitle("Welcome to Haidilao");
//clock attributes
timeF.setEditable(false);
timeF.setFont(new Font("Arial",Font.BOLD,48));
timeF.setBackground(new Color(228,224,199));
timeF.setHorizontalAlignment(SwingConstants.RIGHT);
//button attributes
button1.setFont(new Font("Arial",Font.PLAIN,38));
button2.setFont(new Font("Arial",Font.PLAIN,38));
btnBox.add(button1);
btnBox.add(Box.createRigidArea(new Dimension(10,70)));
btnBox.add(button2);
//Add ActionListener to buttons
Button1Handler handlerB1 = new Button1Handler();
button1.addActionListener(handlerB1);
Button2Handler handlerB2 = new Button2Handler();
button2.addActionListener(handlerB2);
//Top menu bar
topPanel.setLayout(new BorderLayout());
topPanel.add(btnBox, BorderLayout.WEST);
topPanel.add(timeF, BorderLayout.EAST);
topPanel.setBackground(new Color(228,224,199));
//Typing Area Attribute
txtEnter.setFont(new Font("DejaVu Sans",Font.PLAIN,30));
typingPanel.setBorder(BorderFactory.createEmptyBorder(10,20,10,20));
typingPanel.setLayout(new BorderLayout());
typingPanel.setBackground(new Color(228,224,199));
typingPanel.add(txtEnter);
//Add action listener for typing area
TypingHandler handlerT = new TypingHandler();
txtEnter.addActionListener(handlerT);
//Chat Area Attribute
txtChat.setEditable(false);
txtChat.setFont(new Font("DejaVu Sans",Font.PLAIN,30));
txtChat.setLineWrap(true);
txtChat.setWrapStyleWord(true);
chatPanel.setBorder(BorderFactory.createEmptyBorder(5,20,10,20));
chatPanel.setLayout(new BorderLayout());
chatPanel.setBackground(new Color(228,224,199));
chatPanel.add(txtChat, BorderLayout.CENTER);
chatPanel.add(scroll, BorderLayout.EAST);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
//mainPanel Layout
mainPanel.setLayout(new BorderLayout());
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.add(typingPanel, BorderLayout.SOUTH);
mainPanel.add(chatPanel, BorderLayout.CENTER);
//Add components to the JFrame
this.add(mainPanel);
//Add actionListener to clock
ClockHandler handlerC = new ClockHandler();
Timer t = new Timer(500, handlerC);
t.start();
//display greetings and ask for name
name = greetings();
addText(botSays("Welcome! " + name + ", you can ask me anything about the menu by providing keywords."));
}
//Action handler for txtEnter
private class TypingHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
//grab input
String input = txtEnter.getText();
//add to chat area
txtChat.append(name + ": " + input + "\n");
//set input field to empty
txtEnter.setText("");
SoundEffect.music();
convo.setInput(input);
addText(botSays(convo.getReply()));
//set the chat area to bottom of scroll
txtChat.setCaretPosition(txtChat.getDocument().getLength());
}
}
Please find a working solution and tweak this as per your requirements.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TestFrame extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestFrame frame = new TestFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TestFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea textArea = new JTextArea();
scrollPane.setViewportView(textArea);
}
}
Hope this will be helpful. :-)
So, I'm brand spankin' new to programming, so thanks in advance for your help. I'm trying to put this base 2 to base 10/base 10 to base 2 calculator I have made into a GUI. For the life of me I can't figure out how to nicely format it. I'm trying to make it look like the following: The two radio buttons on top, the input textfield bellow those, the convert button bellow that, the output field bellow that, and the clear button bellow that. Any ideas on how I can accomplish this?
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.*;
#SuppressWarnings("serial")
public class GUI extends JFrame implements ActionListener
{
private JTextField input;
private JTextField output;
private JRadioButton base2Button;
private JRadioButton base10Button;
private JButton convert;
private JButton clear;
private Container canvas = getContentPane();
private Color GRAY;
public GUI()
{
this.setTitle("Base 10-2 calc");
this.setLayout(new FlowLayout(FlowLayout.LEFT));
//this.setLayout(new GridLayout(2,2));
base2Button = new JRadioButton( "Convert to base 2");
base10Button = new JRadioButton( "Convert to base 10");
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(base2Button);
radioGroup.add(base10Button);
JPanel radioButtonsPanel = new JPanel();
radioButtonsPanel.setLayout( new FlowLayout(FlowLayout.LEFT) );
radioButtonsPanel.add(base2Button);
radioButtonsPanel.add(base10Button);
canvas.add(radioButtonsPanel);
base2Button.setSelected( true );
base10Button.setSelected( true );
input = new JTextField(18);
//input = new JFormattedTextField(20);
canvas.add(input);
output = new JTextField(18);
//output = new JFormattedTextField(20);
canvas.add(output);
convert = new JButton("Convert!");
convert.addActionListener(this);
canvas.add(convert);
clear = new JButton("Clear");
clear.addActionListener(this);
canvas.add(clear);
output.setBackground(GRAY);
output.setEditable(false);
this.setSize(300, 200);
this.setVisible(true);
this.setLocation(99, 101);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
GUI app = new GUI();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if(s.equals("Convert!"))
{
String numS = input.getText();
int numI = Integer.parseInt(numS);
if(base2Button.isSelected())
{
output.setText(Integer.toBinaryString(Integer.valueOf(numI)));
}
if(base10Button.isSelected())
{
output.setText("" + Integer.valueOf(numS,2));
}
}
if(s.equals("Clear"))
{
input.setText("");
output.setText("");
}
}
}
For a simple layout, you could use a GridLayout with one column and then use a bunch of child panels with FlowLayout which align the components based on the available space in a single row. If you want more control, I'd suggest learning about the GridBagLayout manager which is a more flexible version of GridLayout.
public class ExampleGUI {
public ExampleGUI() {
init();
}
private void init() {
JFrame frame = new JFrame();
// Set the frame's layout to a GridLayout with one column
frame.setLayout(new GridLayout(0, 1));
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Child panels, each with FlowLayout(), which aligns the components
// in a single row, until there's no more space
JPanel radioButtonPanel = new JPanel(new FlowLayout());
JRadioButton button1 = new JRadioButton("Option 1");
JRadioButton button2 = new JRadioButton("Option 2");
radioButtonPanel.add(button1);
radioButtonPanel.add(button2);
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel inputLabel = new JLabel("Input: ");
JTextField textField1 = new JTextField(15);
inputPanel.add(inputLabel);
inputPanel.add(textField1);
JPanel convertPanel = new JPanel(new FlowLayout());
JButton convertButton = new JButton("Convert");
convertPanel.add(convertButton);
JPanel outputPanel = new JPanel(new FlowLayout());
JLabel outputLabel = new JLabel("Output: ");
JTextField textField2 = new JTextField(15);
outputPanel.add(outputLabel);
outputPanel.add(textField2);
// Add the child panels to the frame, in order, which all get placed
// in a single column
frame.add(radioButtonPanel);
frame.add(inputPanel);
frame.add(convertPanel);
frame.add(outputPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
ExampleGUI example = new ExampleGUI();
}
}
The end result:
so I have my Main, and this is done inside of it.
JFrame CF = new JFrame();
CF.setLayout(new BorderLayout());
CF.add(new CarGUI(), BorderLayout.NORTH);
// CF.add(new CarGUI(), BorderLayout.SOUTH);
//' South FlowLayout ' here ^
CF.setSize(600,400);
CF.setVisible(true);
In my CarGUI class I have:
public class CarGUI extends JPanel {
private CarTaxManager manager;
private JLabel lpLabel;
private JTextField searchField;
private JButton searchButton;
public CarGUI(){
FlowLayout NorthLayout = new FlowLayout();
//this.setLayout(new FlowLayout());
this.setLayout(NorthLayout);
lpLabel = new JLabel("License Plate");
searchField = new JTextField(10);
searchButton = new JButton("Search");
add(lpLabel);
add(searchField);
add(searchButton);
}
So basically what has to happen here, is I need to make another flow layout, called 'SouthLayout', and in the main, I need to put it to that one. However, the flowlayout has to be done inside CarGUI. I can't seem to get this working.
EDIT:
What it has to look like eventually:
So I'll be needing two FlowLayouts in total. One for the top, and one at the bottom. Neither of them include the TextPane in the middle.
This all comes in a borderLayout in the main.
Thanks in advance!
Sounds like a good candidate for BorderLayout
I've modified your code to get a good start at implementing it, given what you have shown us:
public class CarGUI extends JPanel {
private CarTaxManager manager;
private JLabel lpLabel;
private JTextField searchField;
private JButton searchButton;
public CarGUI(){
setLayout(new BorderLayout());
JPanel north = new JPanel();
north .setLayout(new FlowLayout());
lpLabel = new JLabel("License Plate");
searchField = new JTextField(10);
searchButton = new JButton("Search");
north.add(lpLabel);
north.add(searchField);
north.add(searchButton);
add(north, BorderLayout.NORTH);
JPanel center = new JPanel();
center.setLayout(new FlowLayout());
//TODO add components to center
add(center, BorderLayout.CENTER);
JPanel south= new JPanel();
south.setLayout(new FlowLayout());
//TODO add components to south
add(south, BorderLayout.SOUTH);
}
I think a BorderLayout would work well. The big text field could be in the center and you could have the buttons and menus above and below it. Of course, A simple BoxLayout would also do the job fine. Here is a simple example on how to achieve this with a BorderLayout.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CarGUI extends JFrame {
public CarGUI() {
initGUI();
}
public void initGUI() {
setLayout(new BorderLayout());
setSize(600, 400);
initNorthGUI();
initCenterGUI();
initSouthGUI();
setVisible(true);
}
private void initNorthGUI() {
JPanel northPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
northPanel.add(new JLabel("License Plate"));
northPanel.add(new JTextField(10));
northPanel.add(new JButton("Search"));
add(northPanel, BorderLayout.PAGE_START);
}
private void initCenterGUI() {
JLabel centerPanel = new JLabel("Center");
centerPanel.setBorder(BorderFactory.createLineBorder(Color.black));
add(centerPanel, BorderLayout.CENTER);
}
private void initSouthGUI() {
JPanel southPanel = new JPanel();
southPanel.setLayout(new FlowLayout());
southPanel.add(new JButton("Some Button"));
southPanel.add(new JComboBox());
add(southPanel, BorderLayout.PAGE_END);
}
public static void main(String args[]) {
CarGUI c = new CarGUI();
}
}
Each individual 'JPanel', or any other container, can have its own layout manager. So if you want a different layout in part of your application, add a JPanel with the layout you need.
I am part of team that is creating a test for students to get used to a certain format before they have to take a certification test. The test is four hours long and as I am trying to implement the timer I am seeing unusual patterns.
I expect the timer to start at 4 hours (in HH:MM:SS format) and count down to all zeros, unfortunately it is starting at 11:00:00 and counting down to 07:00:00.
The next problem is the timer has to be shown between two different pages. The actual taking of the exam and a review page. When I toggle back and fourth between the pages the counter starts decrementing by the multiple of times clicked between pages.
Below is my created timer class, take quiz and submit review. The code is not perfect and needs work but I needed a GUI mock up to present.
Any help would be appreciated. Thank you.
TAKE QUIZ
package edu.kings.pexam.student;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class TakeQuiz extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton submit;
private JButton show;
static QuizTimer timer;
/**
* #param args
*/
public static void main(String[] args){
TakeQuiz window = new TakeQuiz();
window.setVisible(true);
}
public TakeQuiz(){
setExtendedState(JFrame.MAXIMIZED_BOTH);
JPanel upperPanel = new JPanel(new GridLayout(2,8));
upperPanel.setPreferredSize(new Dimension(WIDTH,100));
upperPanel.setBackground(Color.lightGray);
this.add(upperPanel,BorderLayout.NORTH);
JPanel lowerPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
lowerPanel.setBackground(Color.white);
this.add(lowerPanel, BorderLayout.CENTER);
Font font = new Font("Dialog",Font.PLAIN,17);
Font buttonFont = new Font("Dialog",Font.PLAIN,13);
Font textButtonFont = new Font("Dialog",Font.PLAIN+Font.BOLD,13);
Font submitButtonFont = new Font("Dialog", Font.PLAIN + Font.BOLD,15);
//adding the questions buttons to the upper panel
JPanel questionPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
questionPanel.setBackground(Color.lightGray);
JButton firstQuestion = new JButton("<<");
firstQuestion.setFont(buttonFont);
questionPanel.add(firstQuestion);
//space to help button line up with text
JPanel spacer1 = new JPanel();
spacer1.setBackground(Color.lightGray);
questionPanel.add(spacer1);
JButton perviousQuestion = new JButton("<");
perviousQuestion.setFont(buttonFont);
questionPanel.add(perviousQuestion);
//space to help button line up with text
JPanel spacer2 = new JPanel();
spacer2.setBackground(Color.lightGray);
questionPanel.add(spacer2);
JButton nextQuestion = new JButton(">");
nextQuestion.setFont(buttonFont);
questionPanel.add(nextQuestion);
//space to help button line up with text
JPanel spacer3 = new JPanel();
spacer3.setBackground(Color.lightGray);
questionPanel.add(spacer3);
JButton lastQuestion = new JButton(">>");
lastQuestion.setFont(buttonFont);
questionPanel.add(lastQuestion);
upperPanel.add(questionPanel);
//adding the goto button to the upper panel
JPanel goToPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
goToPanel.setBackground(Color.lightGray);
JButton goTo = new JButton("Go To");
goTo.setFont(textButtonFont);
goToPanel.add(goTo);
upperPanel.add(goToPanel);
//adding the flag buttons to the upper panel
JPanel flagPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
flagPanel.setBackground(Color.lightGray);
JButton flagP = new JButton("< Flag");
flagP.setFont(textButtonFont);
flagPanel.add(flagP);
JButton flag = new JButton("Flag");
flag.setFont(textButtonFont);
flagPanel.add(flag);
JButton flagN = new JButton("Flag >");
flagN.setFont(textButtonFont);
flagPanel.add(flagN);
upperPanel.add(flagPanel);
//adding help and hide/show timer buttons to the upper panel
JPanel timerPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
timerPanel.setBackground(Color.lightGray);
JButton help = new JButton("Help");
help.setFont(textButtonFont);
timerPanel.add(help);
show = new JButton("Show/Hide Timer");
show.setFont(textButtonFont);
show.addActionListener(this);
timerPanel.add(show);
upperPanel.add(timerPanel);
//adding space panels
JPanel spacePanel1 = new JPanel();
JPanel spacePanel2 = new JPanel();
spacePanel1.setBackground(Color.lightGray);
spacePanel2.setBackground(Color.lightGray);
upperPanel.add(spacePanel1);
upperPanel.add(spacePanel2);
//adding the submit button to the upper panel
JPanel submitPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
submitPanel.setBackground(Color.lightGray);
submit = new JButton("Submit Quiz");
submit.setFont(submitButtonFont);
submit.addActionListener(this);
submitPanel.add(submit);
upperPanel.add(submitPanel);
//adding the question button text to the upper panel
JPanel questionText = new JPanel(new FlowLayout(FlowLayout.LEFT));
questionText.setBackground(Color.lightGray);
JLabel label2 = new JLabel("<html><center>First<br></br>Question</center></html>");
label2.setFont(textButtonFont);
questionText.add(label2);
JLabel label4 = new JLabel("<html><center>Perivous<br></br>Question</center></html>");
label4.setFont(textButtonFont);
questionText.add(label4);
JLabel label6 = new JLabel("<html><center>Next<br></br>Question</center></html>");
label6.setFont(textButtonFont);
questionText.add(label6);
JLabel label8 = new JLabel("<html><center>Last<br></br>Question</center></html>");
label8.setFont(textButtonFont);
questionText.add(label8);
upperPanel.add(questionText);
//adding text box for go to button
JPanel textGoTo = new JPanel(new FlowLayout(FlowLayout.CENTER));
textGoTo.setBackground(Color.lightGray);
JPanel upper10 = new JPanel();
upper10.setBackground(Color.lightGray);
JTextField goToText = new JTextField("1",2);
JLabel label10 = new JLabel("/25");
label10.setFont(font);
upper10.add(goToText,BorderLayout.CENTER);
upper10.add(label10,BorderLayout.CENTER);
textGoTo.add(upper10);
upperPanel.add(textGoTo);
//adding spacer to the upper panel
JPanel spacePanel3 = new JPanel();
spacePanel3.setBackground(Color.lightGray);
upperPanel.add(spacePanel3);
//adding the timer to the upper panel
JPanel timePanel = new JPanel();
timePanel.setBackground(Color.lightGray);
timer = new QuizTimer();
timer.start();
JPanel upper20 = new JPanel();
upper20.setBackground(Color.lightGray);
upper20.add(timer.getTimeLabel(),BorderLayout.CENTER);
timePanel.add(upper20);
upperPanel.add(timePanel);
//adding two more space panels
JPanel spacePanel4 = new JPanel();
JPanel spacePanel5 = new JPanel();
spacePanel4.setBackground(Color.lightGray);
spacePanel5.setBackground(Color.lightGray);
upperPanel.add(spacePanel4);
upperPanel.add(spacePanel5);
//adding the questions to the lower panel
JPanel lower1 = new JPanel(new GridLayout(4,1));
lower1.setBackground(Color.white);
JLabel question = new JLabel("<html>The parents of a 16-year-old swimmer contact an athletic trainer seeking nutritional advice for the athlete's pre-event<br><\bmeal. What recommendation should the athletic trainer share share with the parents regrading ideal pre-event meals?</html>");
question.setFont(new Font("Dialog", Font.PLAIN+Font.BOLD, 18));
JPanel answer = new JPanel(new GridLayout(6,1));
answer.setBackground(Color.white);
JLabel type = new JLabel("Choose all that apply.");
type.setFont(new Font("Dialog", Font.PLAIN+Font.BOLD+Font.ITALIC, 20));
JPanel answerA = new JPanel(new FlowLayout(FlowLayout.LEFT));
answerA.setBackground(Color.white);
JRadioButton a = new JRadioButton();
a.setBackground(Color.white);
a.setSize(25,25);
JLabel aFill = new JLabel("Include foods high in carbohydrates, high in proteins , and low in fats");
aFill.setFont(font);
answerA.add(a);
answerA.add(aFill);
JPanel answerB = new JPanel(new FlowLayout(FlowLayout.LEFT));
answerB.setBackground(Color.white);
JRadioButton b = new JRadioButton();
b.setBackground(Color.white);
b.setSize(25,25);
JLabel bFill = new JLabel("Prepare meals without diuretics foods");
bFill.setFont(font);
answerB.add(b);
answerB.add(bFill);
JPanel answerC = new JPanel(new FlowLayout(FlowLayout.LEFT));
answerC.setBackground(Color.white);
JRadioButton c = new JRadioButton();
c.setBackground(Color.white);
c.setSize(25,25);
JLabel cFill = new JLabel("Prepare meals for eating four hours prior to the competition");
cFill.setFont(font);
answerC.add(c);
answerC.add(cFill);
JPanel answerD = new JPanel(new FlowLayout(FlowLayout.LEFT));
answerD.setBackground(Color.white);
JRadioButton d = new JRadioButton();
d.setBackground(Color.white);
d.setSize(25,25);
JLabel dFill = new JLabel("Prepare meals with food that delay gastric emptying");
dFill.setFont(font);
answerD.add(d);
answerD.add(dFill);
JPanel record = new JPanel(new FlowLayout(FlowLayout.LEFT));
record.setBackground(Color.lightGray);
JLabel unanswered = new JLabel("Unanswered: ");
unanswered.setFont(font);
record.add(unanswered);
JLabel unansweredNumber = new JLabel("25");
unansweredNumber.setFont(font);
unansweredNumber.setForeground(Color.blue);
record.add(unansweredNumber);
JLabel space1 = new JLabel();
record.add(space1);
JLabel answered = new JLabel("Answered: ");
answered.setFont(font);
record.add(answered);
JLabel answeredNumber = new JLabel("0");
answeredNumber.setFont(font);
answeredNumber.setForeground(Color.blue);
record.add(answeredNumber);
JLabel space2 = new JLabel();
record.add(space2);
JLabel flagged = new JLabel("Flagged: ");
flagged.setFont(font);
record.add(flagged);
JLabel flaggedNumber = new JLabel("0");
flaggedNumber.setFont(font);
flaggedNumber.setForeground(Color.blue);
record.add(flaggedNumber);
answer.add(type);
answer.add(answerA);
answer.add(answerB);
answer.add(answerC);
answer.add(answerD);
answer.add(record);
lower1.add(question);
lower1.add(answer);
lowerPanel.add(lower1);
getContentPane().setBackground(Color.white);
upperPanel.setVisible(true);
lowerPanel.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == submit){
SubmitReview reviewScreen = new SubmitReview();
this.setVisible(false);
reviewScreen.setVisible(true);
}else if(e.getSource() == show){
if(timer.getTimeLabel().isVisible() == true){
timer.getTimeLabel().setVisible(false);
}else{
timer.getTimeLabel().setVisible(true);
}
}
}
}
FINAL SUBMIT
package edu.kings.pexam.student;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SubmitReview extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton hideTimerButton;
private JButton showTimerButton;
private JComboBox<String> languageBox;
private JButton returnToQuizButton;
private JButton endQuizButton;
private JTextField textEnter;
static QuizTimer timer = TakeQuiz.timer;
/**
* Runs the program to produce the screen for submission review.
* #param args
*/
public static void main(String[] args){
SubmitReview window = new SubmitReview();
//sets the window visible
window.setVisible(true);
}
public SubmitReview(){
//Extends the screen to maximum size
setExtendedState(JFrame.MAXIMIZED_BOTH);
//Creates a panel that will keep items pushed to the right.
JPanel leftPanel = new JPanel();
leftPanel.setPreferredSize(new Dimension(200,HEIGHT));
leftPanel.setBackground(Color.white);
this.add(leftPanel,BorderLayout.WEST);
//Panel where everything on page will go.
JPanel rightPanel = new JPanel(new GridLayout(10,1));
rightPanel.setBackground(Color.white);
this.add(rightPanel, BorderLayout.CENTER);
//font for the text
Font textFont = new Font("Dialog",Font.PLAIN,15);
//First panel in the grid. Grid moves from top to bottom.
JPanel panel0 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panel0.setBackground(Color.white);
//hide timer button, visible when timer is shown.
hideTimerButton = new JButton("Hide Timer");
hideTimerButton.setBackground(Color.lightGray);
Dimension hideTimerDimension = new Dimension(100,25);
hideTimerButton.setSize(hideTimerDimension);
hideTimerButton.setMinimumSize(hideTimerDimension);
hideTimerButton.setMaximumSize(hideTimerDimension);
hideTimerButton.setPreferredSize(hideTimerDimension);
hideTimerButton.setVisible(true);
//show timer button, visible when timer is not shown.
showTimerButton = new JButton("Show Timer");
showTimerButton.setBackground(Color.lightGray);
Dimension showTimerDimension = new Dimension(125, 25);
showTimerButton.setSize(showTimerDimension);
showTimerButton.setMinimumSize(showTimerDimension);
showTimerButton.setMaximumSize(showTimerDimension);
showTimerButton.setPreferredSize(showTimerDimension);
showTimerButton.setVisible(false);
//creates functionality for the show and hide timer buttons
hideTimerButton.addActionListener(this);
showTimerButton.addActionListener(this);
panel0.add(timer.getTimeLabel());
panel0.add(hideTimerButton);
panel0.add(showTimerButton);
rightPanel.add(panel0);
//Second panel in the grid.
JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel1.setBackground(Color.white);
//Splits this panel into a grid
JPanel grid = new JPanel(new GridLayout(2,1));
//A Panel to hold the language drop down menu
JPanel languagePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
languagePanel.setBackground(Color.white);
//Creates a combo box of languages (drop down menu)
String[] languages = {"English", "Spanish", "French", "Portuguese" };
languageBox = new JComboBox<String>(languages);
languageBox.setBackground(Color.white);
languageBox.addActionListener(this);
languagePanel.add(languageBox);
//Text under the combo box
JPanel textPanel = new JPanel();
JLabel text = new JLabel("Do you want to end your exam now?");
Font font = new Font("Dialog",Font.PLAIN,17);
text.setFont(font);
textPanel.setBackground(Color.white);
textPanel.add(text);
grid.add(languagePanel);
grid.add(textPanel);
//Stop sign picture
File stopSign = new File("resources/stop_sign.png");
ImageIcon stopSignIcon = null;
try {
stopSignIcon = new ImageIcon(ImageIO.read(stopSign));
}
catch (IOException e) {
System.out.println("Caught exception:" + e);
}
JLabel stopLabel = new JLabel();
stopLabel.setIcon(stopSignIcon);
stopLabel.setBackground(Color.white);
stopLabel.setBorder(null);
panel1.add(grid);
panel1.add(stopLabel);
rightPanel.add(panel1);
//third panel in the grid
JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel2.setBackground(Color.white);
//splits the panel into a grid
JPanel textArea2 = new JPanel(new GridLayout(2,1));
textArea2.setBackground(Color.white);
JPanel warningText1 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
warningText1.setBackground(Color.white);
JLabel warningText1Point = new JLabel("<html><li>You left the following questions unanswered. If you end your exam now,<b> you lose the chance to answer these questions.</b></html>");
warningText1Point.setFont(textFont);
warningText1.add(warningText1Point);
JPanel breakPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
breakPanel.setBackground(Color.white);
JLabel space = new JLabel("<html><t> </t></html>");
breakPanel.add(space);
//adds FAKE question buttons to the panel
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
buttonPanel.setBackground(Color.white);
JButton one = new JButton("1");
JButton two = new JButton("5");
JButton three = new JButton("12");
one.setBackground(Color.lightGray);
two.setBackground(Color.lightGray);
three.setBackground(Color.lightGray);
buttonPanel.add(one);
buttonPanel.add(two);
buttonPanel.add(three);
breakPanel.add(buttonPanel);
textArea2.add(warningText1);
textArea2.add(breakPanel);
panel2.add(textArea2);
rightPanel.add(panel2);
//fourth panel in the grid
JPanel panel3 = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel3.setBackground(Color.white);
JPanel textArea3 = new JPanel(new GridLayout(2,1));
textArea3.setBackground(Color.white);
JPanel warningText3 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
warningText3.setBackground(Color.white);
JLabel warningText3Point = new JLabel("<html><li>You marked the following questions for later review. If you end your exam now, <b>you lose the chance to review these marked questions.</b></html>");
textArea3.setBackground(Color.white);
warningText3Point.setFont(textFont);
JPanel breakPanel3 = new JPanel(new FlowLayout(FlowLayout.LEFT));
breakPanel3.setBackground(Color.white);
JLabel space3 = new JLabel("<html><t> </t></html>");
breakPanel3.add(space3);
JPanel buttonPanel3 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
buttonPanel3.setBackground(Color.white);
JButton four = new JButton("4");
JButton five = new JButton("9");
JButton six = new JButton("20");
four.setBackground(Color.lightGray);
five.setBackground(Color.lightGray);
six.setBackground(Color.lightGray);
buttonPanel3.add(four);
buttonPanel3.add(five);
buttonPanel3.add(six);
breakPanel3.add(buttonPanel3);
textArea3.add(warningText3Point);
textArea3.add(warningText3);
textArea3.add(breakPanel3);
panel3.add(textArea3);
rightPanel.add(panel3);
//fifth panel in the grid
JPanel panel4 = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel4.setBackground(Color.white);
JPanel grid4 = new JPanel(new GridLayout(2,1));
grid4.setBackground(Color.white);
JPanel border4 = new JPanel(new GridLayout(1,2));
border4.setBackground(Color.white);
JPanel spacer4 = new JPanel();
spacer4.setBackground(Color.white);
JPanel button4 = new JPanel();
button4.setBackground(Color.white);
returnToQuizButton = new JButton("No. Return to the Quiz" );
returnToQuizButton.setBackground(Color.lightGray);
returnToQuizButton.addActionListener(this);
button4.add(returnToQuizButton,BorderLayout.SOUTH);
JPanel textPanel4 = new JPanel(new FlowLayout(FlowLayout.LEFT));
textPanel4.setBackground(Color.white);
JLabel label4 = new JLabel("<html><li>You still have time remaining.</b></html>");
label4.setFont(textFont);
textPanel4.add(label4);
border4.add(spacer4);
border4.add(button4);
grid4.add(textPanel4);
grid4.add(border4);
panel4.add(grid4);
rightPanel.add(panel4);
//sixth panel in the grid
JPanel panel5 = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel5.setBackground(Color.white);
JPanel textPanel5 = new JPanel(new FlowLayout(FlowLayout.LEFT));
textPanel5.setBackground(Color.white);
JLabel text5 = new JLabel("<html><li>If you end your exam now,<b> you cannot return to the exam.</b></html>");
text5.setFont(textFont);
textPanel5.add(text5);
panel5.add(textPanel5);
rightPanel.add(panel5);
//seventh panel in the grid
JPanel panel6 = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel6.setBackground(Color.white);
JPanel textPanel6 = new JPanel(new FlowLayout(FlowLayout.LEFT));
textPanel6.setBackground(Color.white);
JLabel text6 = new JLabel("If you are ready to end the multiple-choice exam now, type the words 'I understand' in the box below.");
text6.setFont(textFont);
textPanel6.add(text6);
panel6.add(textPanel6);
rightPanel.add(panel6);
//eight panel in the grid
JPanel panel7 = new JPanel(new FlowLayout(FlowLayout.CENTER));
panel7.setBackground(Color.white);
textEnter = new JTextField("Type 'I understand' here.");
textEnter.setFont(textFont);
textEnter.setColumns(13);
//clears box on click of mouse
textEnter.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
textEnter.setText("");
}
});
textEnter.addActionListener(this);
JPanel textHolder = new JPanel();
textHolder.setBackground(Color.white);
textHolder.add(textEnter,BorderLayout.CENTER);
panel7.add(textHolder);
rightPanel.add(panel7);
//ninth panel in the grid
JPanel panel8 = new JPanel(new FlowLayout(FlowLayout.CENTER));
panel8.setBackground(Color.white);
endQuizButton = new JButton("Yes. End the Quiz Now");
endQuizButton.setBackground(Color.lightGray);
endQuizButton.addActionListener(this);
endQuizButton.setEnabled(false);
JPanel button8 = new JPanel();
button8.setBackground(Color.white);
button8.add(endQuizButton, BorderLayout.CENTER);
panel8.add(button8);
rightPanel.add(panel8);
getContentPane().setBackground(Color.white);
leftPanel.setVisible(true);
rightPanel.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
String text = textEnter.getText();
if(text.equals("I understand")){
endQuizButton.setEnabled(true);
}
if(e.getSource() == hideTimerButton){
hideTimerButton.setVisible(false);
timer.getTimeLabel().setVisible(false);
showTimerButton.setVisible(true);
}else if(e.getSource() == showTimerButton){
showTimerButton.setVisible(false);
hideTimerButton.setVisible(true);
timer.getTimeLabel().setVisible(true);
}else if(e.getSource() == returnToQuizButton){
TakeQuiz quizScreen = new TakeQuiz();
this.setVisible(false);
quizScreen.setVisible(true);
}else if(e.getSource() == endQuizButton){
int response = JOptionPane.showConfirmDialog(null, "Are you sure you want to submit your quiz for grading?","Select an Option", JOptionPane.YES_NO_OPTION);
if(response == JOptionPane.YES_OPTION){
JOptionPane.showMessageDialog(null, "Your grade on this quiz is: 85");
System.exit(0);
}
}
}
}
QUIZ TIMER
package edu.kings.pexam.student;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.Timer;
public class QuizTimer {
private static double time = 1.44*Math.pow(10,7);
private SimpleDateFormat setTime = new SimpleDateFormat("hh:mm:ss");
private JLabel timeLabel;
private Timer countDown;
public QuizTimer(){
countDown = new Timer(1000, new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (time >= 0) {
timeLabel.setText(setTime.format(time));
time = time-1000;
}else{
JOptionPane.showMessageDialog(null, "Your quiz has been automatically submitted for grading.", "Out of Time", JOptionPane.OK_OPTION);
System.exit(0);
}
}
});
timeLabel = new JLabel();
timeLabel.setFont( new Font("Dialog", Font.PLAIN + Font.BOLD,24));
timeLabel.setVisible(true);
}
public JLabel getTimeLabel(){
return timeLabel;
}
public void start(){
countDown.start();
}
}
The first problem (11:00:00 to 7:00:00) probably has to do with your timezone.
The second one may (from the top of my head) have to do with time field being static.
In any way, I'd be curious why it is static. Seems that this logic would break if you have two timers.
(P.S. Please vote.)
How do I get the JTextField to have a fixed height when the Frame is maximized? I want it to look sort of similar to the Skype application on Ubuntu.
private JTextField username;
private JPasswordField password;
private JLabel usernamelabel;
private JLabel passwordlabel;
public LoginPanel(){
setSize(200,200);
setLayout(new GridLayout(4,4));
setBackground(new Color(85,153,187));
setBorder(BorderFactory.createEmptyBorder(70, 70, 70, 70));
username = new JTextField();
password = new JPasswordField();
usernamelabel= new JLabel("Username");
passwordlabel= new JLabel("Password");
username.setBounds(5, 5, 100, 100);
username.setPreferredSize(new Dimension(80,20));
password.setPreferredSize(new Dimension(80,20));
add(usernamelabel);
add(username);
add(passwordlabel);
add(password);
Don't use a layout other than GridLayout or put the text field in another panel that has a FlowLayout that sits inside of your GridLayout.
I think this solves your problem.
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
JFrame failFrame = new JFrame();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(0, 4));
JPanel leftTextFieldPanel = new JPanel();
leftTextFieldPanel.setLayout(new FlowLayout());
JPanel rightTextFieldPanel = new JPanel();
rightTextFieldPanel.setLayout(new FlowLayout());
JTextField leftTextField = new JTextField();
leftTextField.setPreferredSize(new Dimension(150,20));
JTextField rightTextField = new JTextField();
rightTextField.setPreferredSize(new Dimension(150,20));
leftTextFieldPanel.add(leftTextField);
mainPanel.add(leftTextFieldPanel);
rightTextFieldPanel.add(rightTextField);
mainPanel.add(rightTextFieldPanel);
mainPanel.add(new JPanel());
mainPanel.add(rightTextFieldPanel);
mainPanel.add(new JPanel());
failFrame.add(mainPanel);
failFrame.setSize(600, 400);
failFrame.setLocationRelativeTo(null);
failFrame.setVisible(true);
}
}
I used nested Layouts. On the Top is your GridLayout and the textfields are in a FlowLayout which are added on the gridLayout panel. So the textfields are no longer stretched.
You can refer to here.
The setMaximumSize method can be found in JComponent and the JTextField gets to use this method from JComponent.
EDIT: However, it seems its not a good practice to hardcode the size of the JTextField particularly when you are running it on multiple platforms as you may face issues with the font-size.
Thanks for all the help guys, hope this helps out others in the future. I got the visual look that I was looking for.
private JTextField username;
private JPasswordField password;
private JPanel [] login = {new JPanel(), new JPanel()};
private JLabel usernamelabel;
private JLabel passwordlabel;
public LoginPanel(){
setSize(200,200);
setBackground(new Color(85,153,187));
setBorder(BorderFactory.createEmptyBorder(70, 70, 70, 70));
username = new JTextField();
password = new JPasswordField();
usernamelabel= new JLabel("Username");
passwordlabel= new JLabel("Password");
login[0].add(usernamelabel);
login[0].add(username);
login[1].add(passwordlabel);
login[1].add(password);
for(JPanel p : login){
p.setBackground(new Color(85,153,187));
this.add(p);
}
username.setBounds(5, 5, 100, 100);
username.setPreferredSize(new Dimension(120,20));
password.setPreferredSize(new Dimension(120,20));
}
In a pinch, doing
tf.setMaximumSize(tf.getMinimumSize())
will keep it constant size and platform neutral.