Stop music when open new JFrame - java

In my application i have add some music to my main Frame. If i click a Jbutton on this Frame it will open a new Jframe but my problem is when i open the new JFrame the music still continue with playing but i want it to stop when the new Jframe is open
Code of my main class:
package View;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import Controller.HomeController;
import music.PlaySound;
public class Home extends JFrame {
private JLabel label, label1, label2;
private JPanel panel;
private JButton logo, logo1, logo2, logo3, logo4, logo5, selectie;
private Container window = getContentPane();
private HomeController Controller;
public Home (){
initGUI();
}
public void addHomeListener(ActionListener a){
selectie.addActionListener(a);
}
public void initGUI(){
PlaySound sound = new PlaySound();
setLayout(null);
setTitle("");
setPreferredSize(new Dimension(800,600));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel();
label.setBounds(0, 0, 266, 800);
label.setBackground(Color.WHITE);
label.setOpaque(true);
window.add(label);
label1 = new JLabel();
label1.setBounds(267, 0, 266, 800);
label1.setBackground(Color.RED);
label1.setOpaque(true);
window.add(label1);
label2 = new JLabel();
label2.setBounds(533, 0, 266, 800);
label2.setBackground(Color.WHITE);
label2.setOpaque(true);
window.add(label2);
logo = new JButton(new ImageIcon("../Ajax/src/img/logotje.gif"));
logo.setBorderPainted(false);
logo.setBounds(40, 150, 188, 188);
label1.add(logo);
logo1 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
logo1.setBorderPainted(false);
logo1.setBounds(10, 50, 82, 82);
label1.add(logo1);
logo2 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
logo2.setBorderPainted(false);
logo2.setBounds(92, 20, 82, 82);
label1.add(logo2);
logo3 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
logo3.setBorderPainted(false);
logo3.setBounds(174, 50, 82, 82);
label1.add(logo3);
logo4 = new JButton(new ImageIcon("../Ajax/src/img/shirt.png"));
logo4.setBorderPainted(false);
logo4.setBounds(50, 50, 135, 182);
label.add(logo4);
logo5 = new JButton(new ImageIcon("../Ajax/src/img/uitshirt.png"));
logo5.setBorderPainted(false);
logo5.setBounds(65, 50, 138, 190);
label2.add(logo5);
selectie = new JButton("Selectie");
selectie.setBounds(60, 500, 99, 25);
selectie.setActionCommand("selectie");
label.add(selectie);
pack();
Controller = new HomeController(this);
addHomeListener(Controller);
setVisible(true);
}
public static void main(String... args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new Home();
}
});
}
}
Code of my new opened Jframe when click on button:
package View;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import music.PlaySound;
import Controller.HomeController;
public class Selectie extends JFrame{
private JLabel label, label1, label2;
private JButton keeper;
private JPanel panel;
private Container window = getContentPane();
public Selectie()
{
initGUI();
}
public void initGUI()
{
setLayout(null);
setTitle("");
setSize(800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel();
label.setBounds(0, 0, 266, 800);
label.setBackground(Color.RED);
label.setOpaque(true);
window.add(label);
label1 = new JLabel();
label1.setBounds(266, 0, 266, 800);
label1.setBackground(Color.BLACK);
label1.setOpaque(true);
window.add(label1);
label2 = new JLabel();
label2.setBounds(532, 0, 266, 800);
label2.setBackground(Color.RED);
label2.setOpaque(true);
window.add(label2);
keeper = new JButton("Kenneth Vermeer");
keeper.setBounds(10, 50, 82, 82);
label.add(keeper);
}
}
Code of my music class:
package music;
import java.io.*;
import javax.sound.sampled.*;
import Controller.HomeController;
import View.Home;
public class PlaySound
{
{
sound = new File("../Ajax/src/sound/Sound.wav"); // Write you own file location here and be aware that it need to be an .wav file
new Thread(play).start();
}
static File sound;
static boolean muted = false; // This should explain itself
static float volume = 100.0f; // This is the volume that goes from 0 to 100
static float pan = 0.0f; // The balance between the speakers 0 is both sides and it goes from -1 to 1
static double seconds = 0.0d; // The amount of seconds to wait before the sound starts playing
static boolean looped_forever = false; // It will keep looping forever if this is true
static int loop_times = 0; // Set the amount of extra times you want the sound to loop (you don't need to have looped_forever set to true)
static int loops_done = 0; // When the program is running this is counting the times the sound has looped so it knows when to stop
final static Runnable play = new Runnable() // This Thread/Runnabe is for playing the sound
{
public void run()
{
try
{
// Check if the audio file is a .wav file
if (sound.getName().toLowerCase().contains(".wav"))
{
AudioInputStream stream = AudioSystem.getAudioInputStream(sound);
AudioFormat format = stream.getFormat();
if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED)
{
format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
format.getSampleRate(),
format.getSampleSizeInBits() * 2,
format.getChannels(),
format.getFrameSize() * 2,
format.getFrameRate(),
true);
stream = AudioSystem.getAudioInputStream(format, stream);
}
SourceDataLine.Info info = new DataLine.Info(
SourceDataLine.class,
stream.getFormat(),
(int) (stream.getFrameLength() * format.getFrameSize()));
SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
line.open(stream.getFormat());
line.start();
// Set Volume
FloatControl volume_control = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);
volume_control.setValue((float) (Math.log(volume / 100.0f) / Math.log(10.0f) * 20.0f));
// Mute
BooleanControl mute_control = (BooleanControl) line.getControl(BooleanControl.Type.MUTE);
mute_control.setValue(muted);
FloatControl pan_control = (FloatControl) line.getControl(FloatControl.Type.PAN);
pan_control.setValue(pan);
long last_update = System.currentTimeMillis();
double since_last_update = (System.currentTimeMillis() - last_update) / 1000.0d;
// Wait the amount of seconds set before continuing
while (since_last_update < seconds)
{
since_last_update = (System.currentTimeMillis() - last_update) / 1000.0d;
}
System.out.println("Playing!");
int num_read = 0;
byte[] buf = new byte[line.getBufferSize()];
while ((num_read = stream.read(buf, 0, buf.length)) >= 0)
{
int offset = 0;
while (offset < num_read)
{
offset += line.write(buf, offset, num_read - offset);
}
}
line.drain();
line.stop();
if (looped_forever)
{
new Thread(play).start();
}
else if (loops_done < loop_times)
{
loops_done++;
new Thread(play).start();
}
}
}
catch (Exception ex) { ex.printStackTrace(); }
}
};
}
Code of my button click class:
package Controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import music.PlaySound;
import View.Home;
import View.Selectie;
public class HomeController implements ActionListener {
private Home home;
public HomeController(Home home){
this.home = home;
}
public void actionPerformed (ActionEvent e){
home.dispose();
Selectie selectie = new Selectie();
selectie.setVisible(true);
}
}

You could set a variable in PlaySound before opening the new frame to indicate that the playback should stop.
static boolean shouldStop = false;
static void stopPlayback() {
shouldStop = true;
}
In the inner loop of PlaySound you quit the loop and the thread terminates.
while ((num_read = stream.read(buf, 0, buf.length)) >= 0) {
if ( shouldStop ) {
break;
}
...
}

Related

Java OpenCV Video capture cut off

i am Brand new to OpenCV in java been trying to create an image capture program which both records the user and allows images to be moved to the captured image area on the GUI, my only issue is the recording seems to be cut off even when I specified a region for where it should be displayed, any help will be highly appricated.
package gesture.recognition;
import com.sun.xml.internal.ws.api.Component;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.*;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.videoio.VideoCapture;
import static org.opencv.videoio.Videoio.CV_CAP_PROP_FRAME_HEIGHT;
import static org.opencv.videoio.Videoio.CV_CAP_PROP_FRAME_WIDTH;
public class GestureRecognition extends javax.swing.JFrame {
private DaemonThread myThread = null;
int count = 0;
VideoCapture webSource = null;
Mat vid = new Mat();
MatOfByte mem = new MatOfByte();
int CANVAS_INITIAL_WIDTH =400;
int CANVAS_INITIAL_HEIGHT =500;
int Video_display=400;
int Button_Area=200;
float h,s,v;
int alpha,r,g,b;
BufferedImage img = null;
File f = null;
Mat hsv = new Mat();
class Canvas extends JPanel
{
// Called every time there is a change in the canvas contents.
public void paintComponent(Graphics g)
{
super.paintComponent(g);
draw(g);
}
}
class DaemonThread implements Runnable
{
protected volatile boolean runnable = false;
#Override
public void run()
{
synchronized(this)
{
while(runnable)
{
if(webSource.grab())
{
try
{
webSource.retrieve(vid);
Imgcodecs.imencode(".jpg", vid, mem);
Image im = ImageIO.read(new ByteArrayInputStream(mem.toArray()));
BufferedImage buff = (BufferedImage) im;
Graphics g=freehandSliderPanel.getGraphics();
if (g.drawImage(im, 0, 0, null));
// if (g.drawImage(buff,0, 0, getWidth(), getHeight() -150 , 0 , 0, buff.getWidth(), buff.getHeight(),null))
if(runnable == false)
{
System.out.println("Going to wait()");
this.wait();
}
}
catch(IOException | InterruptedException ex)
{
System.out.println("Error");
}
}
}
}
}
}
private Canvas canvas;
private JPanel controlPanel;
private JPanel messageArea;
private JButton jButton1;
private JPanel freehandSliderPanel;
public GestureRecognition()
{
setTitle("Gesture Recognition");
setLayout(new BorderLayout()); // Layout manager for the frame.
// Canvas
canvas = new Canvas();
canvas.setBorder(new TitledBorder(new EtchedBorder(), "Video"));
canvas.setPreferredSize(new Dimension(CANVAS_INITIAL_WIDTH, CANVAS_INITIAL_HEIGHT));
add(canvas, BorderLayout.WEST);
controlPanel = new JPanel();
controlPanel.setBorder(new TitledBorder(new EtchedBorder(), "Picture"));
controlPanel.setPreferredSize(new Dimension(Video_display, CANVAS_INITIAL_HEIGHT));
// the following two lines put the control panel in a scroll pane (nicer?).
JScrollPane controlPanelScrollPane = new JScrollPane(controlPanel);
controlPanelScrollPane.setPreferredSize(new Dimension(Video_display + 30, CANVAS_INITIAL_HEIGHT));
add(controlPanelScrollPane, BorderLayout.EAST);
messageArea = new JPanel();
messageArea.setBackground(canvas.getBackground());
messageArea.setBorder(new TitledBorder(new EtchedBorder(), "Message Area"));
messageArea.setPreferredSize(new Dimension(Video_display + CANVAS_INITIAL_WIDTH, Button_Area));
add(messageArea, BorderLayout.SOUTH);
jButton1 = new JButton("Start Video");
jButton1.setPreferredSize(new Dimension(Button_Area - 10, 50));
messageArea.add(jButton1);
freehandSliderPanel = new JPanel();
freehandSliderPanel.setPreferredSize(new Dimension(CANVAS_INITIAL_WIDTH - 20, 90));
canvas.setLayout(new GridLayout(0, 1));
freehandSliderPanel.setBorder(new TitledBorder(new EtchedBorder(), "Display"));
canvas.add(freehandSliderPanel,BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
jButton1.setText("Video Capture");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
}
void draw(Graphics g)
{
}// end draw method
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
webSource =new VideoCapture(0);
myThread = new DaemonThread();
Thread t = new Thread(myThread);
t.setDaemon(true);
myThread.runnable = true;
t.start();
jButton1.setEnabled(false); //start button
// jButton2.setEnabled(true); // stop button
}
public static void main(String args[]) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
GestureRecognition GestureRecognitionInstance = new GestureRecognition();
/*Create and display the form */
/* java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
}
});
*/ }
}
So far it displays the GUI but as you can see it simply cuts off the image like so
Example image

Loop to beginning with JFrame, accessing method in different class

So I'm revising a random number generator I made a while back and instead of making it in JOptionPane, I decided to try to create it in JFrame. The 2 problems I'm having is:
I can't figure out how to access the number of attempts in class "Easy" to use for class "PlayAgain".
How could I loop back to the beginning of the program and start at the Menu screen again if they decide to click btnPlayAgain? Creating a new instance of Menu does not work the way I want it to, as the Menu frame doesn't close after you choose a difficulty.
The code is for the 3 classes, Menu, Easy, and PlayAgain. I didn't include the code for buttons Medium or Hard as it is pretty much identical to Easy.
Menu
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class Menu extends JFrame {
private JPanel contentPane;
public static Menu frame;
public static Easy eFrame;
public static Medium mFrame;
public static Hard hFrame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new Menu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Menu() {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 149);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblSelectADifficulty = new JLabel("Select a difficulty");
lblSelectADifficulty.setBounds(10, 49, 424, 19);
lblSelectADifficulty.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblSelectADifficulty.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lblSelectADifficulty);
JLabel lblRandomNumberGuessing = new JLabel("Random Number Guessing Game");
lblRandomNumberGuessing.setHorizontalAlignment(SwingConstants.CENTER);
lblRandomNumberGuessing.setFont(new Font("Tahoma", Font.PLAIN, 22));
lblRandomNumberGuessing.setBounds(10, 11, 424, 27);
contentPane.add(lblRandomNumberGuessing);
JButton btnEasy = new JButton("Easy (0-100)");
btnEasy.setBounds(10, 79, 134, 23);
contentPane.add(btnEasy);
JButton btnMedium = new JButton("Medium (0-1000)");
btnMedium.setBounds(155, 79, 134, 23);
contentPane.add(btnMedium);
JButton btnHard = new JButton("Hard (0-10000)");
btnHard.setBounds(300, 79, 134, 23);
contentPane.add(btnHard);
btnEasy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
eFrame = new Easy();
eFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
}
}
Easy
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JTextField;
import javax.swing.JButton;
public class Easy extends JFrame {
private JPanel contentPane;
private JTextField textField;
private int rand;
public int attempts;
public Easy() {
attempts = 1;
Random rnd = new Random();
rand = rnd.nextInt(100 + 1);
setResizable(false);
setTitle("Take a guess");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 300, 135);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
final JLabel lblGuessANumber = new JLabel("Guess a number between 0 - 100");
lblGuessANumber.setBounds(10, 11, 274, 19);
lblGuessANumber.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblGuessANumber.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lblGuessANumber);
textField = new JTextField();
textField.setBounds(20, 41, 110, 20);
contentPane.add(textField);
textField.setColumns(10);
final JButton btnGuess = new JButton("Guess");
btnGuess.setBounds(164, 41, 110, 20);
contentPane.add(btnGuess);
final JLabel label = new JLabel("");
label.setFont(new Font("Tahoma", Font.PLAIN, 12));
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setBounds(10, 72, 274, 24);
contentPane.add(label);
btnGuess.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if((Integer.parseInt(textField.getText())) >= 0 && (Integer.parseInt(textField.getText())) <= 100){
if((Integer.parseInt(textField.getText())) < rand){
label.setText("You guessed too low.");
System.out.println(rand);
attempts++;
}
else if((Integer.parseInt(textField.getText())) > rand){
label.setText("You guessed too high.");
attempts++;
}
else if((Integer.parseInt(textField.getText())) == rand){
dispose();
PlayAgain pl = new PlayAgain();
pl.setVisible(true);
}
}
else
label.setText("Please enter a valid input.");
}
});
}
public int returnAttempts(){
return attempts;
}
}
PlayAgain
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class PlayAgain extends JFrame {
private JPanel contentPane;
public PlayAgain() {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 240, 110);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblPlayAgain = new JLabel("Play Again?");
lblPlayAgain.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblPlayAgain.setHorizontalAlignment(SwingConstants.CENTER);
lblPlayAgain.setBounds(10, 27, 214, 23);
contentPane.add(lblPlayAgain);
JButton btnYes = new JButton("Yes");
btnYes.setBounds(10, 49, 89, 23);
contentPane.add(btnYes);
JButton btnQuit = new JButton("Quit");
btnQuit.setBounds(135, 49, 89, 23);
contentPane.add(btnQuit);
//Need to return number of attempts from Easy.java in lblYouGuessedCorrectly
JLabel lblYouGuessedCorrectly = new JLabel("You guessed correctly! Attempts: ");
lblYouGuessedCorrectly.setHorizontalAlignment(SwingConstants.CENTER);
lblYouGuessedCorrectly.setBounds(10, 11, 214, 14);
contentPane.add(lblYouGuessedCorrectly);
btnYes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Need to start the program over again, starting with from the Menu screen
}
});
btnQuit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
}
Suggestions:
You're creating an event-driven Swing GUI, and so you won't "loop" back to the beginning of your program as you would in a linear console program, because that's not how event driven programs work. Rather you'd simply display the menu view when needed, usually in response to some event such as within the ActionListener of a JButton and/or JMenuItem.
So add a reset JButton or JMenuItem or both, have them share the same ResetAction AbstractAction, and inside of that Action, re-show the menu view.
Side recommendation 1 (not related to your main problem): Don't use null layouts or setBounds as that will lead to rigid hard to debug and enhance GUI's that look good on one platform only.
Side recommendation 2: Don't code towards creation of JFrames but rather JPanel views as this will increase the flexibility of your program greatly, allowing you to swap JPanel views if need be using a CardLayout, or displaying views within a JFrame or JDialog or anywhere else they're needed.
For example using a CardLayout to swap JPanel views and a JOptionPane to get user input on re-starting:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class Main2 extends JPanel {
private MenuPanel menuPanel = new MenuPanel(this);
private GamePanel gamePanel = new GamePanel(this);
private CardLayout cardLayout = new CardLayout();
public Main2() {
setLayout(cardLayout);
add(menuPanel, MenuPanel.NAME);
add(gamePanel, GamePanel.NAME);
}
public void setDifficulty(Difficulty difficulty) {
gamePanel.setDifficulty(difficulty);
}
public void showCard(String name) {
cardLayout.show(Main2.this, name);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Main2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Main2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class MenuPanel extends JPanel {
public static final String NAME = "menu panel";
private static final String MAIN_TITLE = "Random Number Guessing Game";
private static final String SUB_TITLE = "Select a difficulty";
private static final int GAP = 3;
private static final float TITLE_SIZE = 20f;
private static final float SUB_TITLE_SIZE = 16;
private Main2 main2;
public MenuPanel(Main2 main2) {
this.main2 = main2;
JLabel titleLabel = new JLabel(MAIN_TITLE, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, TITLE_SIZE));
JPanel titlePanel = new JPanel();
titlePanel.add(titleLabel);
JLabel subTitleLabel = new JLabel(SUB_TITLE, SwingConstants.CENTER);
subTitleLabel.setFont(subTitleLabel.getFont().deriveFont(Font.PLAIN, SUB_TITLE_SIZE));
JPanel subTitlePanel = new JPanel();
subTitlePanel.add(subTitleLabel);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, GAP, GAP));
for (Difficulty difficulty : Difficulty.values()) {
buttonPanel.add(new JButton(new DifficultyAction(difficulty)));
}
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(titlePanel);
add(subTitlePanel);
add(buttonPanel);
}
private class DifficultyAction extends AbstractAction {
private Difficulty difficulty;
public DifficultyAction(Difficulty difficulty) {
this.difficulty = difficulty;
String name = String.format("%s (0-%d)", difficulty.getText(), difficulty.getMaxValue());
putValue(NAME, name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
main2.setDifficulty(difficulty);
main2.showCard(GamePanel.NAME);
}
}
}
enum Difficulty {
EASY("Easy", 100), MEDIUM("Medium", 1000), HARD("Hard", 10000);
private String text;
private int maxValue;
private Difficulty(String text, int maxValue) {
this.text = text;
this.maxValue = maxValue;
}
public String getText() {
return text;
}
public int getMaxValue() {
return maxValue;
}
}
#SuppressWarnings("serial")
class GamePanel extends JPanel {
public static final String NAME = "game panel";
private String labelText = "Guess a number between 0 - ";
private JLabel label = new JLabel(labelText + Difficulty.HARD.getMaxValue(), SwingConstants.CENTER);
private Main2 main2;
GuessAction guessAction = new GuessAction("Guess");
private JTextField textField = new JTextField(10);
private JButton guessButton = new JButton(guessAction);
private boolean guessCorrect = false;
private Difficulty difficulty;
public GamePanel(Main2 main2) {
this.main2 = main2;
textField.setAction(guessAction);
JPanel guessPanel = new JPanel();
guessPanel.add(textField);
guessPanel.add(Box.createHorizontalStrut(10));
guessPanel.add(guessButton);
JPanel centerPanel = new JPanel(new GridBagLayout());
centerPanel.add(guessPanel);
setLayout(new BorderLayout());
add(label, BorderLayout.PAGE_START);
add(centerPanel, BorderLayout.CENTER);
}
public void setDifficulty(Difficulty difficulty) {
this.difficulty = difficulty;
label.setText(labelText + difficulty.getMaxValue());
}
private class GuessAction extends AbstractAction {
private int attempts = 1;
public GuessAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO use difficulty and all to check guesses, and reply to user
// we'll just show the go back to main menu dialog
guessCorrect = true; // TODO: Delete this later
if (guessCorrect) {
String message = "Attempts: " + attempts + ". Play Again?";
String title = "You've Guessed Correctly!";
int optionType = JOptionPane.YES_NO_OPTION;
int selection = JOptionPane.showConfirmDialog(GamePanel.this, message, title, optionType);
if (selection == JOptionPane.YES_OPTION) {
textField.setText("");
main2.showCard(MenuPanel.NAME);
} else {
Window window = SwingUtilities.getWindowAncestor(GamePanel.this);
window.dispose();
}
}
}
}
}

Browse for image file and display it using Java Swing

My problem here is,
after clicking Browse button it displays all files in a directory to choose,
then the chosen image is displayed in GUI correctly. But When i click Browse button
for the second time, it shows the old image only instead of showing the new one. Please help me in this.
For reference, i uploaded the UI.
package GUI;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
#SuppressWarnings("serial")
public class MainAppFrame extends JFrame {
private JPanel contentPane;
File targetFile;
BufferedImage targetImg;
public JPanel panel,panel_1;
private static final int baseSize = 128;
private static final String basePath =
"C:\\Documents and Settings\\Administrator\\Desktop\\Images";
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainAppFrame frame = new MainAppFrame();
frame.setVisible(true);
frame.setResizable(false);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainAppFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 550, 400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
panel = new JPanel();
panel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
contentPane.add(panel, BorderLayout.WEST);
JButton btnBrowse = new JButton("Browse");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
browseButtonActionPerformed(e);
}
});
JLabel lblSelectTargetPicture = new JLabel("Select target picture..");
JButton btnDetect = new JButton("Detect");
btnDetect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
JButton btnAddDigit = new JButton("Add Digit");
btnAddDigit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
JButton button = new JButton("Recognize");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
panel_1 = new JPanel();
panel_1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
GroupLayout gl_panel = new GroupLayout(panel);
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(6)
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addComponent(lblSelectTargetPicture)
.addGap(6)
.addComponent(btnBrowse))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(btnDetect)
.addGap(18)
.addComponent(btnAddDigit))))
.addGroup(gl_panel.createSequentialGroup()
.addGap(50)
.addComponent(button))
.addGroup(gl_panel.createSequentialGroup()
.addContainerGap()
.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 182, GroupLayout.PREFERRED_SIZE))
);
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(7)
.addComponent(lblSelectTargetPicture))
.addGroup(gl_panel.createSequentialGroup()
.addGap(3)
.addComponent(btnBrowse)))
.addGap(18)
.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 199, GroupLayout.PREFERRED_SIZE)
.addGap(22)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(btnDetect)
.addComponent(btnAddDigit))
.addGap(18)
.addComponent(button)
.addContainerGap())
);
panel.setLayout(gl_panel);
}
public BufferedImage rescale(BufferedImage originalImage)
{
BufferedImage resizedImage = new BufferedImage(baseSize, baseSize, BufferedImage.TYPE_INT_RGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, baseSize, baseSize, null);
g.dispose();
return resizedImage;
}
public void setTarget(File reference)
{
try {
targetFile = reference;
targetImg = rescale(ImageIO.read(reference));
} catch (IOException ex) {
Logger.getLogger(MainAppFrame.class.getName()).log(Level.SEVERE, null, ex);
}
panel_1.setLayout(new BorderLayout(0, 0));
panel_1.add(new JLabel(new ImageIcon(targetImg)));
setVisible(true);
}
private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser(basePath);
fc.setFileFilter(new JPEGImageFileFilter());
int res = fc.showOpenDialog(null);
// We have an image!
try {
if (res == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
setTarget(file);
} // Oops!
else {
JOptionPane.showMessageDialog(null,
"You must select one image to be the reference.", "Aborting...",
JOptionPane.WARNING_MESSAGE);
}
} catch (Exception iOException) {
}
}
}
//JPEGImageFileFilter.java
package GUI;
import java.io.File;
import javax.swing.filechooser.FileFilter;
/*
* This class implements a generic file name filter that allows the listing/selection
* of JPEG files.
*/
public class JPEGImageFileFilter extends FileFilter implements java.io.FileFilter
{
public boolean accept(File f)
{
if (f.getName().toLowerCase().endsWith(".jpeg")) return true;
if (f.getName().toLowerCase().endsWith(".jpg")) return true;
if(f.isDirectory())return true;
return false;
}
public String getDescription()
{
return "JPEG files";
}
}
Each time a new image is selected, you're creating components unnecessarily and in error here:
public void setTarget(File reference) {
//....
panel_1.setLayout(new BorderLayout(0, 0));
panel_1.add(new JLabel(new ImageIcon(targetImg)));
setVisible(true);
Instead I would recommend that you have all these components created from the get-go, before any file/image has been selected, and then in this method, create an ImageIcon from the Image, and then simply use this Icon to set the Icon of an already existng JLabel rather than a new JLabel. This is done simply by calling myLabel.setIcon(new ImageIcon(targetImg));
Create an ImageViewer with method like ImageViewer.setImage(Image), display the image in a JLabel.
ImageViewer
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.Random;
public class ImageViewer {
JPanel gui;
/** Displays the image. */
JLabel imageCanvas;
/** Set the image as icon of the image canvas (display it). */
public void setImage(Image image) {
imageCanvas.setIcon(new ImageIcon(image));
}
public void initComponents() {
if (gui==null) {
gui = new JPanel(new BorderLayout());
gui.setBorder(new EmptyBorder(5,5,5,5));
imageCanvas = new JLabel();
JPanel imageCenter = new JPanel(new GridBagLayout());
imageCenter.add(imageCanvas);
JScrollPane imageScroll = new JScrollPane(imageCenter);
imageScroll.setPreferredSize(new Dimension(300,100));
gui.add(imageScroll, BorderLayout.CENTER);
}
}
public Container getGui() {
initComponents();
return gui;
}
public static Image getRandomImage(Random random) {
int w = 100 + random.nextInt(400);
int h = 50 + random.nextInt(200);
BufferedImage bi = new BufferedImage(
w,h,BufferedImage.TYPE_INT_RGB);
return bi;
}
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("Image Viewer");
// TODO Fix kludge to kill the Timer
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final ImageViewer viewer = new ImageViewer();
f.setContentPane(viewer.getGui());
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
ActionListener animate = new ActionListener() {
Random random = new Random();
#Override
public void actionPerformed(ActionEvent arg0) {
viewer.setImage(getRandomImage(random));
}
};
Timer timer = new Timer(1500,animate);
timer.start();
}
};
SwingUtilities.invokeLater(r);
}
}
I modified your code , I hope it will fulfill your requirement. I use MigLayout (it is a Layout manager) to arrange the component.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
public class MyFileChooser
{
JFrame frame;
JPanel panel;
JButton btnBrowse;
JButton change;
JLabel imglabel;
File targetFile;
BufferedImage targetImg;
private static final int baseSize = 128;
private static final String basePath ="/images/fimage";
JPanel panel_1;
ImageIcon icon;
public MyFileChooser()
{
// TODO Auto-generated constructor stub
frame =new JFrame();
frame.setLayout(new MigLayout());
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel=new JPanel(new MigLayout());
panel_1 = new JPanel();
panel_1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(5, 5, 5), 1, true));
panel_1.setBackground(Color.pink);
btnBrowse=new JButton("browse");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
browseButtonActionPerformed(e);
}
});
change=new JButton("Delete");
change.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
changeButtonActionPerformed(e);
}
private void changeButtonActionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
imglabel.revalidate(); //ADD THIS AS WELL
imglabel.repaint(); //ADD THIS AS WELL
imglabel.setIcon(null);
System.out.println("delete button activated");
}
});
imglabel=new JLabel("Image");
imglabel.setSize(100, 100);
imglabel.setBackground(Color.yellow);
frame.add(panel_1,"span,pushx,pushy,growx,growy");
frame.add(btnBrowse);
frame.add(change,"");
//frame.pack();
}
protected void browseButtonActionPerformed(ActionEvent e)
{
JFileChooser fc = new JFileChooser(basePath);
fc.setFileFilter(new JPEGImageFileFilter());
int res = fc.showOpenDialog(null);
// We have an image!
try {
if (res == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
imglabel.setIcon(null);
setTarget(file);
} // Oops!
else {
JOptionPane.showMessageDialog(null,
"You must select one image to be the reference.", "Aborting...",
JOptionPane.WARNING_MESSAGE);
}
} catch (Exception iOException) {
}
}
public BufferedImage rescale(BufferedImage originalImage)
{
BufferedImage resizedImage = new BufferedImage(baseSize, baseSize, BufferedImage.TYPE_INT_RGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, baseSize, baseSize, null);
g.dispose();
return resizedImage;
}
public void setTarget(File reference)
{
try {
targetFile = reference;
targetImg = rescale(ImageIO.read(reference));
} catch (IOException ex) {
// Logger.getLogger(MainAppFrame.class.getName()).log(Level.SEVERE, null, ex);
}
panel_1.setLayout(new BorderLayout(0, 0));
icon=new ImageIcon(targetImg);
imglabel=new JLabel(icon);
panel_1.add(imglabel);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new MyFileChooser();
}
});
}
}
JPEGImageFileFilter class , you can keep this class in same pakage
import java.io.File;
import javax.swing.filechooser.FileFilter;
public class JPEGImageFileFilter extends FileFilter implements FileFilter
{
public boolean accept(File f)
{
if (f.getName().toLowerCase().endsWith(".jpeg")) return true;
if (f.getName().toLowerCase().endsWith(".jpg")) return true;
if(f.isDirectory())return true;
return false;
}
public String getDescription()
{
return "JPEG files";
}
}

issue with fram hiding

I am having trouble hiding a new frame when I am trying to open a new one. At the end of this code there is a call to start() method of another class and I would like this classes frame to be hidden but I cannot seem to access the from from its current location.
package InventoryApp;
//Import
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
*
* #author Curtis
*/
public class JSplash extends JFrame implements ActionListener
{
//declaration of variable objects
Font myFont = new Font("Arial", Font.BOLD, 20);
JButton myButton = new JButton("Click Me!");
Color bgColor = new Color(0,0,255);
Color firstColor = new Color(255,255,255);
String first = "Welcome to DaemoDynamics!";
String last = "Click the Button";
String middle = "";
String middle2 = "";
int count = 1;
//Constructor
public JSplash()
{
super("Item Inventory Application");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout (new BorderLayout());
add(myButton, BorderLayout.SOUTH);
setDefaultLookAndFeelDecorated(true);
getContentPane().setBackground(bgColor);
//adds action listener
myButton.addActionListener(this);
}
//Paint method
#Override
public void paint(Graphics e)
{
super.paint(e);
e.setFont(myFont);
e.setColor(firstColor);
e.drawString(first, 14, 80);
e.drawString(last, 70, 240);
e.drawString(middle, 75, 150);
e.drawString(middle2, 60, 175);
}
public static void begin()
{
final int TALL = 316;
final int WIDE = 304;
JSplash frame = new JSplash();
frame.setSize(WIDE, TALL);
frame.setVisible(true);
}
//Listener Method
#Override
public void actionPerformed(ActionEvent e)
{
//First Time button hit
if(count == 1)
{
middle = "Brighter Business";
middle2 = "for A Brighter Future";
last = "Click Again to Begin";
repaint();
//increases button count
count ++;
}
else//if button count is not 1
{
frame.setVisible(false);
FinalProject.start();
}
}
}
The frame is declare as a local variable, and therefore is out of scope in the actionPerformed() method.

Cannot close frame using button after opening a new one in swing

package bt;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class login extends javax.swing.JFrame implements ActionListener, javax.swing.RootPaneContainer {
private static final long serialVersionUID = 1L;
private JTextField TUserID=new JTextField(20);
private JPasswordField TPassword=new JPasswordField(20);
protected int role;
public JButton bLogin = new JButton("continue");
private JButton bCancel = new JButton("cancel");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new login().createAndShowGUI();
}
});
}
public void createAndShowGUI() {
ImageIcon icon = new ImageIcon("");
JLabel l = new JLabel();
JLabel l2 = new JLabel("(2011)");
l2.setFont(new Font("Courier New", Font.BOLD, 10));
l.setIcon(icon);
JLabel LUserID=new JLabel("Your User ID: ");
JLabel LPassword=new JLabel("Your Password: ");
TUserID.addActionListener(this);
TPassword.addActionListener(this);
TUserID.setText("correct");
TPassword.setEchoChar('*');
TPassword.setText("correct");
bLogin.setOpaque(true);
bLogin.addActionListener(this);
bCancel.setOpaque(true);
bCancel.addActionListener(this);
JFrame f = new JFrame("continue");
f.setUndecorated(true);
f.setSize(460,300);
AWTUtilitiesWrapper.setWindowOpaque(f, false);
AWTUtilitiesWrapper.setWindowOpacity(f, ((float) 80) / 100.0f);
Container pane = f.getContentPane();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS) );
pane.setBackground(Color.BLACK);
Box box0 = Box.createHorizontalBox();
box0.add(Box.createHorizontalGlue());
box0.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
box0.add(l);
box0.add(Box.createRigidArea(new Dimension(100, 0)));
pane.add(box0);
Box box = Box.createHorizontalBox();
box.add(Box.createHorizontalGlue());
box.setBorder(BorderFactory.createEmptyBorder(10, 20, 20, 100));
box.add(Box.createRigidArea(new Dimension(100, 0)));
box.add(LUserID);
box.add(Box.createRigidArea(new Dimension(32, 0)));
box.add(TUserID);
LUserID.setMaximumSize( LUserID.getPreferredSize() );
TUserID.setMaximumSize( TUserID.getPreferredSize() );
pane.add(box);
Box box2 = Box.createHorizontalBox();
box2.add(Box.createHorizontalGlue());
box2.setBorder(BorderFactory.createEmptyBorder(10, 20, 20, 100));
box2.add(Box.createRigidArea(new Dimension(100, 0)));
box2.add(LPassword,LEFT_ALIGNMENT);
box2.add(Box.createRigidArea(new Dimension(15, 0)));
box2.add(TPassword,LEFT_ALIGNMENT);
LPassword.setMaximumSize( LPassword.getPreferredSize() );
TPassword.setMaximumSize( TPassword.getPreferredSize() );
pane.add(box2);
Box box3 = Box.createHorizontalBox();
box3.add(Box.createHorizontalGlue());
box3.setBorder(BorderFactory.createEmptyBorder(20, 20, 0, 100));
box3.add(bLogin);
box3.add(Box.createRigidArea(new Dimension(10, 0)));
box3.add(bCancel);
pane.add(box3);
f.setLocation(450,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBackground(Color.BLACK);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent evt) {
String TBUsername = TUserID.getText();
Object src = evt.getSource();
char[] CHPassword1 = TPassword.getPassword();
String TBPassword = String.valueOf(CHPassword1);
login mLogin = this;
if (src==bLogin) {
if (authenticate(TBUsername,TBPassword)) {
System.out.println(this);
exitApp(this);
} else {
exitApp(this);
}
} else if (src==bCancel) {
exitApp(mLogin);
}
}
public void exitApp(JFrame mlogin) {
mlogin.setVisible(false);
}
private boolean authenticate(String uname, String pword) {
if ((uname.matches("correct")) && (pword.matches("correct"))) {
new MyJFrame().createAndShowGUI();
return true;
}
return false;
}
}
and MyJFrame.java
package bt;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MyJFrame extends javax.swing.JFrame implements ActionListener {
private static final long serialVersionUID = 2871032446905829035L;
private JButton bExit = new JButton("Exit (For test purposes)");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyJFrame().createAndShowGUI();
}
});
}
public void createAndShowGUI() {
JPanel p = new JPanel();
p.setBackground(Color.black);
ImageIcon icon = new ImageIcon("");
JLabel l = new JLabel("(2011)"); //up to here
l.setIcon(icon);
p.add(l);
p.add(bExit);
bExit.setOpaque(true);
bExit.addActionListener(this);
JFrame f = new JFrame("frame");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setUndecorated(true);
p.setOpaque(true);
f.getContentPane().add(p);
f.pack();
f.setSize(1000,600);
Container pane=f.getContentPane();
pane.setLayout(new GridLayout(0,1) );
//p.setPreferredSize(200,200);
AWTUtilitiesWrapper.setWindowOpaque(f, false);
AWTUtilitiesWrapper.setWindowOpacity(f, ((float) 90) / 100.0f);
f.setLocation(300,300);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent evt) {
Object src = evt.getSource();
if (src==bExit) {
System.exit(0);
}
}
}
I cannot get the exitApp() method to work, although it worked before I expanded on my code, I've been trying for hours to get it to work but no avail! The login button suceeds in opening the new frame but will not close the preious(login) frame. It did earlier till I added the validation method etc ....
Create only one JFrame as parent and for another Top-level Containers create only once JDialog (put there JPanel as base), and re-use that for another Action, then you only to remove all JComponents from Base JPanel and add there another JPanel
don't forget for as last lines after switch betweens JPanels inside Base JPanel
revalidate();
repaint();
you can pretty to forgot about that by implements CardLayout

Categories

Resources