I'm trying to make a small game (just for fun because i get bored) and at the current time i have a few panels, buttons, frames, images and whatnot already in it working well, but i'm come to a problem that i couldn't figure out for the past few days so i thought i'd ask here
The problem i have is i want to set a JButton transparent so that all you see is the image that is placed onto it (left and right arrows), and it works....except for when you hover your mouse over the transparent button, a different part of the screen becomes the background/foreground of the JButton instead of it still being transparent
(The White Spots are where my mouse is at the time, i do not click or anything, it just changes when you interact with the JButton, look specifically at the larger left arrow)
Image Without Mouse on JButton - http://i.imgur.com/xWWE5E0.png
Image With Mouse on JButton - http://i.imgur.com/8PosnwP.png
As you can see the previously transparent JButton has not got a background/foreground and most definitely not transparent anymore
The code for the JFrame is like this (i tried to make a smaller demo but it works properly in a plain, new frame so here's my actual code(feel free to give tips on improving it by PM))
package com.Braxeo.Games;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CharacterNew
{
static ImageIcon LArrow = new ImageIcon("Materials/LeftArrow.png");
static ImageIcon RArrow = new ImageIcon("Materials/RightArrow.png");
static ImageIcon bg = new ImageIcon("Materials/CharacterNewBackground.jpg");
public static JPanel CreateNewCharacter()
{
JPanel contentPane = new JPanel();
JPanel BackGround = new JPanel();
JLabel background = new JLabel();
JLabel shipshape = new JLabel();
JButton shapeleft = new JButton();
JButton shaperight = new JButton();
JLabel shapetext = new JLabel();
JPanel ShapeText = new JPanel();
JPanel ShipShape = new JPanel();
JPanel Shape = new JPanel();
JLabel shipcolor = new JLabel();
JButton colorleft = new JButton();
JButton colorright = new JButton();
JLabel colortext = new JLabel();
JPanel ShipColor = new JPanel();
JPanel ShipText = new JPanel();
JPanel SColor = new JPanel();
JLabel chartext = new JLabel();
JLabel charicon = new JLabel();
JButton iconleft = new JButton();
JButton iconright = new JButton();
JPanel iconpane = new JPanel();
JPanel icontext = new JPanel();
JPanel icon = new JPanel();
JButton back = new JButton();
JPanel backtext = new JPanel();
JButton continu = new JButton();
JPanel cont = new JPanel();
JLabel charname = new JLabel();
JTextField typename = new JTextField();
JPanel charnamePane = new JPanel();
// Shape
ShapeText.setLayout(new GridLayout(1,1));
ShipShape.setLayout(new GridLayout(1,3));
Shape.setLayout(new BorderLayout());
shipshape = new JLabel("ADD SSHIPS");
shapeleft = new JButton(LArrow);
shaperight = new JButton(RArrow);
shapeleft.setContentAreaFilled(false);
shapeleft.setOpaque(false);
shapeleft.setBackground(new Color(0,0,0,0));
shapetext = new JLabel("Choose Shape of Ship");
ShipShape.setBackground(new Color(0,0,0,0));
Shape.setBackground(new Color(0,0,0,0));
Shape.setBounds(600, 100, 500, 400);
ShipShape.add(shapeleft);
ShipShape.add(shipshape);
ShipShape.add(shaperight);
ShapeText.add(shapetext);
Shape.add(ShapeText, BorderLayout.PAGE_START);
Shape.add(ShipShape);
contentPane.add(Shape);
// Color
ShipColor.setLayout(new GridLayout(1, 3));
ShipText.setLayout(new GridLayout(1,1));
SColor.setLayout(new BorderLayout());
colortext = new JLabel(" Choose Color of your Ship");
shipcolor = new JLabel("ADD IMAGES");
colorleft = new JButton("ADD LEFT ARROW");
colorright = new JButton("ADD RIGHT ARROW");
colortext.setFont(new Font("Serif", Font.BOLD, 32));
ShipText.setBackground(new Color(0,0,0,0));
colortext.setForeground(Color.red);
SColor.setBackground(new Color(0,0,0,0));
ShipText.setOpaque(true);
ShipText.add(colortext);
ShipColor.add(colorleft);
ShipColor.add(shipcolor);
ShipColor.add(colorright);
SColor.setBounds(Main.x - 750,400,380,145);
SColor.add(ShipText, BorderLayout.PAGE_START);
SColor.add(ShipColor);
contentPane.add(SColor);
// Icon
iconpane.setLayout(new GridLayout(1,3));
icontext.setLayout(new GridLayout(1,1));
icon.setLayout(new BorderLayout());
chartext = new JLabel(" Pick Your Desired Icon");
charicon = new JLabel("PLACE IMAGE");
iconleft = new JButton("PLACE LEFT ICON");
iconright = new JButton("PLACE right ICON");
chartext.setFont(new Font("Serif", Font.BOLD, 32));
icontext.setBackground(new Color(0,0,0,0));
icon.setBackground(new Color(0,0,0,0));
chartext.setForeground(Color.red);
icontext.setOpaque(true);
icontext.add(chartext);
iconpane.add(iconleft);
iconpane.add(charicon);
iconpane.add(iconright);
icon.setBounds(Main.x - 750,550,380,145);
icon.add(icontext, BorderLayout.PAGE_START);
icon.add(iconpane);
contentPane.add(icon);
// back
backtext.setLayout(new BorderLayout());
back = new JButton("Back");
backtext.setBounds(50, Main.y-150, 252,76);
back.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Main.defaultframe.getContentPane().removeAll();
Main.defaultframe.getContentPane().revalidate();
Main.defaultframe.setContentPane(CharacterSelect.CreateLoadCharacter());
Main.defaultframe.setVisible(true);
}
});
backtext.add(back);
contentPane.add(backtext);
// continue
cont.setLayout(new BorderLayout());
continu = new JButton("Continue");
cont.setBounds(Main.x-302, Main.y-150, 252,76);
cont.add(continu);
contentPane.add(cont);
// Name
charnamePane.setLayout(new GridLayout( 2,1));
charname = new JLabel(" Enter Your Name Below");
charname.setFont(new Font("Impact", Font.BOLD, 32));
typename.setSize(252, 76);
typename.setFont(new Font("Razer Text Regular", Font.BOLD, 22));
typename.setBackground(Color.LIGHT_GRAY);
typename.setHorizontalAlignment(JLabel.CENTER);
charnamePane.setBounds(100,200,400,100);
charnamePane.setOpaque(true);
charnamePane.setBackground(new Color(0,0,0,0));
charname.setBackground(new Color(0,0,0,0));
charname.setForeground(Color.white);
charnamePane.add(charname);
charnamePane.add(typename, BorderLayout.PAGE_START);
contentPane.add(charnamePane);
// Background
background = new JLabel(bg);
BackGround.setLayout(new BorderLayout());
BackGround.setBounds(0, 0, Main.x, Main.y);
BackGround.add(background);
contentPane.add(BackGround);
contentPane.setLayout(new BorderLayout());
return contentPane;
}
}
The code that works out the Transparent JButton is
JButton shapeleft = new JButton();
JPanel ShapeText = new JPanel();
JPanel Shape = new JPanel();
shapeleft = new JButton(LArrow);
shapeleft.setContentAreaFilled(false);
shapeleft.setOpaque(false);
shapeleft.setBackground(new Color(0,0,0,0));
ShipShape.setBackground(new Color(0,0,0,0));
Shape.setBackground(new Color(0,0,0,0));
Shape.setBounds(600, 100, 500, 400);
ShipShape.add(shapeleft);
Shape.add(ShipShape);
contentPane.add(Shape);
If anyone could please help me figure out why its playing up like it is that would be a massive help, and i'm still a beginner so all help is good help :) thanks :)
ShipShape.setBackground(new Color(0,0,0,0));
Check out Background With Transparency for the probable problem and a couple of solutions.
Basically you need to make sure the parent component gets painted before you paint your components background.
Related
I use a BorderLayout combined with a FlowLayout, which works perfectly when I set up the BorderLayout.NORTH. However, in the CENTER area I would like to add a JTextArea (to print out console), but when I create a panel, add JTextArea, after adding a panel to BorderLayout.CENTER nothing appears and became grey. I have tried several combinations and tricks, also I have checked several forum posts without luck. Here is my very simplified code (should run flawlessly, I have commented the problematic part if you remove the comment the bug present):
public static void main(String[] args) {
blogGUI();
}
public static void blogGUI() {
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
frame.setSize(700, 500);
frame.setLayout(new BorderLayout()); //a frame BorderLayout elrendezésü
JPanel panel1 = new JPanel();
//panel.setBounds(0,0,700,500);
panel1.setBackground(new java.awt.Color(255,255,255));
panel1.setVisible(true);
panel1.setSize(new Dimension(140, 30));
JPanel panel2 = new JPanel();
//panel.setBounds(0,0,700,500);
panel2.setBackground(new java.awt.Color(255,255,255));
panel2.setVisible(true);
panel2.setSize(new Dimension(140, 30));
JButton btNewEntry = new JButton("New Post");
JButton btModifyEntry = new JButton("Modify");
JButton btDeleteEntry = new JButton("Delete");
JButton btShowEntries = new JButton("List");
JButton btExit = new JButton("Exit");
JLabel lbFile = new JLabel("Open Blog:");
JLabel lbFilePath = new JLabel("Nothing selected...");
JButton btFileOpen = new JButton("Open");
btNewEntry.setPreferredSize(new Dimension(100,30));
btModifyEntry.setPreferredSize(new Dimension(100,30));
btDeleteEntry.setPreferredSize(new Dimension(100,30));
btShowEntries.setPreferredSize(new Dimension(100,30));
btExit.setPreferredSize(new Dimension(100,30));
lbFile.setPreferredSize(new Dimension(100,30));
lbFilePath.setPreferredSize(new Dimension(310,30));
btFileOpen.setPreferredSize(new Dimension(100,30));
panel1.add(btNewEntry);
panel1.add(btModifyEntry);
panel1.add(btDeleteEntry);
panel1.add(btShowEntries);
panel1.add(btExit);
panel2.add(lbFile);
panel2.add(btFileOpen);
panel2.add(lbFilePath);
JPanel cpanelNorth = new JPanel();
cpanelNorth.setBackground(new java.awt.Color(135,206,250));
cpanelNorth.setLayout(new FlowLayout());
cpanelNorth.setPreferredSize(new Dimension(500, 95));
cpanelNorth.add(panel1);
cpanelNorth.add(panel2);
frame.add(cpanelNorth, BorderLayout.NORTH);
/*Something wrong here! From this point, if this uncommented ruins the gui.*/
JPanel panel3 = new JPanel();
panel3.setLayout(new FlowLayout());
//panel.setBounds(0,0,700,500);
panel3.setBackground(new java.awt.Color(255,255,255));
//panel3.setVisible(true);
//panel3.setPreferredSize(new Dimension(30, 30));
JTextArea textArea = new JTextArea("Welcome to...!");
//textArea.setPreferredSize(new Dimension(50,50));
textArea.setBackground(new java.awt.Color(255,0,0));
panel3.add(textArea);
frame.add(panel3, BorderLayout.CENTER);
Hi Andrew Thompson and user16320675, Thanks for the quick help, this solved my issue. How can I further improve the quality the code? I had to put only one setPrefferedSize() at the JTextArea, all other places I removed (without this the window shrinks to zero)
I reduced my code
image: https://ibb.co/Xj7tYKf
I have removed allsetPrefferedSize()
I put frame.setVisible(true) at the end, and also frame.pack() at the end
Here is my code:
package bloggui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Start {
public static void main(String[] args) {
blogGUI();
}
public static void blogGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.setBackground(new java.awt.Color(255,255,255));
JPanel panel2 = new JPanel();
panel2.setBackground(new java.awt.Color(255,255,255));
JButton btNewEntry = new JButton("New Post");
JButton btModifyEntry = new JButton("Modify");
JButton btDeleteEntry = new JButton("Delete");
JButton btShowEntries = new JButton("List");
JButton btExit = new JButton("Exit");
JLabel lbFile = new JLabel("Open Blog:");
JLabel lbFilePath = new JLabel("Nothing selected...");
JButton btFileOpen = new JButton("Open");
panel1.add(btNewEntry);
panel1.add(btModifyEntry);
panel1.add(btDeleteEntry);
panel1.add(btShowEntries);
panel1.add(btExit);
panel2.add(lbFile);
panel2.add(btFileOpen);
panel2.add(lbFilePath);
JPanel cpanelNorth = new JPanel();
cpanelNorth.setBackground(new java.awt.Color(135,206,250));
cpanelNorth.setLayout(new FlowLayout());
cpanelNorth.add(panel1);
cpanelNorth.add(panel2);
frame.add(cpanelNorth, BorderLayout.NORTH);
frame.pack();
JPanel panel3 = new JPanel();
panel3.setLayout(new FlowLayout());
panel3.setBackground(new java.awt.Color(135,206,250));
JTextArea textArea = new JTextArea("Welcome to...!");
textArea.setBackground(new java.awt.Color(255,255,255));
textArea.setPreferredSize(new Dimension(620, 400)); //Must not use setPreferredSize() [I must use it only once here!]
panel3.add(textArea);
frame.add(panel3, BorderLayout.CENTER);
frame.pack(); //Must be at the end
frame.setVisible(true); //Must be at the end
}
}
This is the picture I am trying to replicate
This is what I have (didn't add icon images yet)
I can't seem to find a solution, been staring at it for quite some time.
I am trying to replicate the following picture, using GridLayout for the buttons and the figure out the rest on my own using Java Swing. Furthermore, I've added my buttons into a JPanel and now I'm trying to add spacing between the panel and the pane.
This is what I have, how can I go about it?
super(title);
this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.PAGE_AXIS));
Container pane = this.getContentPane();
JButton b1 = new JButton();
b1.setBackground(Color.white);
JButton b2 = new JButton();
b2.setBackground(Color.white);
JButton b3 = new JButton();
b3.setBackground(Color.white);
JButton b4 = new JButton();
b4.setBackground(Color.white);
JButton b5 = new JButton();
b5.setBackground(Color.white);
JButton b6 = new JButton();
b6.setBackground(Color.white);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2,3,10,10));
panel.setBackground(Color.black);
panel.add(b1);
panel.add(b2);
panel.add(b3);
panel.add(b4);
panel.add(b5);
panel.add(b6);
pane.add(panel);
this.setSize(500,500);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
The easiest way to do it would be to add an empty border to your JPanel (see this post on empty borders):
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2, 10, 10));
// ...
panel.setBorder(new EmptyBorder(50, 50, 50, 50));
Another good approach (depending always on your application needs), if you have the JButton preferred size set, would be to have the main JPanel's grid layout set to have two columns and one row, with another JPanel inside each column. Adding to the interior JPanels a BoxLayout in Y_AXIS mode and aligning the buttons with setAlignmentX() would work great too (note this approach wouldn't center the JButtons vertically) (see How to use BoxLayout):
public class MyFrame extends JFrame {
private String title = "Title";
public MyFrame(){
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(1,2,10,10));
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
mainPanel.add(leftPanel);
mainPanel.add(rightPanel);
JButton b1 = new JButton();
b1.setBackground(Color.white);
//b1.setIcon(new ImageIcon(img1));
b1.setAlignmentX(Component.RIGHT_ALIGNMENT);
leftPanel.add(b1);
JButton b2 = new JButton();
b2.setBackground(Color.white);
//b2.setIcon(new ImageIcon(img2));
b2.setAlignmentX(Component.RIGHT_ALIGNMENT);
leftPanel.add(b2);
JButton b3 = new JButton();
b3.setBackground(Color.white);
//b3.setIcon(new ImageIcon(img3));
b3.setAlignmentX(Component.RIGHT_ALIGNMENT);
leftPanel.add(b3);
JButton b4 = new JButton();
b4.setBackground(Color.white);
//b4.setIcon(new ImageIcon(img4));
b4.setAlignmentX(Component.LEFT_ALIGNMENT);
rightPanel.add(b4);
JButton b5 = new JButton();
b5.setBackground(Color.white);
//b5.setIcon(new ImageIcon(img5));
b5.setAlignmentX(Component.LEFT_ALIGNMENT);
rightPanel.add(b5);
JButton b6 = new JButton();
b6.setBackground(Color.white);
//b6.setIcon(new ImageIcon(img6));
b6.setAlignmentX(Component.LEFT_ALIGNMENT);
rightPanel.add(b6);
add(mainPanel); //Adding our mainPanel to the contentPane of the JFrame
this.setSize(500,500); //or pack();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setTitle(title);
this.setVisible(true);
}
}
Here's a little demonstration I whipped up.
All Swing applications must start with a call to the SwingUtilities invokeLater method. This method ensures that all Swing components are created and executed on the Event Dispatch Thread.
You don't set the size of the JFrame and try and make the Swing components fit. You let the JFrame pack with all the Swing components.
You create a GridLayout JPanel inside of a FlowLayout JPanel. The FlowLayout JPanel uses an empty border of the appropriate size.
I used the image the OP provided to get the icons.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class EmptySpaceDemo implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new EmptySpaceDemo());
}
private Image[] images;
public EmptySpaceDemo() {
this.images = createImages();
}
private Image[] createImages() {
BufferedImage image = readImage();
Image[] images = new Image[6];
images[0] = image.getSubimage(155, 113, 110, 90);
images[1] = image.getSubimage(276, 113, 110, 90);
images[2] = image.getSubimage(155, 217, 110, 90);
images[3] = image.getSubimage(276, 217, 110, 90);
images[4] = image.getSubimage(155, 321, 110, 90);
images[5] = image.getSubimage(276, 321, 110, 90);
return images;
}
#Override
public void run() {
JFrame frame = new JFrame("Empty Space Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBackground(Color.BLACK);
panel.setBorder(BorderFactory.createEmptyBorder(40, 100, 40, 100));
JPanel innerPanel = new JPanel(new GridLayout(0, 2, 10, 10));
innerPanel.setBackground(Color.BLACK);
for (int i = 0; i < images.length; i++) {
JButton button = new JButton(new ImageIcon(images[i]));
innerPanel.add(button);
}
panel.add(innerPanel);
return panel;
}
private BufferedImage readImage() {
try {
return ImageIO.read(getClass().getResourceAsStream("/icons.png"));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
I am having a problem with BorderLayout, that was set to the green JPanel side. It does not display elements on the EAST in a row order. Do I have to combine this with GridBagLayout ? Could someone advice me how should I tackle this problem?
Basically the problem is of displaying objects inside green area below when I am using
Current layout:
My aim is to achieve this layout:
public class GUILayout {
public static void main(String[] args) {
JFrame jf = new JFrame();
JButton jbO = new JButton("CSIS0396");
JButton jbl = new JButton("Final");
JButton jb2 = new JButton("2010");
JButton jb3 = new JButton("Exam");
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
JButton object_btn = new JButton("Object");
JButton oriented_btn = new JButton("Oriented");
JButton programming_btn = new JButton("Programming");
JButton and_btn = new JButton("and");
JButton java_btn = new JButton("Java");
BorderLayout layout = new BorderLayout();
panel.setLayout(layout);
panel2.setLayout(layout);
panel.add(BorderLayout.CENTER,object_btn);
panel.add(BorderLayout.WEST,oriented_btn);
panel.add(BorderLayout.WEST,programming_btn);
panel.add(BorderLayout.WEST,and_btn);
panel.add(BorderLayout.WEST,java_btn);
panel2.add(BorderLayout.NORTH, jbO);
panel2.add(BorderLayout.SOUTH, jb2);
panel2.add(BorderLayout.WEST, jbl);
panel2.add(BorderLayout.EAST, jb3);
panel.setBackground(Color.GREEN);
panel2.setBackground(Color.RED);
jf.getContentPane().add(panel);
jf.getContentPane().add(panel2, BorderLayout.EAST);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(400, 300);
jf.setVisible(true);
}
}
don't share same layout for multiple component and use box layout for left panel to positioning buttons
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GUILayout {
public static void main(String[] args) {
JFrame jf = new JFrame();
JButton jbO = new JButton("CSIS0396");
JButton jbl = new JButton("Final");
JButton jb2 = new JButton("2010");
JButton jb3 = new JButton("Exam");
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
JButton object_btn = new JButton("Object");
JButton oriented_btn = new JButton("Oriented");
JButton programming_btn = new JButton("Programming");
JButton and_btn = new JButton("and");
JButton java_btn = new JButton("Java");
BorderLayout layout = new BorderLayout();
panel2.setLayout(layout);
panel.setLayout( new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(object_btn);
panel.add(oriented_btn);
panel.add(programming_btn);
panel.add(and_btn);
panel.add(java_btn);
panel2.add(BorderLayout.NORTH, jbO);
panel2.add(BorderLayout.SOUTH, jb2);
panel2.add(BorderLayout.WEST, jbl);
panel2.add(BorderLayout.EAST, jb3);
panel.setBackground(Color.GREEN);
panel2.setBackground(Color.RED);
jf.setLayout(new BorderLayout());
jf.getContentPane().add(panel ,BorderLayout.WEST);
jf.getContentPane().add(panel2, BorderLayout.EAST);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(400, 300);
jf.setVisible(true);
}
}
The first problem is that you're having your panels share a layout. You must use a new BorderLayout for each of them.
The second problem is that a BorderLayout can only have one component in each constraint position. When you try to add multiple components to the WEST position, each one replaces the one that was previously in that position:
panel.add(BorderLayout.WEST,oriented_btn);
// Implicitly removes oriented_btn from panel
panel.add(BorderLayout.WEST,programming_btn);
// Implicitly removes programming_btn from panel
panel.add(BorderLayout.WEST,and_btn);
// Implicitly removes and_btn from panel
panel.add(BorderLayout.WEST,java_btn);
The solution is to put them in their own container, such as a Box or a JPanel with a GridLayout:
Box box = Box.createVerticalBox();
// Or:
//JComponent box = new JPanel(new GridLayout(0, 1));
box.add(oriented_btn);
box.add(programming_btn);
box.add(and_btn);
box.add(java_btn);
panel.add(BorderLayout.WEST, box);
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 can I make buttons like this?
JPanel jp = new JPanel();
JPanel jpB1 = new JPanel();
JPanel jpB2 = new JPanel();
JPanel jpB3 = new JPanel();
JButton jb1 = new JButton("button1");
JButton jb2 = new JButton("button2");
JButton jb3 = new JButton("button3");
...
JLabel jl = new JLabel("label");
...
jp.setLayout(new BorderLayout());
...
jpB1.add(jb1);
jpB2.add(jb2);
jpB3.add(jb3);
...
jp.add(jpB1, BorderLayout.NORTH);
jp.add(jpB2, BorderLayout.CENTER);
jp.add(jpB3, BorderLayout.SOUTH);
...
I tried this code on creating 3 panels and add them to the main panel. It shows two buttons on north and one button on south! Can someone help me?
Note, the default layout of JPanel is FlowLayout; a GridBagLayout with default constraints is centered in the frame's BorderLayout.CENTER. Also, pack() the enclosing Window and display it last. Using Initial Threads left as an exercise.
Addendum: A useful trick for solving layout problems is setting the background color of an enclosing container to a contrasting color, for example
jpB2.setBackground(Color.blue);
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Bouton2 {
public static void main(String[] args) {
final int LARGEUR = 400;
final int HAUTEUR = 300;
JFrame jf = new JFrame();
JPanel jp = new JPanel();
JPanel jpB1 = new JPanel();
JPanel jpB2 = new JPanel(new GridBagLayout());
JPanel jpB3 = new JPanel();
JButton jb1 = new JButton("Cliquez ici");
JButton jb2 = new JButton("Je compte");
JButton jb3 = new JButton("J'agrandis");
JLabel jl = new JLabel("0 clic");
jp.setLayout(new BorderLayout());
jpB1.add(jb1);
jpB2.add(jb2);
jpB3.add(jb3);
jp.add(jpB1, BorderLayout.NORTH);
jp.add(jpB2, BorderLayout.CENTER);
jp.add(jpB3, BorderLayout.SOUTH);
jf.setTitle("Fenêtre Bouton2");
jf.setContentPane(jp);
jf.pack();
jf.setSize(LARGEUR, HAUTEUR);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLocationRelativeTo(null);
jf.setVisible(true);
}
}