I want to have a random order for displaying the cards or screens in my CardLayout. I need guidance on how to accomplish this. What is strategy I should use?
I tried using the code below, but it is in a fixed order. I want to be able to choose whichever order I like.
EDIT !
Sorry, by random order I did not mean shuffling. But, it is good to know. I want the user of the program to be able to enter some input. Depending on the value of the input, a particular screen/card is displayed.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class CardLayoutExample extends JFrame {
private int currentCard = 1;
private JPanel cardPanel;
private CardLayout cl;
public CardLayoutExample() {
setTitle("Card Layout Example");
setSize(300, 150);
cardPanel = new JPanel();
cl = new CardLayout();
cardPanel.setLayout(cl);
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
JLabel lab1 = new JLabel("Card1");
JLabel lab2 = new JLabel("Card2");
JLabel lab3 = new JLabel("Card3");
JLabel lab4 = new JLabel("Card4");
p1.add(lab1);
p2.add(lab2);
p3.add(lab3);
p4.add(lab4);
cardPanel.add(p1, "1");
cardPanel.add(p2, "2");
cardPanel.add(p3, "3");
cardPanel.add(p4, "4");
JPanel buttonPanel = new JPanel();
JButton b1 = new JButton("Previous");
JButton b2 = new JButton("Next");
buttonPanel.add(b1);
buttonPanel.add(b2);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (currentCard > 1) {
currentCard -= 1;
cl.show(cardPanel, "" + (currentCard));
}
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (currentCard < 4) {
currentCard += 1;
cl.show(cardPanel, "" + (currentCard));
}
}
});
getContentPane().add(cardPanel, BorderLayout.NORTH);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
CardLayoutExample cl = new CardLayoutExample();
cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cl.setVisible(true);
}
}
Put the CartLayouts in a List, shuffle the List, add to the containing layout in the List order.
Here is a simple way to jump directly to a card.
final JButton jumpTo = new JButton("Jump To");
buttonPanel.add(jumpTo);
jumpTo.addActionListener( new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae) {
String[] names = {"1","2","3","4"};
String s = (String)JOptionPane.showInputDialog(
jumpTo,
"Jump to card",
"Navigate",
JOptionPane.QUESTION_MESSAGE,
null,
names,
names[0]);
if (s!=null) {
cl.show(cardPanel, s);
}
}
} );
Obviously this will require some changes to the rest of the code. Here is an SSCCE.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class CardLayoutExample extends JFrame {
private int currentCard = 1;
private JPanel cardPanel;
private CardLayout cl;
public CardLayoutExample() {
setTitle("Card Layout Example");
setSize(300, 150);
cardPanel = new JPanel();
cl = new CardLayout();
cardPanel.setLayout(cl);
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
JLabel lab1 = new JLabel("Card1");
JLabel lab2 = new JLabel("Card2");
JLabel lab3 = new JLabel("Card3");
JLabel lab4 = new JLabel("Card4");
p1.add(lab1);
p2.add(lab2);
p3.add(lab3);
p4.add(lab4);
cardPanel.add(p1, "1");
cardPanel.add(p2, "2");
cardPanel.add(p3, "3");
cardPanel.add(p4, "4");
JPanel buttonPanel = new JPanel();
JButton b1 = new JButton("Previous");
JButton b2 = new JButton("Next");
buttonPanel.add(b1);
buttonPanel.add(b2);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (currentCard > 1) {
currentCard -= 1;
cl.show(cardPanel, "" + (currentCard));
}
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (currentCard < 4) {
currentCard += 1;
cl.show(cardPanel, "" + (currentCard));
}
}
});
final JButton jumpTo = new JButton("Jump To");
buttonPanel.add(jumpTo);
jumpTo.addActionListener( new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae) {
String[] names = {"1","2","3","4"};
String s = (String)JOptionPane.showInputDialog(
jumpTo,
"Jump to card",
"Navigate",
JOptionPane.QUESTION_MESSAGE,
null,
names,
names[0]);
if (s!=null) {
cl.show(cardPanel, s);
}
}
} );
getContentPane().add(cardPanel, BorderLayout.NORTH);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
CardLayoutExample cl = new CardLayoutExample();
cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cl.setVisible(true);
}
}
BTW - my comment "Where is the part of the code where you prompt the user for a card number?" was actually a very subtle way to try & communicate.. For better help sooner, post an SSCCE.
Related
My friend has given me a practice problem regarding prime number. Numbers 1 to n needs to be displayed in a new window. I also can't figure out on how I can use the input I got from panel1 to panel2. I'm very new to GUI since I haven't gone there when I studied Java a few years back. Hope you can help!
I haven't done much with the GUI since I don't really know where to start, but I've watched youtube videos and have gone through many sites on how to start with a GUI. Here's what I have done:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class sieve
{
private JPanel contentPane;
private MyPanel input;
private MyPanel2 sieve;
private void displayGUI()
{
JFrame frame = new JFrame("Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
input = new MyPanel(contentPane);
sieve = new MyPanel2();
contentPane.add(input, "Input");
contentPane.add(sieve, "Sieve of Erasthoneses");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class MyPanel extends JPanel {
private JTextField text;
private JLabel label1;
private JButton OK;
private JButton cancel;
private JPanel contentPane;
public MyPanel(JPanel panel) {
contentPane = panel;
label1 = new JLabel ("Enter a number from 1 to n:");
text = new JTextField(1000);
OK = new JButton ("OK");
cancel = new JButton ("Cancel");
setPreferredSize (new Dimension (500, 250));
setLayout (null);
text.setBounds (145, 50, 60, 25);
OK.setBounds (450, 30, 150, 50);
cancel.setBounds (250, 30, 150, 50);
OK.setSize(315, 25);
OK.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
add (text);
add (label1);
add (OK);
add (cancel);
}
}
class MyPanel2 extends JPanel {
private JFrame frame;
private JLabel label;
JLabel label1;
public MyPanel2()
{
frame = new JFrame("Sieve of Eratosthenes");
label = new JLabel("The Prime numbers from 2 to " + num + " are");
num1 = num;
boolean[] bool = new boolean[num1];
for (int i = 0; i < bool.length; i++)
{
bool[i] = true;
}
for (int i = 2; i < Math.sqrt(num1); i++)
{
if(bool[i] == true)
{
for(int j = (i*i); j < num1; j = j+i)
{
bool[j] = false;
}
}
}
for (int i = 2; i< bool.length; i++)
{
if(bool[i]==true)
{
label1 = new JLabel(" " + label[i]);
}
}
}
}
Thanks for your help!
Your code had many compilation errors.
Oracle has a helpful tutorial, Creating a GUI With JFC/Swing. Skip the Netbeans section. Review all the other sections.
I reworked your two JPanels. When creating a Swing application, you first create the GUI. After the GUI is created, you fill in the values to be displayed.
I created the following GUI. Here's the input JPanel.
Here's the Sieve JPanel.
I used Swing layout managers to create the two JPanels. Using null layouts and absolute positioning leads to many problems.
I created the sieve JPanel, then populated it with values. You can see how I did it in the source code.
Here's the complete runnable code. I made the classes inner classes.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Eratosthenes {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Eratosthenes().displayGUI();
}
});
}
private CardLayout cardLayout;
private JFrame frame;
private JPanel contentPane;
private InputPanel inputPanel;
private SievePanel sievePanel;
private void displayGUI() {
frame = new JFrame("Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
cardLayout = new CardLayout();
contentPane.setLayout(cardLayout);
inputPanel = new InputPanel();
sievePanel = new SievePanel();
contentPane.add(inputPanel.getPanel(), "Input");
contentPane.add(sievePanel.getPanel(), "Sieve");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public void cancelAction() {
frame.dispose();
System.exit(0);
}
public class InputPanel {
private JPanel panel;
private JTextField textField;
public InputPanel() {
this.panel = createMainPanel();
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
JPanel entryPanel = new JPanel(new FlowLayout());
entryPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JLabel label = new JLabel("Enter a number from 1 to n:");
entryPanel.add(label);
textField = new JTextField(10);
entryPanel.add(textField);
panel.add(entryPanel, BorderLayout.BEFORE_FIRST_LINE);
JPanel buttonPanel = new JPanel(new FlowLayout());
entryPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JButton okButton = new JButton("OK");
buttonPanel.add(okButton);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int inputNumber = valueOf(textField.getText().trim());
if (inputNumber < 2) {
return;
}
sievePanel.updatePrimeLabel(inputNumber);
sievePanel.updatePrimeNumbers(inputNumber);
cardLayout.show(contentPane, "Sieve");
}
private int valueOf(String number) {
try {
return Integer.valueOf(number);
} catch (NumberFormatException e) {
return -1;
}
}
});
JButton cancelButton = new JButton("Cancel");
buttonPanel.add(cancelButton);
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelAction();
}
});
okButton.setPreferredSize(cancelButton.getPreferredSize());
panel.add(buttonPanel, BorderLayout.AFTER_LAST_LINE);
return panel;
}
public JPanel getPanel() {
return panel;
}
}
public class SievePanel {
private JLabel primeLabel;
private JList<Integer> primeNumbersList;
private JPanel panel;
public SievePanel() {
this.panel = createMainPanel();
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
Font titlefont = panel.getFont().deriveFont(Font.BOLD, 24f);
JPanel textPanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Sieve of Eratosthenes");
titleLabel.setFont(titlefont);
titleLabel.setHorizontalAlignment(JLabel.CENTER);
textPanel.add(titleLabel, BorderLayout.BEFORE_FIRST_LINE);
primeLabel = new JLabel(" ");
primeLabel.setHorizontalAlignment(JLabel.CENTER);
textPanel.add(primeLabel, BorderLayout.AFTER_LAST_LINE);
panel.add(textPanel, BorderLayout.BEFORE_FIRST_LINE);
primeNumbersList = new JList<>();
JScrollPane scrollPane = new JScrollPane(primeNumbersList);
panel.add(scrollPane, BorderLayout.CENTER);
JButton button = new JButton("Return");
panel.add(button, BorderLayout.AFTER_LAST_LINE);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
cardLayout.show(contentPane, "Input");
}
});
return panel;
}
public void updatePrimeLabel(int inputNumber) {
primeLabel.setText("The prime numbers from 2 to " +
inputNumber + " are:");
}
public void updatePrimeNumbers(int inputNumber) {
DefaultListModel<Integer> primeNumbers =
new DefaultListModel<>();
boolean[] bool = new boolean[inputNumber];
for (int i = 0; i < bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i < Math.sqrt(inputNumber); i++) {
if (bool[i] == true) {
for (int j = (i * i); j < inputNumber; j = j + i) {
bool[j] = false;
}
}
}
for (int i = 2; i < bool.length; i++) {
if (bool[i] == true) {
primeNumbers.addElement(i);
}
}
primeNumbersList.setModel(primeNumbers);
}
public JPanel getPanel() {
return panel;
}
}
}
I am trying to learn how to use CardLayout instead of multiple JFrames and I am messing around with this code I found on youtube. I tried calling setSize() on all the JPanes but it does not change the size and it remains at the minimum window size. Is the reason I can't set the size because of this line of code: "panelCont.setLayout(cl);" ?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CLayout {
JFrame frame = new JFrame("CardLayout");
JPanel panelCont = new JPanel();
JPanel panelFirst = new JPanel();
JPanel panelSecond = new JPanel();
JButton buttonOne = new JButton("Switch to second panel");
JButton buttonSecond = new JButton("Switch to first panel");
CardLayout cl = new CardLayout();
public CLayout() {
panelCont.setLayout(cl);
panelFirst.add(buttonOne);
panelSecond.add(buttonSecond);
panelFirst.setBackground(Color.BLUE);
panelSecond.setBackground(Color.GREEN);
panelCont.add(panelFirst, "1");
panelCont.add(panelSecond, "2");
cl.show(panelCont, "1");
buttonOne.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cl.show(panelCont, "2");
}
});
buttonSecond.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cl.show(panelCont, "1");
}
});
frame.add(panelCont);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new CLayout();
}
});
}
}
Yes, it's for CardLayout but also it's possible to do resize. You can nest your JPanels for instance. or use something like this :
Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
public class MultiSizedPanels {
private static void createAndShowUI() {
final CardLayout cardLayout = new CardLayout();
final JPanel cardHolder = new JPanel(cardLayout);
JLabel[] labels = {
new JLabel("Small Label", SwingConstants.CENTER),
new JLabel("Medium Label", SwingConstants.CENTER),
new JLabel("Large Label", SwingConstants.CENTER)};
for (int i = 0; i < labels.length; i++) {
int padding = 50;
Dimension size = labels[i].getPreferredSize();
size = new Dimension(size.width + 2 * (i + 1) * padding, size.height + 2 * (i + 1) * padding);
labels[i].setPreferredSize(size);
Border lineBorder = BorderFactory.createLineBorder(Color.blue);
labels[i].setBorder(lineBorder);
JPanel containerPanel = new JPanel(new GridBagLayout());
containerPanel.add(labels[i]);
cardHolder.add(containerPanel, String.valueOf(i));
}
JButton nextButton = new JButton("Next");
nextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardLayout.next(cardHolder);
}
});
JPanel btnHolder = new JPanel();
btnHolder.add(nextButton);
JFrame frame = new JFrame("MultiSizedPanels");
frame.getContentPane().add(cardHolder, BorderLayout.CENTER);
frame.getContentPane().add(btnHolder, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Where component (here a JLabel rather than a JPanel) has it's preferredSize set, then place it in another JPanel.
I hope this helps you.
For instance, I want the program to run multiple times without stopping after somebody has pressed the "Please hit to finish process". However, when I do run the GUI method again, only the first panel shows up. Unsure of why this is happening.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
public class Hotel {
public static JFrame frame;
public static JPanel pan;
public static JPanel endPanel;
public static JPanel buttonPanel;
public static GridBagConstraints c;
public static GridBagConstraints f;
public static JButton econ;
public static Boolean openA = true;
public Hotel(){
Frame();
GUI();
}
public static void Frame(){
frame = new JFrame ("Kiosk");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(600,400);
}
public static void GUI (){
pan = new JPanel(new GridBagLayout());
c = new GridBagConstraints();
frame.add(pan);
JLabel l2 = new JLabel("Please fill out your name and room number");
l2.setVisible(false);
pan.add(l2);
buttonPanel = new JPanel(new GridBagLayout());
GridBagConstraints GB = new GridBagConstraints();
JButton b1 = new JButton("Check in?");
c.gridx=0;
c.gridy=0;
c.insets = new Insets(10,10,10,10);
buttonPanel.add(b1, c);
JButton b2 = new JButton("Check out?");
c.gridx=1;
c.gridy=0;
c.insets = new Insets(10,10,10,10);
buttonPanel.add(b2, c);
frame.add(buttonPanel);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
buttonPanel.setVisible(false);
Checkin();
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
l2.setVisible(true);
b1.setVisible(false);
b2.setVisible(false);
}
});
}
public static void Checkin(){
JLabel name = new JLabel("What is your name?");
c.gridx=0;
c.gridy=0;
pan.add(name,c);
JLabel number = new JLabel("How many people in your party?");
c.gridx=0;
c.gridy=3;
pan.add(number,c);
JTextField namefield = new JTextField(20);
c.insets = new Insets(10,10,10,10);
c.gridx=1;
c.gridy=0;
pan.add(namefield,c);
JTextField numberfield = new JTextField(2);
c.insets = new Insets(10,10,10,10);
c.gridx=1;
c.gridy=3;
pan.add(numberfield,c);
JButton confirm = new JButton("Confirm");
c.insets = new Insets(10,10,10,10);
c.gridx=1;
c.gridy=4;
pan.add(confirm,c);
JPanel errorPanel = new JPanel(new GridBagLayout());
GridBagConstraints d = new GridBagConstraints();
errorPanel.setVisible(false);
frame.add(errorPanel);
JButton econ = new JButton("Confirm");
d.insets = new Insets(10,10,10,10);
d.gridx=1;
d.gridy=4;
errorPanel.add(econ,d);
JLabel error = new JLabel("Sorry you must fill in all the fields");
d.insets = new Insets(10,10,10,10);
d.gridx=1;
d.gridy=0;
errorPanel.add(error,d);
confirm.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if((namefield.getText().equals("")) ||
(numberfield.getText().equals(""))){
pan.setVisible(false);
errorPanel.setVisible(true);
econ.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
errorPanel.setVisible(false);
pan.setVisible(true);
}
});
}
else{
endPanel = new JPanel(new GridBagLayout());
f = new GridBagConstraints();
pan.setVisible(false);
frame.add(endPanel);
String hey = namefield.getText();
Memory(hey);
int people =0;
try {
people = Integer.parseInt(numberfield.getText());
}
catch(NumberFormatException ex)
{
System.out.println("Exception : "+ex);
}
Rooms(people);
}
}
});
}
public static void Memory(String h){
ArrayList<String> Guest = new ArrayList<String>();
for(int x=0;x<Guest.size();x++){
if(Guest.get(x).equals(h)){
JLabel duplicate = new JLabel("Duplicate Name - Please refer
to the manager " + h);
JPanel dupPanel = new JPanel();
pan.setVisible(false);
dupPanel.setVisible(true);
frame.add(dupPanel);
econ.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dupPanel.setVisible(false);
pan.setVisible(true);
}
});
}
else{
JLabel nameLab = new JLabel("Have a nice day " + h);
f.insets = new Insets(10,10,10,10);
f.gridx = 0;
f.gridy=0;
endPanel.add(nameLab);
}
Guest.add(h);
}
}
public static void Rooms(Integer n){
JLabel roomLab = new JLabel("Sorry there are no rooms with that
occupany available");
f.insets = new Insets(10,10,10,10);
f.gridx = 0;
f.gridy=0;
endPanel.add(roomLab,f);
JButton restart = new JButton("Please hit to finish process");
f.insets = new Insets(10,10,10,10);
f.gridx = 0;
f.gridy=4;
endPanel.add(restart,f);
int x=0;
if(openA == true && n<2){
openA = false;
x=1;
}
switch(x){
case 1 : roomLab.setText("You have been assigned room A");
}
restart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
endPanel.setVisible(false);
GUI();
}
});
}
public static void main(String[] args) {
new Hotel();
}
}
If you want to cleanly restart a GUI, and make sure that the new GUI is 100% independent from the previous one, the best way is to dispose of the previous one, and create a brand new instance.
The biggest problem in your case is that all your fields and methods are static. This is wrong. You should typically have something like:
public class Hotel extends JFrame {
public JPanel pan;
...
public Hotel() {
super("Kiosk");
createGUI();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
setSize(600,400);
}
public void createGUI(){
pan = new JPanel(new GridBagLayout());
c = new GridBagConstraints();
add(pan);
...
If you want to restart the GUI, it's then very simple:
restart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dispose();
new Hotel();
}
});
If you just want to reset a particular panel within the frame, you can remove it from its container, and add a new instance:
somepanel.remove(somesubpanel);
somepanel.add(createSubpanel());
Hey I could use help debugging this program. The code is not mine, it is from an answer to a question and I wanted to try it but I get a NullPointerException and can't figure out where the problem is. I think the problem may be image paths but I am not sure so I could use help.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
public class CircleImages {
private int score = 0;
private JTextField scoreField = new JTextField(10);
public CircleImages() {
scoreField.setEditable(false);
final ImageIcon[] icons = createImageIcons();
final JPanel iconPanel = createPanel(icons, 8);
JPanel bottomLeftPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
bottomLeftPanel.add(new JLabel("Score: "));
bottomLeftPanel.add(scoreField);
JPanel bottomRightPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
JButton newGame = new JButton("New Game");
bottomRightPanel.add(newGame);
JButton quit = new JButton("Quit");
bottomRightPanel.add(quit);
JPanel bottomPanel = new JPanel(new GridLayout(1, 2));
bottomPanel.add(bottomLeftPanel);
bottomPanel.add(bottomRightPanel);
newGame.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
reset(iconPanel, icons);
score = 0;
scoreField.setText(String.valueOf(score));
}
});
JFrame frame = new JFrame();
frame.add(iconPanel);
frame.add(bottomPanel, BorderLayout.PAGE_END);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void reset(JPanel panel, ImageIcon[] icons) {
Component[] comps = panel.getComponents();
Random random = new Random();
for(Component c : comps) {
if (c instanceof JLabel) {
JLabel button = (JLabel)c;
int index = random.nextInt(icons.length);
button.setIcon(icons[index]);
}
}
}
private JPanel createPanel(ImageIcon[] icons, int gridSize) {
Random random = new Random();
JPanel panel = new JPanel(new GridLayout(gridSize, gridSize));
for (int i = 0; i < gridSize * gridSize; i++) {
int index = random.nextInt(icons.length);
JLabel label = new JLabel(icons[index]);
label.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
score += 1;
scoreField.setText(String.valueOf(score));
}
});
label.setBorder(new LineBorder(Color.GRAY, 2));
panel.add(label);
}
return panel;
}
private ImageIcon[] createImageIcons() {
String[] files = {"DarkGrayButton.png",
"BlueButton.png",
"GreenButton.png",
"LightGrayButton.png",
"OrangeButton.png",
"RedButton.png",
"YellowButton.png"
};
ImageIcon[] icons = new ImageIcon[files.length];
for (int i = 0; i < files.length; i++) {
icons[i] = new ImageIcon(getClass().getResource("/circleimages/" + files[i]));
}
return icons;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CircleImages();
}
});
}
}
Your problem is here:
icons[i] = new ImageIcon(getClass().getResource("/circleimages/" + files[i]));
You don't have the required images in your project, so getClass().getResource() will return null and you will have a NullPointerException in the constructor of ImageIcon.
What you have to do is put the following files in your project:
/circleimages/DarkGrayButton.png
/circleimages/BlueButton.png
/circleimages/GreenButton.png
/circleimages/LightGrayButton.png
/circleimages/OrangeButton.png
/circleimages/RedButton.png
/circleimages/YellowButton.png
I've been spending so long looking at my computer monitor because I really don't know what to do to prevent the frames on my program on appearing simultaneously when I click the Start button.
Here's my main class:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.Random;
import javax.swing.*;
public class PopQuizDemo {
public static void main (String args[]){
PopQuizDemo();
}
public static void PopQuizDemo(){
final SimpleFrame frame = new SimpleFrame();
final JPanel main = new JPanel();
main.setSize(400,75);
main.setLayout(new GridLayout(3,1));
frame.add(main);
JLabel l1 = new JLabel("Welcome to POP Quiz!");
main.add(l1);
JLabel l2 = new JLabel("Enter your name:");
main.add(l2);
final JTextField name = new JTextField ();
main.add(name);
final JPanel panel = new JPanel();
panel.setSize(400,50);
panel.setLocation(0,225);
frame.add(panel);
JButton start = new JButton ("Start");
panel.add(start);
frame.setVisible(true);
start.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
randomize();
}
});
}
public static void randomize(){
Questions q = new Questions();
int a=0;
Random randnum = new Random (System.currentTimeMillis());
java.util.HashSet<Integer> myset = new java.util.HashSet<>();
for (int count = 1; count <= 3; count++){
while (true) {
a = randnum.nextInt (3);
if(!myset.contains(a)) { myset.add(new Integer(a)); break;}
}
if(a==0){
q.one();
}
else if(a==1){
q.two();
}
else if(a==2){
q.three();
}
else{
break;
}
}
}
}
And here is the class Question where I get the methods one(), two(), and three():
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Questions {
public static void one(){
final SimpleFrame frame = new SimpleFrame();
JPanel p1 = new JPanel();
p1.setSize(400,100);
frame.add(p1);
JLabel qu1 = new JLabel();
qu1.setText("In computers, what is the smallest and basic unit of");
JLabel qu2 = new JLabel();
qu2.setText("information storage?");
p1.add(qu1);
p1.add(qu2);
JPanel p2 = new JPanel();
p2.setSize(400,175);
p2.setLocation(0,100);
p2.setLayout(new GridLayout(2,4));
frame.add(p2);
JButton a = new JButton("a. Bit");
p2.add(a);
JButton b = new JButton("b. Byte");
p2.add(b);
JButton c = new JButton("c. Data");
p2.add(c);
JButton d = new JButton("d. Newton");
p2.add(d);
frame.setVisible(true);
final PopQuizDemo demo = new PopQuizDemo();
a.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
demo.randomize();
}
});
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
demo.randomize();
}
});
c.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
demo.randomize();
}
});
d.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
demo.randomize();
}
});
}//end of method
public static void two(){
final SimpleFrame frame = new SimpleFrame();
JPanel p1 = new JPanel();
p1.setSize(400,100);
frame.add(p1);
JLabel qu1 = new JLabel();
qu1.setText("Machine language is also known as __________.");
p1.add(qu1);
JPanel p2 = new JPanel();
p2.setSize(400,175);
p2.setLocation(0,100);
p2.setLayout(new GridLayout(2,4));
frame.add(p2);
JButton a = new JButton("a. Low level language");
p2.add(a);
JButton b = new JButton("b. Assembly language");
p2.add(b);
JButton c = new JButton("c. High level language");
p2.add(c);
JButton d = new JButton("d. Source code");
p2.add(d);
frame.setVisible(true);
final PopQuizDemo demo = new PopQuizDemo();
a.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
demo.randomize();
}
});
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
demo.randomize();
}
});
c.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
demo.randomize();
}
});
d.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
demo.randomize();
}
});
}//end of method
public static void three(){
final SimpleFrame frame = new SimpleFrame();
JPanel p1 = new JPanel();
p1.setSize(400,100);
frame.add(p1);
JLabel qu1 = new JLabel();
qu1.setText("What is the shortcut key of printing a document for");
JLabel qu2 = new JLabel();
qu2.setText("computers using Windows?");
p1.add(qu1);
p1.add(qu2);
JPanel p2 = new JPanel();
p2.setSize(400,175);
p2.setLocation(0,100);
p2.setLayout(new GridLayout(2,4));
frame.add(p2);
JButton a = new JButton("a. Ctrl + P");
p2.add(a);
JButton b = new JButton("b. Shift + P");
p2.add(b);
JButton c = new JButton("c. Shift + PP");
p2.add(c);
JButton d = new JButton("d. Alt + P");
p2.add(d);
frame.setVisible(true);
final PopQuizDemo demo = new PopQuizDemo();
a.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
demo.randomize();
}
});
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
demo.randomize();
}
});
c.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
demo.randomize();
}
});
d.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
demo.randomize();
}
});
}//end of method
}
The only problem here is that the when I call the method randomize() in the action listener in the Start button, it shows all the frames. Yes, they are not repeating but it shows simultaneously. I don't know where the problem is. Is it with the method randomize, the looping, the questions? Can someone help me? Please? Big thanks.
PS:
This is the class SimpleFrame
import javax.swing.JFrame;
public class SimpleFrame extends JFrame{
public SimpleFrame(){
setSize(400,300);
setTitle("Pop Quiz!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
setResizable(false);
}
}
You can use model dialog to show one after another using a for loop as show below:
public static void main(String[] args) {
JFrame m = new JFrame("Hello");
m.setSize(200,200);
m.setVisible(true);
for(int i=0;i<3;i++) {
JDialog dlg = new JDialog(m,"Dialog",true);
dlg.setSize(100,100);
dlg.show();
}
}