Closing background JFrame after showConfirmDialog - java

I am trying to write a very simple Blackjack game.
This is the class that is supposed to show the currently drawn card:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
public class ShowRandomCard {
JFrame f = new JFrame();
JPanel p = new JPanel();
public void ShowUsARandomCard() {
f.setLayout(new BorderLayout());
p.add(new JLabel("A Panel"));
f.add(p, BorderLayout.NORTH);
// Picture
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(new File("somepicture"));
} catch (IOException e) {
e.printStackTrace();
}
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
f.add(picLabel,BorderLayout.NORTH);
// elements
f.pack();
f.setVisible(true);
Blackjack jt = new Blackjack();
jt.dialog();
}
public void hideCards() {
f.setVisible(false);
f.remove(p);
f.dispose();
f.repaint();
}
}
And this is the actual game class:
import static javax.swing.JOptionPane.*;
public class Blackjack {
ShowRandomCard it = new ShowRandomCard();
public void dialog() {
int answer2 = showConfirmDialog(null, "some message", "some title",
YES_NO_OPTION);
if (answer2 == YES_OPTION) {
garbageCollection();
it.ShowUsARandomCard();
if (answer2 == NO_OPTION || answer2 == CANCEL_OPTION) {
garbageCollection();
// System.exit(0);
}
}
}
public void garbageCollection() {
it.hideCards();
}
}
But the JPanel that holds the cards does not disappear.
Any help would be appreciated.

When you remove a component from a visible frame the basic code is:
panel.remove(...);
panel.revalidate();
panel.repaint();
However, there is rarely a good reason to use code like that. Instead you should be using a Card Layout to hide/show panels.
Method names do not start with an upper case character. "GarbageCollection()" should be GarbageCollection()

Related

Replace ImageIcon with JButton pressed

I am having trouble replacing ImageIcon with a first ImageIcon whereupon a Jbutton is pressed. So far I have tried replacing the frame, .setIcon(myNewImage);, and .remove();. Not sure what to do now... (I'll need to replace and resize them.) Here is my code. (It is supposed to be like one of those Japanese dating games... please ignore that the pictures are local I have no site to host them yet.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.*;
import java.awt.*;
public class NestedPanels extends JPanel {
JPanel southBtnPanel = new JPanel(new GridLayout(3, 2, 1, 1)); //grid layout of buttons and declaration of panel SoutbtnPanel
JButton b = new JButton("Say Hello");//1
JButton c = new JButton("Say You Look Good");//1
JButton d = new JButton("Say Sorry I'm Late");//1
JButton e2 = new JButton("So where are we headed?");//2
JButton f = new JButton("Can we go to your place?");//2
JButton g = new JButton("I don't have any money for our date...");//2
public NestedPanels() { //implemeted class
//add action listener
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button1Clicked(e);//when button clicked, invoke method
}
});
c.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button2Clicked(e);//when button clicked, invoke method
}
});
d.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button3Clicked(e);//when button clicked, invoke method
}
});
e2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button4Clicked(e);//when button clicked, invoke method
}
});
f.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button5Clicked(e);//when button clicked, invoke method
}
});
g.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button6Clicked(e);//when button clicked, invoke method
}
});
southBtnPanel.add(b);
southBtnPanel.add(c);
southBtnPanel.add(d);
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); //layout of buttons "Button text"
setLayout(new BorderLayout());
add(Box.createRigidArea(new Dimension(600, 600))); //space size of text box webapp over all
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {//class to show gui
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
ImageIcon icon = new ImageIcon("C:/Users/wchri/Pictures/10346538_10203007241845278_2763831867139494749_n.jpg");
JLabel label = new JLabel(icon);
mainPanel.add(label);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void button1Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Hey there! Ready to get started?", "Christian feels good!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button2Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Ugh... thanks! You too ready?!", "Christian is a bit... Embarrased.", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button3Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "It's ok! Just make sure it doesn't happen again!", "Christian is a bit angry!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button4Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageTwo = new ImageIcon("C:/Users/wchri/Documents/chrisferry.jpg");
mainPanel.add(label);
label.setIcon(imageTwo);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Let's take the ferry to NYC!", "Christian feels good!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button5Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageThree = new ImageIcon("C:/Users/wchri/Pictures/Screenshots/chrisart.jpg");
mainPanel.add(label);
label.setIcon(imageThree);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Don't you think it's a bit soon for that?", "Christian is embarrassed...", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button6Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageFour = new ImageIcon("C:/Users/wchri/Downloads/chrismoney.jpg");
mainPanel.add(label);
label.setIcon(imageFour);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "I got money!", "Christian is ballin'", JOptionPane.PLAIN_MESSAGE); //display button Action
}
public static void main(String[] args) {
System.out.println("Welcome to Date Sim 1.0 with we1. Are you ready to play? Yes/No?");
Scanner in = new Scanner(System.in);
String confirm = in.nextLine();
if (confirm.equalsIgnoreCase("Yes")) {
System.out.println("Ok hot stuff... Let's start.");
NestedPanels mainPanel = new NestedPanels();
} else {
System.out.println("Maybe some other time!");
return;
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGui();
}
});
}
}
Here is MCVE that demonstrates changing an icon on a JButton when it is clicked:
import java.io.IOException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class ChangeButtonIcon extends JPanel{
private URL[] urls = {
new URL("https://findicons.com/files/icons/345/summer/128/cake.png"),
new URL("http://icons.iconarchive.com/icons/atyourservice/service-categories/128/Sweets-icon.png"),
new URL("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS_FkBgG3_ux0kCbfG8mcRHvdk1dYbZYsm2SFMS01YvA6B_zfH_kg"),
};
private int iconNumber = 0;
private JButton button;
public ChangeButtonIcon() throws IOException {
button = new JButton();
button.setIcon(new ImageIcon(urls[iconNumber]));
button.setHorizontalTextPosition(SwingConstants.CENTER);
button.addActionListener(e -> swapIcon());
add(button);
}
private void swapIcon() {
iconNumber = iconNumber >= (urls.length -1) ? 0 : iconNumber+1;
button.setIcon(new ImageIcon(urls[iconNumber]));
}
public static void main(String[] args) throws IOException{
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(new ChangeButtonIcon());
window.pack();
window.setVisible(true);
}
}
I find writting MCVE a very useful technique. Not only it makes helping much easier, it
is a powerful debugging tool. It many case, while preparing one, you are likely to find the problem.
It should represent the problem or the question asked. Not your application.

Moving from one frame to another

I am new to JAVA swing , where i develop two different JFrame if I click on button frame should move to another frame and previous frame should close by opening of next frame.
I click on button a next frame open but data inside frame is not displaying and previous frame is not closed on button . Please help to find the problem in code.
Frame 1:---------------------------------
package com.demo.test;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import com.demo.gui.TestjigWindow;
public class TestjigWindowCheck extends JFrame{
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public TestjigWindowCheck() {
initUI();
}
private void initUI() {
mainFrame = new JFrame("Fuse Test jig");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(500,500);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
public void showEventDemo(){
//TestjigWindow frame1 = new TestjigWindow();
headerLabel.setText("Fuse Test Jig");
headerLabel.setFont(new Font( "Arial", Font.BOLD, 25));
headerLabel.setBackground(Color.green);
JButton startButton = new JButton("Start");
startButton.setActionCommand("Start");
JButton closeButton = new JButton("Close");
closeButton.setActionCommand("close");
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try
{
if(e.getSource() == startButton)
{
TestjigWindow2 frame2 = new TestjigWindow2();
frame2.setVisible(true);
dispose();
}
else if(e.getSource() == closeButton)
{
System.exit(0);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
closeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try
{
System.exit(0);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
controlPanel.add(startButton);
controlPanel.add(closeButton);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
TestjigWindowCheck test = new TestjigWindowCheck();
test.showEventDemo();
//test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Frame 2----------------------------------- .
package com.demo.test;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class TestjigWindow2 extends JFrame{
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private JPanel controlPanel1;
public TestjigWindow2()
{
prepareGUI();
}
public static void main(String args[])
{
TestjigWindow2 test = new TestjigWindow2();
test.showRadioButton();
}
private void prepareGUI()
{
mainFrame = new JFrame("Fuse Test2 jig");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(500,500);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
public void showRadioButton()
{
headerLabel.setText("Fuse Mode");
final JRadioButton setting =new JRadioButton("Setting");
final JRadioButton testing =new JRadioButton("Testing");
setting.setBounds(75,50,100,30);
testing.setBounds(75,100,100,30);
setting.setMnemonic(KeyEvent.VK_S);
testing.setMnemonic(KeyEvent.VK_T);
ButtonGroup group = new ButtonGroup();
group.add(setting);
group.add(testing);
controlPanel.add(setting);
controlPanel.add(testing);
JButton button = new JButton("Next");
button.setActionCommand("Next");
controlPanel.add(button);
mainFrame.setVisible(true);
}
}
For this problem, I think it's a fairly simple solution, as Andrew commented, you don't need to keep creating JFrames, you can create your JFrame in your first program, and pass it to your second class through the constructor.
Why I think your program is closing is because you are calling dispose() after creating the new frame which might be destroying the components in your new frame.
You could take this approach, which uses only one frame creating in the opening class and carried over to the second class
For Example (using snipplets of your code):
Frame 1
//This is where you are moving to the second frame.
if(e.getSource() == startButton)
{
mainFrame.getContentPane().removeAll(); //removeAll() method wipes all components attached to the contentpane of the frame
//Frame can be reused when passed to second class
TestjigWindow2 frame2 = new TestjigWindow2(this.mainFrame);
}
Frame 2
//In your constructor you could have something like this
private JFrame mainFrame;
/*
* Other variables and constants go here
*
*/
public TestjigWindow2(JFrame mainFrame)
{
this.mainFrame = mainFrame;
prepareGUI();
}
And then in prepareGUI(), you would then be adding your components to your frame, without creating a new frame. With this, your first page will be closed, and the second frame will be open, without you having to creating mutiple JFrames.
You should just create a new Instance of TestjigWindow2 in the actionPerformed method within your first frame. Instead of adding actionPerformed on the startbutton and stopbutton seperately, implement ActionListener interface in your Frame1 class and just keep one method since you are checking for the source inside the method anyways.
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try
{
if(e.getSource() == startButton)
{
TestjigWindow2 frame2 = new TestjigWindow2();
//frame2.setVisible(true); do this inside the frame2 preparegui method
dispose();
}
else if(e.getSource() == closeButton)
{
System.exit(0);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
Also the code will have a more generalized flow if you have the main method inside Frame1 and instantiate the Frame1 in it.
And you don't need to use setVisible inside the actionPerformed of Frame1.

switch to an animation image in cardlayout

I want to create a login dialog. when user press login button it will show a animation image. with some search I find that use cardlayout can switch to another panel so I chose cardlayout for my login dialog. but when a switch to a panel contain a jlabel that have animation image jlabel just load text
here is my code:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author 20133_000
*/
public class Draft9 {
public static void main(String[] args) {
TestCardLayout test = new TestCardLayout();
}
}
class TestCardLayout extends JFrame {
private JPanel mainPanel;
private CardPanel panel1;
private JPanel panel2;
private CardLayout layout;
public TestCardLayout() {
mainPanel = new JPanel();
panel1 = new CardPanel();
panel2 = new JPanel();
layout = new CardLayout();
panel1.add(new JButton("here is panel 1"));
JLabel jLabel1 = new javax.swing.JLabel("here is panel 2",new javax.swing.ImageIcon( "E:\\programming\\programming java\\Netbean Projectr\\Project1\\src\\images\\loading3.gif") , JLabel.CENTER);
jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
//jLabel1.setIcon(new javax.swing.ImageIcon("/images/loading3.gif")); // NOI18N
// jLabel1.setIcon(new javax.swing.ImageIcon("E:\\programming\\programming java\\Netbean Projectr\\Project1\\src\\images\\loading3.gif"));
panel2.add(new JButton("here is panel 2"), BorderLayout.NORTH);
panel2.add(jLabel1, BorderLayout.CENTER);
mainPanel.setLayout(layout);
mainPanel.add("panel1", panel1);
mainPanel.add("panel2", panel2);
add(mainPanel, BorderLayout.CENTER);
setSize(400, 450);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
//layout.show(mainPanel, "panel2");
}
}
class CardPanel extends JPanel {
JButton btnChangePanel;
public CardPanel() {
btnChangePanel = new JButton("show panel 2");
btnChangePanel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
showPanel2();
calculateData();
}
});
add(btnChangePanel);
}
public void showPanel2() {
JPanel parentPanel = (JPanel) getParent();
CardLayout layout = (CardLayout) parentPanel.getLayout();
layout.show(parentPanel, "panel2");
}
public void showPanel1() {
JPanel parentPanel = (JPanel) getParent();
CardLayout layout = (CardLayout) parentPanel.getLayout();
layout.show(parentPanel, "panel1");
}
public void calculateData() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
System.out.println("calculating data...");
//doing some calculate here
Thread.sleep(3000);
System.out.println("done calculting");
//System.exit(0);
int res = 1;
if (res == 1) {
System.out.print("login ok");
showPanel2();
} else {
System.out.print("login failed");
showPanel1();
}
} catch (Exception ex) {
Logger.getLogger(CardPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
when i leave Thread.sleep(3000); comment it work but when i uncomment that line it doesn't work. How can i fix it ?
It's because your image is animated (would work with a normal one) and your Thread.sleep(3000) freezes the whole frame, note that you also can't click the button (or move frame). You could start a new thread to solve this:
public void calculateData() {
new Thread(new Runnable() {
public void run() {
try {
System.out.println("calculating data...");
// doing some calculate here
Thread.sleep(3000);
System.out.println("done calculting");
// System.exit(0);
int res = 1;
if (res == 1) {
System.out.print("login ok");
showPanel2();
} else {
System.out.print("login failed");
showPanel1();
}
} catch (Exception ex) {
Logger.getLogger(CardPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}).start();
}

Repaint many elements with one button click in GUI app

Hello, I've been working on a GUI application that should resize dynamically and change background color multiple times after clicking a button. My first shot was to make a for loop inside an actionPerformed(ActionEvent e) method but it doesn't work properly. Strangely enough, the app changes properly if the listener is removed and the commented code from main function is used. Why is that? This code is actually a simple example of a problem which I've came across making a slightly more complex app. Could You kindly add a line or two if the solution varies if my window consists of many JPanels and I decide to repeatedly change properties of some other elements with one button click?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
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.SwingConstants;
public class TempWindow {
public static void main(String [] args ) {
Frame f = new Frame();
// for (int i = 0; i < 3; i++) {
// if(i == 0) {
// f.getMyPanel().setBackground(Color.red);
// }
// if (i == 1) {
// f.setSize(500, 400);
// f.getMyPanel().setBackground(Color.yellow);
// }
// if( i == 2) {
// f.setSize(100, 200);
// f.getMyPanel().setBackground(Color.green);
// }
//
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// f.repaint();
// }
}
}
class Frame extends JFrame {
MyPanel panel;
JButton but1;
public Frame() {
this.setSize(400, 300);
this.setLocationRelativeTo(null);
this.setLayout(new BorderLayout());
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
but1 = new JButton("Start");
this.getContentPane().add(but1, BorderLayout.NORTH);
panel = new MyPanel();
this.getContentPane().add(panel, BorderLayout.CENTER);
but1.addActionListener(new DanceActionListener(this));
this.setVisible(true);
}
public MyPanel getMyPanel() {
return panel;
}
}
class MyPanel extends JPanel {
JLabel text;
public MyPanel() {
this.setBackground(Color.black);
this.setLayout(new BorderLayout());
text = new JLabel(" xxx ");
text.setFont(new Font(Font.SERIF, Font.BOLD, 40));
this.add(text, BorderLayout.CENTER);
text.setHorizontalAlignment(SwingConstants.CENTER);
text.setVerticalAlignment(SwingConstants.CENTER);
}
}
class DanceActionListener implements ActionListener {
MyPanel panel;
Frame f;
public DanceActionListener(Frame f) {
this.f = f;
this.panel = f.getMyPanel();
}
public void actionPerformed(ActionEvent e ){
for (int i = 0; i < 3; i++) {
if(i == 0) {
panel.setBackground(Color.red);
panel.repaint();
}
if (i == 1) {
panel.setBackground(Color.yellow);
f.setSize(500, 400);
}
if( i == 2) {
f.setSize(100, 200);
panel.setBackground(Color.green);
}
f.repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}

Which timer to use for GUI in Java

I have been trying to find the best timer to use for the following code (note this is a simplified version of my overall program). My hope is to run a method after 3 seconds.
The problem is with the actionPerformed, checkBlankLogin, and resetLoginBlank and putting a timer to delay resetLoginBlank from happening 3 seconds after checkBlankLogin has happened. But I want all methods in the class Outerframe to continuously run. So checkBlankLogin will keep checking if its blank until the person inputs the information for a "Valid Input" and the Login innerframe will close. But I don't know how to do that... Any help there also?
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;
import java.io.*;
import java.io.File;
import java.util.*;
import java.io.FileNotFoundException;
class OuterFrame extends JFrame implements ActionListener
{
Container pane; // container
JDesktopPane outframe; // outer frame
JInternalFrame login; // login frame
//pieces of login frame
JLabel loginLBLtitle;
JPanel loginPanel;
JLabel loginLBLname;
JLabel loginBlankName;
JLabel loginLBLpass;
JLabel loginBlankPass;
JTextField loginTXT;
JPasswordField loginPASS;
JButton loginBUT;
JInternalFrame apple;
OuterFrame()
{
//set up for Outer Frame
super("Application");
setSize(450,240);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
outframe = new JDesktopPane();
outframe.setBackground(Color.BLUE);
//set up for Container
pane = getContentPane();
setContentPane(pane);
pane.add(outframe);
//Login Inner Frame
login = new JInternalFrame();
login.setSize(400,200);
login.setLocation(20,20);
login.setTitle("Member Login");
loginLBLtitle = new JLabel("Sign in with netid and your password.");
Font loginFontbody = new Font("SansSerif", Font.PLAIN, 12);
Font loginFonthead = new Font("SansSerif", Font.BOLD, 13);
loginLBLtitle.setFont(loginFonthead);
loginLBLname=new JLabel("User Name:");
loginLBLname.setFont(loginFontbody);
loginLBLpass=new JLabel("Password: ");
loginLBLpass.setFont(loginFontbody);
loginBUT=new JButton("Login");
loginBUT.setFont(loginFontbody);
loginBUT.addActionListener(this);
loginTXT=new JTextField(20);
loginPASS=new JPasswordField(20);
loginBlankName=new JLabel("");
loginBlankPass=new JLabel("");
loginPanel=new JPanel();
loginPanel.add(loginLBLtitle);
loginPanel.add(loginLBLname);
loginPanel.add(loginTXT);
loginPanel.add(loginBlankName);
loginPanel.add(loginLBLpass);
loginPanel.add(loginPASS);
loginPanel.add(loginBlankPass);
loginPanel.add(loginBUT);
//panel.add(lblmess);
login.add(loginPanel);
login.setVisible(true);
//Add Login to Outer Frame
outframe.add(login);
outframe.setSelectedFrame(login);
pane.add(outframe, BorderLayout.CENTER);
setVisible(true);
loginTXT.requestFocus();
}
public void actionPerformed(ActionEvent e)
{
//problem area
if(e.getSource()==loginBUT)
{
String uname=loginTXT.getText();
String passw=new String(loginPASS.getPassword());
int i=0;
while(i!=5)
{
if(checkBlankLogin(uname,passw,loginBlankName,loginBlankPass))
{
resetLoginBlank(loginBlankName,loginBlankPass);
}
else
{
if(!validateUser("accounts.txt",uname,passw,loginLBLtitle))
{
}
}
}
}
public void resetLoginBlank(JLabel loginBlankName, JLabel loginBlankPass)
{
loginBlankName.setText("");
loginBlankPass.setText("");
}
public void resetLoginTitle(JLabel loginBlankTitle)
{
loginBlankTitle.setText("Sign in with netid and your password.");
loginBlankTitle.setForeground(Color.BLACK);
}
public boolean checkBlankLogin(String name, String passw, JLabel loginBlankName, JLabel loginBlankPass)
{
boolean isBlank=false;
if(name.length()<1)
{
loginBlankMess("User name is required.",loginBlankName);
isBlank=true;
}
if(passw.length()<1)
{
loginBlankMess("Password is required.",loginBlankPass);
isBlank=true;
}
return isBlank;
}
public void loginBlankMess(String mess, JLabel lbl)
{
lbl.setText(mess);
lbl.setForeground(Color.RED);
}
public boolean validateUser(String filename, String name, String password, JLabel title)
{
boolean valid = false;
try
{
File file = new File(filename);
Scanner scanner = new Scanner(file);
ArrayList<String> fileInfo = new ArrayList<String>();
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
fileInfo.add(line);
}
String fullLogin = name + " " + password;
if(fileInfo.contains(fullLogin))
{
//loginBlankMess("Valid login",namemess);
valid=true;
}
if(!valid)
{
loginBlankMess("Please enter valid netid and password.", title);
resetLoginTitle(title);
}
}
catch(Exception ie)
{
System.exit(1);
}
return valid;
}
}
public class TheProgram
{
public static void main(String[] args)
{
new OuterFrame();
}
}`
I would check out the following resource (assuming you using Swing for your UI):
How to Use Swing Timers (Oracle)
Swing timers are the easiest in your case. You make your class implement ActionListener, and create a timer object. The timer will call the actionPerformed method when it expires.
import javax.swing.Timer;
class OuterFrame extends JFrame implements ActionListener{
Timer timer = null;
public void actionPerformed(ActionEvent e) {
if(e.getSource()==loginBUT){
//If the action came from the login button
if (checkBlankLogin()){
timer = new Timer(3000, this);
timer.setRepeats(false);
timer.setInitialDelay(3000);
timer.start();
} else if (timer != null){
timer.stop();
}
}else if(e.getSource()==timer){
//If the action came from the timer
resetLoginBlank(namemess,passwmess));
}
}
}

Categories