How to control where in my window or JFrame panels appear - java

this has seriously been the biggest issue in my code. I just want to create a simple pizza order taker using multiple panels. I want to be able to dictate the specific area each panel is located. Can someone please just pretend I'm a complete idiot and help me point this out?
I've attached my code as well as an image of how it looks so far. I want to be able to place individual segments like getting the user's information, choosing pizza size, then toppings, then a section where I will display the receipt with all of the order total.
I can do the calculations and take in values, I just need to figure out the appearance.
import javax.swing.*;
import java.awt.*;
public class PIZZA extends JFrame {
Container window = getContentPane();
ButtonGroup ordertype;
JRadioButton delivery, takeout;
JRadioButton small, medium, large;
JLabel fname, phonenum, zipcode;
JTextField ufname, uphonenum, uzipcode;
JPanel userinfoinput;
JPanel delivery_type;
JPanel userinfolabel;
JButton start;
BoxLayout userbox, labelbox, deliverybox;
ImageIcon starticon = new ImageIcon("start.png");
public PIZZA() {
}
public static void main(String[] args){
PIZZA frame = new PIZZA();
new PIZZA();
frame.setSize(new Dimension(600,600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("KRUSTY KRAB PIZZA");
frame.deliverymethod();
frame.getuserinfo();
frame.userinfolabels();
frame.getpizzasize();
frame.toppings_meat();
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
private void deliverymethod(){
delivery_type = new JPanel();
ordertype = new ButtonGroup();
delivery = new JRadioButton("Delivery (Currently Unavailable)");
delivery.setEnabled(false);
takeout = new JRadioButton("Take Out");
ordertype.add(takeout);
ordertype.add(delivery);
delivery_type.add(takeout);
delivery_type.add(delivery);
delivery_type.setSize(100,100);
window.add(delivery_type,BorderLayout.NORTH);
}
private void getuserinfo(){
userinfoinput = new JPanel();
//start = new JButton("Start", starticon);
//start.setLayout(null);
ufname = new JTextField(12);
uphonenum = new JTextField(12);
uzipcode = new JTextField(12);
userinfoinput.add(ufname);
userinfoinput.add(uphonenum);
userinfoinput.add(uzipcode);
//userinfoinput.add(start);
GridLayout lay = new GridLayout(3,1);
userinfoinput.setLayout(lay);
window.add(userinfoinput, BorderLayout.CENTER);
}
private void userinfolabels(){
userinfolabel = new JPanel();
fname = new JLabel("First Name");
phonenum = new JLabel("Phone Number");
zipcode = new JLabel("Zip Code");
userinfolabel.add(fname);
userinfolabel.add(zipcode);
userinfolabel.add(phonenum);
labelbox = new BoxLayout(userinfolabel, BoxLayout.Y_AXIS);
GridLayout label = new GridLayout(3,1);
userinfolabel.setLayout(label);
window.add(userinfolabel, BorderLayout.CENTER);
}
private void getpizzasize(){
JPanel pizzasize = new JPanel();
ButtonGroup size = new ButtonGroup();
small = new JRadioButton("Small");
medium = new JRadioButton("Medium");
large = new JRadioButton("Large");
size.add(small);
size.add(medium);
size.add(large);
pizzasize.add(small);
pizzasize.add(medium);
pizzasize.add(large);
pizzasize.setLayout(new FlowLayout());
pizzasize.setSize(100,100);
window.add(pizzasize, BorderLayout.SOUTH);
}
private void toppings_meat(){
JPanel meat = new JPanel();
meat.setLayout(new BoxLayout(meat, BoxLayout.Y_AXIS));
JCheckBox pepperoni = new JCheckBox("Pepperoni");
JCheckBox meatball = new JCheckBox("Meatball");
JCheckBox chicken = new JCheckBox("Grilled Chicken");
JCheckBox sausage = new JCheckBox("Italian Sausage");
JCheckBox bacon = new JCheckBox("Bacon");
meat.add(pepperoni);
meat.add(meatball);
meat.add(chicken);
meat.add(sausage);
meat.add(bacon);
window.add(meat);
}
}

This pizza GUI uses several Swing layout managers in different JPanels.
The main layout managers that I want to talk about are the JFrame BorderLayout and the input form GridBagLayout.
A BorderLayout is rather flexible in that you can put Swing components in various locations. The JPanels I created for this GUI are in the BEFORE_FIRST_LINE, CENTER, AFTER_LAST_LINE, and AFTER_LINE_ENDS positions of the BorderLayout.
The input form uses a GridBagLayout to position the JLabels and the input JTextFields in a column. The GridBagLayout is more flexible than a GridLayout because the grid cells don't have to be the same size in a GridBagLayout.
The Oracle Swing tutorial A Visual Guide to Layout Managers shows the different Swin layout managers, and how to use them.
Here's the code I used to create the pizza GUI. I created each subordinate JPanel in a separate method. All of the JFrame code is in the run method. Separating different parts of the GUI allows me to focus on one part of the GUI at a time. I can test each JPanel method separately.
I create the Swing components from left to right, top to bottom within a JPanel. This allows me to visually verify that I've included all the appropriate methods for a component. This also allows me to zero in on any component that isn't correct.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class PizzaOrdering implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new PizzaOrdering());
}
#Override
public void run() {
JFrame frame = new JFrame("KRUSTY KRAB PIZZA");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(getDeliveryMethodPanel(),
BorderLayout.BEFORE_FIRST_LINE);
frame.add(getUserInformationPanel(),
BorderLayout.CENTER);
frame.add(getPizzaSizePanel(),
BorderLayout.AFTER_LAST_LINE);
frame.add(getMeatToppingsPanel(),
BorderLayout.AFTER_LINE_ENDS);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel getDeliveryMethodPanel() {
JPanel deliveryMethodPanel = new JPanel(new FlowLayout());
ButtonGroup orderTypeGroup = new ButtonGroup();
JRadioButton takeoutRadioButton =
new JRadioButton("Take Out");
orderTypeGroup.add(takeoutRadioButton);
deliveryMethodPanel.add(takeoutRadioButton);
JRadioButton deliveryRadioButton =
new JRadioButton("Delivery (Currently Unavailable)");
deliveryRadioButton.setEnabled(false);
orderTypeGroup.add(deliveryRadioButton);
deliveryMethodPanel.add(deliveryRadioButton);
return deliveryMethodPanel;
}
private JPanel getUserInformationPanel() {
JPanel userInformationPanel = new JPanel(new GridBagLayout());
userInformationPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.weightx = 1d;
JLabel nameLabel = new JLabel("First Name:");
userInformationPanel.add(nameLabel, gbc);
gbc.gridx++;
JTextField userNameField = new JTextField(20);
userInformationPanel.add(userNameField, gbc);
gbc.gridx = 0;
gbc.gridy++;
JLabel phoneNumberLabel = new JLabel("Phone Number:");
userInformationPanel.add(phoneNumberLabel, gbc);
gbc.gridx++;
JTextField userPhoneNumberField = new JTextField(20);
userInformationPanel.add(userPhoneNumberField, gbc);
gbc.gridx = 0;
gbc.gridy++;
JLabel zipCodeLabel = new JLabel("Zip Code:");
userInformationPanel.add(zipCodeLabel, gbc);
gbc.gridx++;
JTextField userZipCodeField = new JTextField(20);
userInformationPanel.add(userZipCodeField, gbc);
return userInformationPanel;
}
private JPanel getPizzaSizePanel() {
JPanel pizzaSizePanel = new JPanel(new FlowLayout());
ButtonGroup sizeGroup = new ButtonGroup();
JRadioButton smallRadioButton = new JRadioButton("Small");
sizeGroup.add(smallRadioButton);
pizzaSizePanel.add(smallRadioButton);
JRadioButton mediumRadioButton = new JRadioButton("Medium");
sizeGroup.add(mediumRadioButton);
pizzaSizePanel.add(mediumRadioButton);
JRadioButton largeRadioButton = new JRadioButton("Large");
sizeGroup.add(largeRadioButton);
pizzaSizePanel.add(largeRadioButton);
return pizzaSizePanel;
}
private JPanel getMeatToppingsPanel() {
JPanel meatToppingsPanel = new JPanel();
meatToppingsPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
meatToppingsPanel.setLayout(new BoxLayout(
meatToppingsPanel, BoxLayout.Y_AXIS));
JCheckBox pepperoniCheckBox = new JCheckBox("Pepperoni");
meatToppingsPanel.add(pepperoniCheckBox);
JCheckBox meatballCheckBox = new JCheckBox("Meatball");
meatToppingsPanel.add(meatballCheckBox);
JCheckBox chickenCheckBox = new JCheckBox("Grilled Chicken");
meatToppingsPanel.add(chickenCheckBox);
JCheckBox sausageCheckBox = new JCheckBox("Italian Sausage");
meatToppingsPanel.add(sausageCheckBox);
JCheckBox baconCheckBox = new JCheckBox("Bacon");
meatToppingsPanel.add(baconCheckBox);
return meatToppingsPanel;
}
}

Related

Vertically center GridBagLayout like BoxLayout

I am trying to center components using a GridBagLayout in the same manner that a Box centers components when you use Box.createVerticalGlue(). I initially did use a vertical Box:
Box box = Box.createVerticalBox();
box.add(Box.createVerticalGlue());
box.add(add);
box.add(remove);
box.add(edit);
box.add(Box.createVerticalGlue());
JPanel internalPanel = new JPanel(new BorderLayout());
internalPanel.add(keywordsScrollPane, BorderLayout.CENTER);
internalPanel.add(box, BorderLayout.EAST);
But as you can see, it looks sloppy because my buttons are different sizes:
I decided to switch to GridBagLayout so I can utilize GridBagConstraints.fill. This approach fixes my button width issue, but I cannot figure out how to vertically center the buttons. I changed the grid size and placed the buttons in the middle three rows, but the buttons were still appearing at the top of the panel. I tried making use of GridBagConstraints.anchor and GridBagConstraints.weighty as well. The latter almost worked, but there are very large margins between the buttons:
I am looking for the buttons to be grouped together as they were in my Box approach. How can I achieve this with a GridBadLayout?
I am using a class I created called ConstraintsBuilder which works exactly as you would expect. It's for creating GridBagContraints with nice one-liners. Here is all the (relevant) code for your viewing pleasure:
public class KeywordsDialog extends JDialog implements ActionListener, ListSelectionListener {
private JList<String> keywords;
private JScrollPane keywordsScrollPane;
private JButton add;
private JButton remove;
private JButton edit;
private Set<String> keywordsList;
public KeywordsDialog(Window parent, Collection<String> keywordsList) {
super(parent);
this.keywordsList = keywordsList == null ? new HashSet<String>() : new HashSet<String>(keywordsList);
if (keywordsList != null && !keywordsList.isEmpty()) {
this.keywords = new JList<String>(toListModel(keywordsList));
} else {
this.keywords = new JList<String>(new DefaultListModel<String>());
}
this.keywordsScrollPane = new JScrollPane(keywords);
this.add = new JButton("Add");
this.remove = new JButton("Remove");
this.edit = new JButton("Edit");
this.edit.setEnabled(false);
this.add.setEnabled(false);
ConstraintsBuilder builder = LayoutUtils.gridBagConstraintsBuilder();
JPanel internalPanel = new JPanel(new GridBagLayout());
internalPanel.add(this.keywordsScrollPane, builder.gridX(0).gridY(0).gridHeight(3).margins(0, 0, 0, 5)
.fill(GridBagConstraints.BOTH).weightX(1D).weightY(1D).build());
internalPanel.add(this.add,
builder.reset().gridX(1).gridY(0).fill(GridBagConstraints.HORIZONTAL).weightX(1D).weightY(1D).build());
internalPanel.add(this.remove,
builder.reset().gridX(1).gridY(1).fill(GridBagConstraints.HORIZONTAL).weightX(1D).weightY(1D).build());
internalPanel.add(this.edit,
builder.reset().gridX(1).gridY(2).fill(GridBagConstraints.HORIZONTAL).weightX(1D).weightY(1D).build());
this.keywords.setBorder(BorderFactory.createTitledBorder("Keywords"));
internalPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
this.setLayout(new BorderLayout());
this.add(internalPanel, BorderLayout.CENTER);
Dimension screen = GuiHelper.getScreenSize(parent);
this.setSize((int) (screen.getWidth() / 4), (int) (screen.getHeight() / 3));
this.setLocationRelativeTo(parent);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
// ...
}
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the How to Use GridBagLayout section.
The easiest way to create this GUI is to treat the JTextArea separately from the JButton area.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class ExampleGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new ExampleGUI());
}
#Override
public void run() {
JFrame frame = new JFrame("Example GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTextArea(), BorderLayout.CENTER);
frame.add(createButtonPanel(), BorderLayout.EAST);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JScrollPane createTextArea() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JTextArea textArea = new JTextArea(10, 30);
textArea.setText("keyword");
panel.add(textArea, BorderLayout.CENTER);
return new JScrollPane(panel);
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(0, 5, 5, 5);
gbc.gridy = 0;
JButton button = new JButton("Add");
panel.add(button, gbc);
gbc.gridy++;
button = new JButton("Remove");
panel.add(button, gbc);
gbc.gridy++;
button = new JButton("Edit");
panel.add(button, gbc);
return panel;
}
}
I would make the GUI simpler. Put the three buttons into a JPanel that uses a GridLayout, one declared to use 1 column and variable number of rows, one with a desired spacing between buttons, here, 5 pixels: JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 5, 5)); and then put that JPanel into the center of a another JPanel, and GridBagLayout without constraints works well for this:
JPanel sidePanel = new JPanel(new GridBagLayout());
sidePanel.add(buttonPanel);
and put that JPanel into the right side of a border layout using JPanel. For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FooSwing01 extends JPanel {
public FooSwing01() {
JTextArea textArea = new JTextArea(20, 50);
JScrollPane scrollPane = new JScrollPane(textArea);
JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 5, 5));
int maxButtons = 3;
for (int i = 0; i < maxButtons; i++) {
buttonPanel.add(new JButton("Button " + (i + 1)));
}
JPanel sidePanel = new JPanel(new GridBagLayout());
sidePanel.add(buttonPanel);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BorderLayout(5, 5));
add(scrollPane);
add(sidePanel, BorderLayout.LINE_END);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("GUI");
frame.add(new FooSwing01());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}

java GUI layout suggestion

public class AFS {
public JPanel afs(final Fields input){
JPanel titlePanel = new JPanel();
//Title fields
JLabel afs = new JLabel("Statement", Label.LEFT);
Label mm = new Label("month ", Label.LEFT);
Label my = new Label("Year ", Label.LEFT);
//first line
titlePanel.add(afs);
titlePanel.add(mm);
titlePanel.add(input.MENTRY);
titlePanel.add(my);
titlePanel.add(input.YENTRY);
titlePanel.setPreferredSize(null);
//Left Panels
JPanel sb = new JPanel();
JPanel entry = new JPanel();
entry.setLayout(new BoxLayout(entry, BoxLayout.Y_AXIS));
entry.setAlignmentX(Component.LEFT_ALIGNMENT);
entry.add(new Label("Service "));
entry.add(input.s);
entry.add(new Label("Amount "));
entry.add(input.a);
entry.add(new Label("Counter "));
entry.add(input.o);
entry.add(new Label("Division "));
entry.add(input.d);
sb.add(entry);
JPanel holderPanel = new JPanel();
holderPanel.setLayout(new BoxLayout(holderPanel, BoxLayout.Y_AXIS));
holderPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
holderPanel.add(titlePanel);
holderPanel.add(sb);
JButton start = new JButton("Save Current");
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ScriptAction action = new ScriptAction();
action.saveAll(input,1);
}
});
holderPanel.add(start);
return holderPanel;
}
I have a short version of what looks like above code.
The current layout looks like this:
But I want the layout look like (paint edited).
I have tried swap using gridLayout for the entry and it will display 2 rows but gridlayout will still align everything in the center (include the title and the header). Furthermore the button span would be across the entire bottom section. I was wondering if there are any suggested way to do this?
You would need to use a combination of layout managers to achieve the desired output:
Before resize / After resize
In this case there are 3 main parts:
Top pane (Uses Box to align some text on the left and some on the right)
Middle pane (Uses GridBagLayout to position the components as in the image, maybe GridLayout with proper insets might work as well)
Bottom pane (Uses default JPanel's layout: FlowLayout)
The top pane uses 2 JPanels as well, the first one for the label Statement alone and other with FlowLayout aligned to the right for the other 4 components, as per this answer BoxLayout does not respect the preferred size of our JTextFields. So a workaround is to wrap them inside another JPanel and then wrap that JPanel along with the Statement label.
A similar problem arises with the middle pane, which needs to use 2 JPanels: One for the fields wrapped inside another bigger one which holds it and the JButton at the bottom (Save Current). We could achieve a similar output by adding the JButton with a gridx = 2 and gridy = 2 with the counter and division label and fields on gridx = 3 and gridx = 4 respectively (instead of 2 & 3) but we would then need to add gbc.insets to add insets to the top and bottom with high values as well... It's up to you which one to use :)
The code that produces the above outputs is the following:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class FormSample {
private JFrame frame;
private JPanel topRightPane;
private JPanel centerPane;
private JPanel centerWithButtonPane;
private JPanel buttonsPane;
private JTextField monthField;
private JTextField yearField;
private JTextField serviceField;
private JTextField amountField;
private JTextField counterField;
private JTextField divisionField;
private static final int LEFT_MARGIN = 50; //Increase / Decrease to add extra space between components
private static final int RIGHT_MARGIN = LEFT_MARGIN;
//Change insets accordingly to add extra space between components (top, left, bottom, right)
private static final Insets leftInsets = new Insets(0, LEFT_MARGIN, 0, 0);
private static final Insets rightInsets = new Insets(0, 0, 0, RIGHT_MARGIN);
private static final Insets defaultInsets = new Insets(0, 0, 0, 0);
private JButton saveCurrentButton;
private JButton saveAllButton;
private JButton resetButton;
public static void main(String[] args) {
SwingUtilities.invokeLater(new FormSample()::createAndShowGui);
}
private void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
monthField = new JTextField(10);
yearField = new JTextField(10);
serviceField = new JTextField(10);
amountField = new JTextField(10);
counterField = new JTextField(10);
divisionField = new JTextField(10);
saveCurrentButton = new JButton("Save Current");
saveAllButton = new JButton("Save all");
resetButton = new JButton("Reset");
buttonsPane = new JPanel();
topRightPane = new JPanel();
topRightPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
topRightPane.add(new JLabel("Month"));
topRightPane.add(monthField);
topRightPane.add(new JLabel("Year"));
topRightPane.add(yearField);
centerWithButtonPane = new JPanel();
centerWithButtonPane.setLayout(new BoxLayout(centerWithButtonPane, BoxLayout.PAGE_AXIS));
Box box = Box.createHorizontalBox();
box.add(new JLabel("Statement"));
box.add(Box.createHorizontalGlue());
box.add(topRightPane);
centerPane = new JPanel();
centerPane.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = defaultInsets;
centerPane.add(new JLabel("Service"), gbc);
gbc.gridx = 1;
gbc.insets = rightInsets;
centerPane.add(serviceField, gbc);
gbc.gridx = 2;
gbc.insets = leftInsets;
centerPane.add(new JLabel("Counter"), gbc);
gbc.gridx = 3;
gbc.insets = defaultInsets;
centerPane.add(counterField, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.insets = defaultInsets;
centerPane.add(new JLabel("Amount"), gbc);
gbc.gridx = 1;
gbc.insets = rightInsets;
centerPane.add(amountField, gbc);
gbc.gridx = 2;
gbc.insets = leftInsets;
centerPane.add(new JLabel("Division"), gbc);
gbc.gridx = 3;
gbc.insets = defaultInsets;
centerPane.add(divisionField, gbc);
saveCurrentButton.setAlignmentX(Component.CENTER_ALIGNMENT); //Force centered alignment for our JButton
centerWithButtonPane.add(centerPane);
centerWithButtonPane.add(saveCurrentButton);
buttonsPane.add(saveAllButton);
buttonsPane.add(resetButton);
frame.add(box, BorderLayout.NORTH);
frame.add(centerWithButtonPane, BorderLayout.CENTER);
frame.add(buttonsPane, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Also please follow the advices given by #SergiyMedvynskyy about not mixing AWT and Swing components (i.e. JTextField with TextField) and only use Swing components as AWT ones are buggy.

JTabbedPane panels won't line up correctly

I am attempting to make a JTabbedPane that can show all the field pertaining to an object (in this case a person) and all the inherent fields that go with it. In doing so i am attempting to have the first panel(the one I am currently having trouble with) contain name, phone number and email.
As you can see below, I placed the JLabels for the title of the row in one panel, and the JLabels for the information in the right panel. The issue with this is that they will not separate from each other. I would like the left labels to be left aligned and together they should take up the entirety of the available panel size. setAlignment didn't seem to have any effect.
This is the code for the text panel creation:
private static JComponent makeTextPanel(String text){
JPanel panel = new JPanel(false);
JLabel filler = new JLabel(text);
filler.setHorizontalAlignment(JLabel.CENTER);
panel.setLayout(new GridLayout(1,1));
panel.add(filler);
return panel;
}
This is the code for TabbedPane as of this second:
public static void tabbedReadMenu(){
JFrame readMenu = new JFrame("Student Records");
JTabbedPane tabbedPane = new JTabbedPane();
Dimension d = new Dimension(300,300);
tabbedPane.setPreferredSize(d);
JComponent basicInfoPane = makeTextPanel("Basic Info");
tabbedPane.addTab("Basic Info", BasicInfoTab());
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
readMenu.add(tabbedPane);
readMenu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
readMenu.pack();
readMenu.setLocationRelativeTo(null);
readMenu.setVisible(true);
}
And this is the information for the actual tab along with the nested panels:
private static JPanel BasicInfoTab(){
JPanel basicInfoTab = new JPanel();
JPanel leftPanel = new JPanel();
JPanel rightPanel = new JPanel();
JPanel buttons = new JPanel();
JPanel spacing = new JPanel();
JPanel title = new JPanel();
JPanel mainPanel = new JPanel();
LayoutManager singleLine = new GridLayout(5,1);
leftPanel.setLayout(singleLine);
rightPanel.setLayout(singleLine);
buttons.setLayout(new FlowLayout());
mainPanel.setLayout(new SpringLayout());
spacing.setLayout(new GridLayout(3,1));
JLabel jspacing = new JLabel(" ");
JLabel jspacing1 = new JLabel(" ");
JLabel jspacing2 = new JLabel(" ");
spacing.add(jspacing);
spacing.add(jspacing1);
spacing.add(jspacing2);
spacing.setLayout(new FlowLayout());
JLabel header = new JLabel("Basic Student Information");
title.add(header);
JLabel FNLabel = new JLabel("First Name: "); //Creates all Labels
JLabel MILabel = new JLabel("Middle Initial: ");
JLabel LNLabel = new JLabel("Last Name: ");
JLabel IDLabel = new JLabel("Student ID: ");
JLabel EmailLabel = new JLabel("E-mail Address: ");
leftPanel.add(FNLabel);
leftPanel.add(MILabel);
leftPanel.add(LNLabel);
leftPanel.add(IDLabel);
leftPanel.add(EmailLabel);
selectedStudent = SaveFunction.passStudent();
JLabel FNInfo = new JLabel(selectedStudent.getFirstName());
JLabel MIInfo = new JLabel(selectedStudent.getMidInitial());
JLabel LNInfo = new JLabel(selectedStudent.getLastName());
JLabel IDInfo = new JLabel(selectedStudent.getID());
JLabel EmailInfo = new JLabel(selectedStudent.getEmail());
rightPanel.add(FNInfo);
rightPanel.add(MIInfo);
rightPanel.add(LNInfo);
rightPanel.add(IDInfo);
rightPanel.add(EmailInfo);
FNLabel.setHorizontalAlignment(JLabel.LEFT);
MILabel.setHorizontalAlignment(JLabel.LEFT);
LNLabel.setHorizontalAlignment(JLabel.LEFT);
IDLabel.setHorizontalAlignment(JLabel.LEFT);
EmailLabel.setHorizontalAlignment(JLabel.LEFT);
JButton edit = new JButton("Edit");
JButton close = new JButton("Close");
buttons.add(edit);
buttons.add(close);
basicInfoTab.add(title, BorderLayout.NORTH);
basicInfoTab.add(spacing, BorderLayout.CENTER);
basicInfoTab.add(leftPanel, BorderLayout.WEST);
basicInfoTab.add(rightPanel, BorderLayout.EAST);
basicInfoTab.add(buttons, BorderLayout.SOUTH);
return basicInfoTab;
}
Any help would be very much appreciated (including any more general coding tips on how I should improve).
Basically, for form design, I pretty much stick to GridBagLayout. If you don't mind a 3rd party layout, you should also consider MigLayout
Check out How to use GridBagLayout for more details...
For example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class FormLayout {
public static void main(String[] args) {
new FormLayout();
}
public FormLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
JLabel FNLabel = new JLabel("First Name: ");
JLabel MILabel = new JLabel("Middle Initial: ");
JLabel LNLabel = new JLabel("Last Name: ");
JLabel IDLabel = new JLabel("Student ID: ");
JLabel EmailLabel = new JLabel("E-mail Address: ");
JLabel FNInfo = new JLabel("My first name");
JLabel MIInfo = new JLabel("My initial");
JLabel LNInfo = new JLabel("My last name");
JLabel IDInfo = new JLabel("My student id");
JLabel EmailInfo = new JLabel("My Email");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = GridBagConstraints.WEST;
add(FNLabel, gbc);
gbc.gridy++;
add(MILabel, gbc);
gbc.gridy++;
add(LNLabel, gbc);
gbc.gridy++;
add(IDLabel, gbc);
gbc.gridy++;
add(EmailLabel, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
add(FNInfo, gbc);
gbc.gridy++;
add(MIInfo, gbc);
gbc.gridy++;
add(LNInfo, gbc);
gbc.gridy++;
add(IDInfo, gbc);
gbc.gridy++;
add(EmailInfo, gbc);
}
}
}

Java swing timer not decrementing the right way and not starting at the correct hour

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.)

Unwanted line between labels and radio group in Java

In my project, I use Swing controls. I had used a label together with a button group, but there is an unwanted line. Please help. There is a label associated with each radio button group. The unwanted line is there.how to add the labels and corresponding radio button group to the same panel
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//import java.util.Arrays;
public class Online extends JFrame {
static JRadioButton[] choice = new JRadioButton[6];
JFrame jtfMainFrame, jtfMainFrame1;
public void createWindow() {
jtfMainFrame = new JFrame("Online Examination");
jtfMainFrame.setSize(800, 500);
jtfMainFrame.setLocation(200, 150);
jtfMainFrame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JPanel pa = new JPanel();
JPanel panlabels = new JPanel(new GridLayout(0, 1, 0, 60));
JPanel pancontrols = new JPanel(new GridLayout(0, 1, 0, 60));
JPanel panEast = new JPanel();
JPanel pan = new JPanel(new FlowLayout());
JLabel qLabel = new JLabel("Question.");
qLabel.setOpaque(true);
qLabel.setForeground(Color.blue);
qLabel.setBackground(Color.lightGray);
JLabel aLabel = new JLabel("Question.");
aLabel.setOpaque(true);
aLabel.setForeground(Color.blue);
aLabel.setBackground(Color.lightGray);
JLabel bLabel = new JLabel("a.");
bLabel.setOpaque(true);
bLabel.setForeground(Color.blue);
bLabel.setBackground(Color.lightGray);
JLabel cLabel = new JLabel("b.");
cLabel.setOpaque(true);
cLabel.setForeground(Color.blue);
cLabel.setBackground(Color.lightGray);
JLabel dLabel = new JLabel("c.");
dLabel.setOpaque(true);
dLabel.setForeground(Color.blue);
dLabel.setBackground(Color.lightGray);
JLabel eLabel = new JLabel("d.");
eLabel.setOpaque(true);
eLabel.setForeground(Color.blue);
eLabel.setBackground(Color.lightGray);
panlabels.add(aLabel, BorderLayout.WEST);
panlabels.add(bLabel, BorderLayout.CENTER);
panlabels.add(cLabel, BorderLayout.CENTER);
panlabels.add(dLabel, BorderLayout.CENTER);
panlabels.add(eLabel, BorderLayout.CENTER);
//panlabels.add(fLabel, BorderLayout.WEST);
//fLabel.setVisible(false);
JLabel ques = new JLabel("q");
ques.setBackground(Color.red);
choice[1] = new JRadioButton("a");
choice[1].setBackground(Color.red);
choice[2] = new JRadioButton("b");
choice[2].setBackground(Color.red);
choice[3] = new JRadioButton("c");
choice[3].setBackground(Color.red);
choice[4] = new JRadioButton("d");
choice[4].setBackground(Color.red);
ButtonGroup bGroup = new ButtonGroup();
pancontrols.add(ques, BorderLayout.WEST);
for (int i = 1; i < 5; i++) {
// pancontrols.add(aLabel,BorderLayout.WEST);
bGroup.add(choice[i]);
pancontrols.add(choice[i], BorderLayout.WEST);
}
choice[4].setVisible(true);
panEast.add("West", panlabels);
panEast.add("West", pancontrols);
pa.add("Center", panEast);
pa.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Select your answer"));
//getContentPane().add(label);
//to be deleted pa.add("South", pan);
pa.setBackground(Color.pink);
jtfMainFrame.add(pa);
jtfMainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
jtfMainFrame.setVisible(true);
}
public static void main(String[] args) {
Online r = new Online();
r.createWindow();
}
}
First, your naming convention for the choice labels is off. qLabel="questions", aLabel="questions", bLabel="a", cLabel="b", etc. I would suggest you fix that to eliminate confusion and make your code more readable (ie only have one label that is a question).
Second, your use of panEast.add("West",panlabels); and the other two statements is generally not suggested. Read up on BorderLayout to find the more accepted method of doing this:
http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html
As for your problem, I have rewritten your code so things do line up, I will try to point out what I commented out to help:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//import java.util.Arrays;
public class Online extends JFrame {
static JRadioButton[] choice = new JRadioButton[6];
JFrame jtfMainFrame, jtfMainFrame1;
public void createWindow() {
jtfMainFrame = new JFrame("Online Examination");
jtfMainFrame.setSize(800, 500);
jtfMainFrame.setLocation(200, 150);
jtfMainFrame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JPanel pa = new JPanel();
//JPanel panlabels = new JPanel(new GridLayout(0, 1, 0, 60));
JPanel pancontrols = new JPanel(new GridLayout(0, 2, 0, 60));
JPanel panEast = new JPanel();
JPanel pan = new JPanel(new BorderLayout());
JLabel qLabel = new JLabel("Question.");
qLabel.setOpaque(true);
qLabel.setForeground(Color.blue);
qLabel.setBackground(Color.lightGray);
JLabel aLabel = new JLabel("Question.");
aLabel.setOpaque(true);
aLabel.setForeground(Color.blue);
aLabel.setBackground(Color.lightGray);
JLabel bLabel = new JLabel("a.");
bLabel.setOpaque(true);
bLabel.setForeground(Color.blue);
bLabel.setBackground(Color.lightGray);
JLabel cLabel = new JLabel("b.");
cLabel.setOpaque(true);
cLabel.setForeground(Color.blue);
cLabel.setBackground(Color.lightGray);
JLabel dLabel = new JLabel("c.");
dLabel.setOpaque(true);
dLabel.setForeground(Color.blue);
dLabel.setBackground(Color.lightGray);
JLabel eLabel = new JLabel("d.");
eLabel.setOpaque(true);
eLabel.setForeground(Color.blue);
eLabel.setBackground(Color.lightGray);
//panlabels.add(fLabel, BorderLayout.WEST);
//fLabel.setVisible(false);
JLabel ques = new JLabel("q");
ques.setBackground(Color.red);
choice[1] = new JRadioButton("a");
choice[1].setBackground(Color.red);
choice[2] = new JRadioButton("b");
choice[2].setBackground(Color.red);
choice[3] = new JRadioButton("c");
choice[3].setBackground(Color.red);
choice[4] = new JRadioButton("d");
choice[4].setBackground(Color.red);
ButtonGroup bGroup = new ButtonGroup();
//pancontrols.add(new JLabel(""));
pancontrols.add(ques, BorderLayout.WEST);
for (int i = 1; i < 5; i++) {
// pancontrols.add(aLabel,BorderLayout.WEST);
bGroup.add(choice[i]);
}
pancontrols.add(qLabel);
pancontrols.add(ques);
pancontrols.add(bLabel);
pancontrols.add(choice[1]);
pancontrols.add(cLabel);
pancontrols.add(choice[2]);
pancontrols.add(dLabel);
pancontrols.add(choice[3]);
pancontrols.add(eLabel);
pancontrols.add(choice[4]);
pancontrols.setSize(400,200);
choice[4].setVisible(true);
pa.add(pancontrols);
pa.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Select your answer"));
//getContentPane().add(label);
//to be deleted pa.add("South", pan);
pa.setBackground(Color.pink);
jtfMainFrame.add(pa);
jtfMainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
jtfMainFrame.setVisible(true);
}
public static void main(String[] args) {
Online r = new Online();
r.createWindow();
}
}
Basically, I removed your unnecessary panels. the only panel you add stuff to now is the pancontrols panel. I changed it to new JPanel(new Gridlayout(0,2,0,60)). With the two column GridLayout you will always have things line up bound wise, due to GridLayout making everything the same size.
Lastly I pulled the adding of choices[] from the loop and did that along with the labels to make sure things line up. I removed all the panels being added except the pancontrols being added to pa, which I assume you want to add more question panels to pa in that case. That covers your question in particular, but there is quite a lot of stuff you should do (ie use choice[0] for example, eliminate unused labels and panels, etc.)

Categories

Resources