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();
}
}
Related
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.lang.*;
import java.util.*;
public class Life {
public static void main (String[] args){
JFrame frame = new JFrame("Interest Calculator");
frame.setVisible(true);
frame.setSize(300,100);
frame.setBackground(Color.magenta);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("Simple Interest");
panel.add(button);
button.addActionListener (new Action1());
JButton button2 = new JButton("Compound Interest");
panel.add(button2);
button2.addActionListener (new Action2());
}
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame2 = new JFrame("Simple");
frame2.setVisible(true);
frame2.setSize(300,100);
JPanel panel = new JPanel();
frame2.add(panel);
JButton button = new JButton("Ordinary");
panel.add(button);
button.addActionListener (new Ordinary());
JButton button2 = new JButton("Exact");
panel.add(button2);
button2.addActionListener (new Exact());
}
}
static class Action2 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame3 = new JFrame("Compound Interest");
frame3.setVisible(true);
frame3.setSize(300,100);
JPanel panel = new JPanel();
frame3.add(panel);
JButton button = new JButton("Compounded");
panel.add(button);
JButton button2 = new JButton("Continously");
panel.add(button2);
}
}
static class Ordinary implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame4 = new JFrame("Simple");
frame4.setVisible(true);
frame4.setSize(300,100);
JPanel panel = new JPanel();
frame4.add(panel);
JButton button = new JButton("Approximate");
panel.add(button);
button.addActionListener (new Approximate());
JButton button2 = new JButton("Actual");
panel.add(button2);
}
}
static class Exact implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame5 = new JFrame("Exact");
frame5.setVisible(true);
frame5.setSize(300,100);
JPanel panel = new JPanel();
frame5.add(panel);
JButton button = new JButton("Approximate");
panel.add(button);
JButton button2 = new JButton("Actual");
panel.add(button2);
}
}
static class Approximate implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame6 = new JFrame("Simple");
frame6.setVisible(true);
frame6.setSize(300,100);
JPanel panel = new JPanel();
frame6.add(panel);
frame6.setVisible(true);
frame6.setSize(300,300);
frame6.setLayout(null);
frame6.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField P = new JTextField();
panel.add(P);
P.setText("Enter Principal");
JTextField r = new JTextField();
panel.add(r);
r.setText("Enter Rate");
JTextField t = new JTextField();
panel.add(t);
t.setText("Enter Year");
JButton button = new JButton("Calculate");
panel.add(button);
button.addActionListener (new button());
static class button implements ActionListener {
public void actionPerformed (ActionEvent e) {
float P,r,t,result ;
P = Float.parseFloat(P.getText());
r = Float.parseFloat(r.getText());
t = Float.parseFloat(t.getText());
result = P*r/100*t/360;
button.setText(String.valueof(result));
}
}
}
}
}
So this is my code to create a compound calculator but I have a problem it is the illegal start of expression.please help me for my project.
Below is partially fixed part of the code which causes problems. Next time include full error code, and try to show only relevant part of the code.
ActionListener listener = new ActionListener() {
public void actionPerformed (ActionEvent e) {
float P,r,t,result ;
//P = Float.parseFloat(P.getText()); // P makes no sens here - its float !!! and uninitialized
//r = Float.parseFloat(r.getText()); // same for r
//t = Float.parseFloat(t.getText()); // same for t
result = P*r/100*t/360;
button.setText(String.valueOf(result));
}
};
button.addActionListener (listener);
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());
I am having a weird issue with my initial JFrame login. When I run the program it will only pull up the cancel JButton at first. Then if I minimize the frame it shows everything like it should. Is there a reason for this? If so, how do I fix it?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
public class example
{
public static void main (String[] args)
{
JFrame frame = new JFrame("Login");
frame.setVisible(true);
frame.setSize(350,150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label1 = new JLabel("User Id: ");
JLabel label2 = new JLabel("Password: ");
JTextField txt2 = new JTextField(20);
JButton button = new JButton("login");
JTextField txt = new JTextField(20);
frame.add(label1);
frame.add(txt);
frame.add(label2);
frame.add(txt2);
String user = txt.getText();
String password = txt2.getText();
JButton button2 = new JButton("Cancel");
frame.add(button);
frame.add(button2);
button2.addActionListener (new Action2());
frame.setVisible(true);
frame.setLayout(new FlowLayout());
button.addActionListener(new ActionListener()
{
public void actionPerformed( ActionEvent e)
{
if ("abc".equals(txt.getText()) && "123".equals(txt2.getText()))
{
JFrame frame2 = new JFrame("Student");
frame2.setVisible(true);
frame2.setSize(200,200);
frame.setVisible(false);
}
if ("def".equals(txt.getText()) && "456".equals(txt2.getText()))
{
JFrame frame2 = new JFrame("Instructor");
frame2.setVisible(true);
frame2.setSize(200,200);
frame.setVisible(false);
}
if ("ghi".equals(txt.getText()) && "789".equals(txt2.getText()))
{
JFrame frame2 = new JFrame("Teacher");
frame2.setVisible(true);
frame2.setSize(200,200);
frame.setVisible(false);
}
else
{
System.out.println("Invalid Password");
}
}
});
}
static class Action2 implements ActionListener {
public void actionPerformed (ActionEvent e)
{
System.exit(0);
}
}
}
The setVisible(true) should be the last method call.
Also, it is recommended to run swing applications in their own thread, as specified by the Java spec:
Concurrency in Swing > Initial Threads: docs.oracle.com
So you should ideally run the Swing application as so:
//example from the referenced java documentation
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
For more information about this which might be clearer:
Will the real Swing Single Threading Rule please stand up?
The createAndShowGUI() method is not required, it is an arbitrary method name and its function is to call a method that basically does everything you've already written for your Swing application (with the modification of setVisible(true) invoked at the very end instead.)
So you should do something like this:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
public class example
{
public static void main (String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
//you can alternatively replace 'createAndShowGUI()' with 'new example()'
}
});
}
public static void createAndShowGUI() {
new example();
}
public example() {
JFrame frame = new JFrame("Login");
//frame.setVisible(true);
frame.setSize(350,150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label1 = new JLabel("User Id: ");
JLabel label2 = new JLabel("Password: ");
JTextField txt2 = new JTextField(20);
JButton button = new JButton("login");
JTextField txt = new JTextField(20);
frame.add(label1);
frame.add(txt);
frame.add(label2);
frame.add(txt2);
String user = txt.getText();
String password = txt2.getText();
JButton button2 = new JButton("Cancel");
frame.add(button);
frame.add(button2);
button2.addActionListener (new Action2());
//frame.setVisible(true);
frame.setLayout(new FlowLayout());
button.addActionListener(new ActionListener()
{
public void actionPerformed( ActionEvent e)
{
if ("abc".equals(txt.getText()) && "123".equals(txt2.getText()))
{
JFrame frame2 = new JFrame("Student");
frame2.setVisible(true);
frame2.setSize(200,200);
frame.setVisible(false);
}
if ("def".equals(txt.getText()) && "456".equals(txt2.getText()))
{
JFrame frame2 = new JFrame("Instructor");
frame2.setVisible(true);
frame2.setSize(200,200);
frame.setVisible(false);
}
if ("ghi".equals(txt.getText()) && "789".equals(txt2.getText()))
{
JFrame frame2 = new JFrame("Teacher");
frame2.setVisible(true);
frame2.setSize(200,200);
frame.setVisible(false);
}
else
{
System.out.println("Invalid Password");
}
}
});
frame.setVisible(true);
}
static class Action2 implements ActionListener {
public void actionPerformed (ActionEvent e)
{
System.exit(0);
}
}
}
You should as well edit the button.addActionListener(new ActionListener()
with the appropriate modifications as I have done in the public example() constructor (move the setVisible(boolean) method calls) and also add EXIT_ON_CLOSE for the new JFrames you have created here.
I found this code online and modified it and it stopped working. I'm thinking it has something to do with when I added the Jpanel but what I am doing works best with a JPanel. How do I make it that the events in the action performed if statements work?
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
public class GUI extends JFrame implements ActionListener {
static JPanel panel = new JPanel(new GridLayout(5, 5, 1, 1));
public GUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
//setSize(100, 100);
//setLocation(100, 100);
//Button 1
JButton button1 = new JButton("1");
button1.addActionListener(this);
panel.add(button1);
//Button 2
JButton button2 = new JButton("2");
button2.addActionListener(this);
panel.add(button2);
//Button 3
JButton button3 = new JButton("3");
button3.addActionListener(this);
panel.add(button3);
//Button 2
JButton button4 = new JButton("4");
button4.addActionListener(this);
panel.add(button4);
//Button 2
JButton button5 = new JButton("5");
button5.addActionListener(this);
panel.add(button5);
//Button 2
JButton button6 = new JButton("6");
button6.addActionListener(this);
panel.add(button6);
//Button 2
JButton button7 = new JButton("7");
button7.addActionListener(this);
panel.add(button7);
//Button 2
JButton button8 = new JButton("8");
button8.addActionListener(this);
panel.add(button8);
//Button 2
JButton button9 = new JButton("9");
button9.addActionListener(this);
panel.add(button9);
panel.setVisible(true);
}
public static void main(String[] args) {
new GUI();
JFrame f = new JFrame("Calc");
f.setContentPane(panel);
f.setSize(1000, 1000);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
ArrayList numbers = new ArrayList();
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("button1")) {
myMethod();
numbers.add(1);
System.out.println("1");
}
if (command.equals("button1")) {
numbers.add(2);
System.out.println("2");
}
}
public void myMethod() {
JOptionPane.showMessageDialog(this, "Hello, World!!!!!");
System.out.println("Hey");
}
}
You need to change the part actionPerformed as:
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("1")) {
myMethod();
numbers.add(1);
System.out.println("1");
}
if (command.equals("2")) {
numbers.add(2);
System.out.println("2");
}
}
Here, when a button is clicked, your e.getActionCommand() will give the constructor string. i.e. "1", "2" ,"3" and so on
reference
I put comments in code, but the first thing you should do is to read official tutorials. How to use Buttons
public class GUI /*extends JFrame implements ActionListener*/ {
//don't extend JFrame is you don't have too neither implement ActionListener in top-container classes that breaks single responsability principle
private JPanel panel = new JPanel(new GridLayout(5, 5, 1, 1)); // why static??
public JPanel getPanel(){
return panel;
}
public GUI() {
//i use anonymous classes for this, then you don't have to use if-else
//Button 1
JButton button1 = new JButton("1");
button1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
myMethod();
numbers.add(1);
System.out.println("1");
}
});
panel.add(button1);
//Button 2
JButton button2 = new JButton("2");
button2.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
//put here logic for button2
}
});
panel.add(button2);
//and goo on with other buttons
//panel.setVisible(true); you don't need to call this!!
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI gui = new GUI();
frame.add(gui.getPanel());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private List<Integer> numbers = new ArrayList<>();//use generics!
public void myMethod() {
JOptionPane.showMessageDialog(this, "Hello, World!!!!!");
System.out.println("Hey");
}
}
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.