I'm trying to achieve the following: Show login window, then from factory to determine what GUIclass to open for instance (admin/dev/tester).
I cannot manage to make the second window pop up; I tried with dispose it closes the program but not runs the main to the end.
main:
public static void main(String[] args){
LoginGui loginGuiWindow = null;
DeveloperGui devGui = null;
TesterGui tesGui = null;
UserCntrl uc = new UserCntrl();
try {
loginGuiWindow = new LoginGui(uc);
} catch (Exception e) {
e.printStackTrace();
}
System.out.print("Checking instance of: ");
if(loginGuiWindow.loggingResult > 0){
System.out.print("Checking instance of: ");
if (uc.user instanceof Developer) {
System.out.println("is instanceOf developer");
devGui = new DeveloperGui(uc);
}
if (uc.user instanceof Tester ) {
System.out.println("is instanceOf tester");
tesGui = new TesterGui(uc);
}
}
}
LoginGui:
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int res;
String nick = textUser.getText();
String pass = textPassword.getText();
if((res = uc.handleLogin(nick, pass)) > 0){
loggingResult = res;
uc.handleUi(res);
frame.setVisible(false);
frame.dispose();
}
else{
JOptionPane.showMessageDialog(frame,
"Wrong username or password.",
"Logging error",
JOptionPane.PLAIN_MESSAGE);
}
}
});
when you are showing a window, its not a blocking call, try setModal(true) before you show it
Make sure LoginGui's dialog is modal.
If it's not, control will return to your original method after making it visible. loggingResult is never > 0, so the "Checking instance of" never runs. Then, when the user finally does log in, that code has already run, and nothing happens.
Making the dialog modal will essentially "pause" on the line where you open the dialog. When the dialog is closed, control will resume from there, which is what you want (in this case)
Related
I am creating an inventory system using java but I am having problem in displaying only one JInternalFrame in my application. I put a condition that will validate if the JInternalFrame is already visible or not and it's working but the problem is that the first clicked doesn't display anything only after the succeeding clicks. Here is my code for calling the JInternalFrame class:
private Planning pFrame;
private void firstWindow()
{
if(pFrame == null)
{
pFrame = new Planning();
Dimension desktopSize = desktop.getSize();
pFrame.setSize(desktopSize);
pFrame.moveToFront();
pFrame.setVisible(true);
desktop.add(pFrame);
try{
pFrame.setMaximum(true);
}catch(Exception e){}
System.out.println("Clicked");
}
if(pFrame.isVisible())
{
pFrame.setVisible(false);
}
else
{
pFrame.setVisible(true);
}
}
After code and try for several hours I found my answer and this is my code that works:
private void firstWindow()
{
if(pFrame == null)
{
pFrame = new Planning();
Dimension desktopSize = desktop.getSize();
pFrame.setSize(desktopSize);
desktop.add(pFrame);
pFrame.setVisible(true);
pFrame.moveToFront();
try{
pFrame.setMaximum(true);
pFrame.setSelected(true);
}catch(Exception e){}
}
else if(!pFrame.isVisible())
{
pFrame.setVisible(true);
pFrame.moveToFront();
}
if(iFrame.isVisible())
{
desktop.remove(iFrame);
iFrame = null;
}
}
private void secondWindow()
{
if(iFrame == null)
{
iFrame = new Inventory();
Dimension desktopSize = desktop.getSize();
iFrame.setSize(desktopSize);
desktop.add(iFrame);
iFrame.setVisible(true);
iFrame.moveToFront();
try{
iFrame.setMaximum(true);
iFrame.setSelected(true);
}catch(Exception e){}
}
else if(!iFrame.isVisible())
{
iFrame.setVisible(true);
iFrame.moveToFront();
}
if(pFrame.isVisible())
{
desktop.remove(pFrame);
pFrame = null;
}
}
Note: I also found a way to close the previous frame when you open other frame class..
And in my internal frame I put this code to make its visibility to false if user clicks the close button.
setDefaultCloseOperation(this.HIDE_ON_CLOSE);
Thanks to the people who helped...
I've created a class to display a modeless dialog box. I want to warn the user of something but I can not prevent them from accessing the application.
In the Test program below, the Dialog will only be created 3 times(same issue i see in my app), then it stops. Have no idea why. if i remove the line dialog.setModalityType(Dialog.ModalityType.MODELESS); ,everything works fine. Another thing is that if I set a breakpoint in the show() method it will hit the breakpoint, if I continue it will show the box 3 more times and stop. Is there something wrong with this code? Don't have much experience with this stuff, but i'm thinking that the while() loop is causing an issue, but I can figure why?
public class JavaApplication6 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
while (true) {
showAlertBox();
}
}
public static void showAlertBox() {
AlertBox box = new AlertBox("Test" , "HI THERE");
int result = box.show();
if (result == JOptionPane.YES_OPTION) {
System.out.println("YES SELECTED");
}
}
}
public class AlertBox {
JOptionPane pane;
JDialog dialog;
Object selectedValue;
String mTitle;
public AlertBox(String title, String alertText) {
pane = new JOptionPane(alertText, JOptionPane.WARNING_MESSAGE, JOptionPane.YES_NO_OPTION, null, null, null);
mTitle=title;
}
public int show() {
dialog = pane.createDialog(null, mTitle );
dialog.setModalityType(Dialog.ModalityType.MODELESS);
dialog.setVisible(true);
selectedValue = pane.getValue();
while (selectedValue == JOptionPane.UNINITIALIZED_VALUE) {
//wait
selectedValue = pane.getValue();
}
if(selectedValue instanceof Integer) {
return ((Integer)selectedValue).intValue();
} else {
return JOptionPane.CLOSED_OPTION;
}
}
}
I am working on a project in which I would like to close a generic JOptionPane programmatically (by not physically clicking on any buttons). When a timer expires, I would like to close any possible JOptionPane that may be open and kick the user back to the login screen of my program. I can kick the user back just fine, but the JOptionPane remains unless I physically click a button on it.
I have looked on many sites with no such luck. A doClick() method call on the "Red X" of the JOptionPane does not seem possible, and using JOptionpane.getRootFrame().dispose() does not work.
Technically, you can loop through all windows of the application, check is they are of type JDialog and have a child of type JOptionPane, and dispose the dialog if so:
Action showOptionPane = new AbstractAction("show me pane!") {
#Override
public void actionPerformed(ActionEvent e) {
createCloseTimer(3).start();
JOptionPane.showMessageDialog((Component) e.getSource(), "nothing to do!");
}
private Timer createCloseTimer(int seconds) {
ActionListener close = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window[] windows = Window.getWindows();
for (Window window : windows) {
if (window instanceof JDialog) {
JDialog dialog = (JDialog) window;
if (dialog.getContentPane().getComponentCount() == 1
&& dialog.getContentPane().getComponent(0) instanceof JOptionPane){
dialog.dispose();
}
}
}
}
};
Timer t = new Timer(seconds * 1000, close);
t.setRepeats(false);
return t;
}
};
This code gotten from
https://amp.reddit.com/r/javahelp/comments/36dv3t/how_to_close_this_joptionpane_using_code/ seems to be the best approach to me. It involves Instantiating the JOptionPane class rather that using the static helper methods to do it for you. The benefit is you have a JOptionPane object that you can dispose when you want to close the dialog.
JOptionPane jop = new JOptionPane();
jop.setMessageType(JOptionPane.PLAIN_MESSAGE);
jop.setMessage("Hello World");
JDialog dialog = jop.createDialog(null, "Message");
// Set a 2 second timer
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(2000);
} catch (Exception e) {
}
dialog.dispose();
}
}).start();
dialog.setVisible(true);
I'm in the process of writing a game. The game plays background music while it is running. This works fine, and I've decided to add a main menu, as their are three types of this game:
Single Player
Two Player
Online
When I run these classes individually (which have their own main methods - obviously), they work perfectly fine. However, in my Welcome Menu class, which is responsible for the main menu (all necessary imports are there, just not shown here):
public class WelcomeMenu implements ActionListener {
public void setButtonBG(JButton button, String imgPath) throws IOException //this method is reponsible for setting images to their corresponding JButton(s)
{
BufferedImage img = ImageIO.read(ClassLoader.getSystemResource(imgPath));
ImageIcon sp = new ImageIcon(img);
button.setIcon(sp);
button.setBorderPainted(false);
}
private JFrame welcomeWindow = new JFrame("Tic-Tac-Toe");
private JButton singlePlayerButton = new JButton();
private JButton twoPlayerButton = new JButton();
private JButton onlineButton = new JButton();
public WelcomeMenu() throws IOException
{
//START OF CONSTRUCTOR
//Main window is being sized, default way to close, and internal layout
welcomeWindow.setSize(600, 420);
welcomeWindow.setLayout(new CardLayout());
//Object res = this.getClass().getResource("/");
//System.out.println(res);
BufferedImage bf = ImageIO.read(ClassLoader.getSystemResource("images/mainMenuBG.jpg"));
welcomeWindow.setContentPane(new backImage(bf)); // adding created component to the JFrame using the backImage class
welcomeWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
welcomeWindow.setLocationRelativeTo(null);
welcomeWindow.setResizable(false);
welcomeWindow.setVisible(true);
//setting the icon
try
{
java.net.URL url = ClassLoader.getSystemResource("images/icon.png");
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.createImage(url);
welcomeWindow.setIconImage(img);
}
catch(NullPointerException n)
{
System.out.println("Image could not be fetched.");
}
//adding custom buttons
//ImageIcon singlePlayer = new ImageIcon("images/singlePlayerButton.jpg");
//setting sizes
singlePlayerButton.setSize(387, 72);
twoPlayerButton.setSize(387, 72);
onlineButton.setSize(387, 72);
//setting background images to buttons
setButtonBG(singlePlayerButton, "images/sPlayerButton.jpg");
setButtonBG(twoPlayerButton, "images/tPlayerButton.jpg");
setButtonBG(onlineButton, "images/mPlayerButton.jpg");
//adding listeners
singlePlayerButton.addActionListener(this);
twoPlayerButton.addActionListener(this);
onlineButton.addActionListener(this);
//adding the custom buttons
welcomeWindow.add(singlePlayerButton);
welcomeWindow.add(twoPlayerButton);
welcomeWindow.add(onlineButton);
//setting locations and visibility
singlePlayerButton.setLocation(110, 90);
singlePlayerButton.setVisible(true);
twoPlayerButton.setLocation(110, 182);
twoPlayerButton.setVisible(true);
onlineButton.setLocation(110, 274);
onlineButton.setVisible(true);
//END OF CONSTRUCTOR
}
public static TicTacToeTP spg;
//All actions are done here
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == singlePlayerButton)
{
System.out.println("<LOG> SINGLE PLAYER GAME REQUESTED");
JOptionPane.showMessageDialog(welcomeWindow, "This game mode has not been implemented yet.");
}
if(e.getSource() == twoPlayerButton)
{
System.out.println("<LOG> TWO PLAYER GAME REQUESTED");
try
{
//spg = new TicTacToeTP("images/black-squareMod_RED.jpg");
//spg.playBackgroundSong();
TicTacToeTP.main(null);
}
catch(IOException io)
{
System.out.println("IO EXCEPTION!");
}
welcomeWindow.setVisible(false);
welcomeWindow.dispose();
}
if(e.getSource() == onlineButton)
{
System.out.println("<LOG> ONLINE GAME REQUESTED");
JOptionPane.showMessageDialog(welcomeWindow, "This game mode has not been implemented yet.");
}
}
public static void main(String[] args) throws IOException
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex)
{
}
}
});
new WelcomeMenu();
}
}
... if I click the Two Player button, for example, it plays the audio ONLY. None of my other components load. Just an empty JFrame. Notice how in the actionPerformed() method, I tried both TicTacToeTP.main(null) and (commented out, now) instantiating a new TicTacToeTP object AND calling the playBackgroundSong() method. If I eliminate this methods call, and just instantiate the object, it works fine - but no music.
Why is this happening, and how can I fix it?
Here is the playBackgroundSong() method:
private Player p = null;
//private InputStream fis = null;
public void playBackgroundSong() //responsible for playing background music
{
//PausablePlayer p = null;
InputStream fis = null;
ArrayList<InputStream> stream = new ArrayList<InputStream>(); //this ArrayList contains multiple audio files that the method will loop through >> defined below
stream.add(ClassLoader.getSystemResourceAsStream("resources/01 Intro.mp3"));
stream.add(ClassLoader.getSystemResourceAsStream("resources/Basic space - The XX - Instrumental.mp3"));
stream.add(ClassLoader.getSystemResourceAsStream("resources/Mirrors [ Upbeat Electronic Instrumental ] Spence Mills HQ Free Beat Download 2012.mp3"));
stream.add(ClassLoader.getSystemResourceAsStream("resources/Static [ Aggressive Dark Pop Hip Hop Rap Instrumental ] Spence Mills Free Beat Download Link 2012 HD.mp3"));
stream.add(ClassLoader.getSystemResourceAsStream("resources/System Shock 2 soundtrack Med Sci 1.mp3"));
stream.add(ClassLoader.getSystemResourceAsStream("resources/System Shock 2 Soundtrack Ops 2.mp3"));
stream.add(ClassLoader.getSystemResourceAsStream("resources/01 Intro.mp3"));
Collections.shuffle(stream);
for(int i = 0; i < stream.size(); i++)
{
try
{
fis = stream.get(i);
}
catch (NullPointerException ex)
{
Logger.getLogger(TicTacToeTP.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
p = new Player(fis);
}
catch (JavaLayerException ex)
{
Logger.getLogger(TicTacToeTP.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
p.play();
}
catch (JavaLayerException ee)
{
Logger.getLogger(TicTacToeTP.class.getName()).log(Level.SEVERE, null, ee);
}
}
playBackgroundSong();
}
You appear to be playing a long-running bit of code, playBackgroundSong(), on the Swing event dispatch thread or EDT. This thread is responsible for painting the GUI and interacting and responding to user input, and if it gets tied up, the program essentially freezes. This might not have been an issue when you called this method in the main method -- basically off of the Swing event thread, but is an issue when it is specifically called on the event dispatch thread. A possible solution: play your music in a background thread. A SwingWorker might work well for you, and there are decent tutorials on the use of these and the EDT. Google "Concurrency in Swing", and check out what will likely be the first hit for more.
As an aside: you usually don't want to call another class's main method. Instead create an instance of the other class and use it.
Edit You state:
Thanks. Looking at this part: docs.oracle.com/javase/tutorial/uiswing/concurrency/simple.html Seems to explain what I want to do, correct? I am reading it all, by the way
Actually you could go even simpler. Since you're not waiting for a result from your playBackgroundSong(), you could possibly just call it in its own simple thread by just wrapping it in a Runnable and then putting that in a Thread:
new Thread(new Runnable() {
public void run() {
playBackgroundSong();
}
}).start();
I am working on a simple J2ME application and i have a StringItem linked to a terms and conditions page online.
I have the StringItem setup and it appears underlined (giving the feeling that it is linked); but when i click on it, it does not perform any action.
Find below my code:
public class mobiMidlet extends MIDlet implements CommandListener {
private Display display;
private TextField userName,password;
public Form form;
private Command login, register, forgot, terms, cancel;
private Image img_error, img_login, img_register, img_forgot, img_terms;
private String termsurl = "http://example.com/terms.php";
private StringItem termsItem;
public mobiMidlet() {
form = new Form("Welcome to My App");
termsItem = new StringItem("", "Terms and Conditions", Item.HYPERLINK);
termsItem.setDefaultCommand(new Command("terms", Command.ITEM, 1));
ItemCommandListener listener = new ItemCommandListener() {
public void commandAction(Command cmd, Item item) {
if(cmd==terms)
{
try {
platformRequest(termsurl);
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
termsItem.setItemCommandListener(listener);
userName = new TextField("LoginID:", "", 30, TextField.ANY);
password = new TextField("Password:", "", 30, TextField.PASSWORD);
cancel = new Command("Cancel", Command.CANCEL, 2);
login = new Command("Login", Command.OK, 2);
try{
img_login = Image.createImage("/logo.jpg");
img_register = Image.createImage("/error2.png");
img_forgot = Image.createImage("/logo.jpg");
img_register = Image.createImage("/error2.png");
}catch(Exception e){
System.out.println(e.getMessage());
}
}
public void startApp() {
display = Display.getDisplay(this);
form.append(termsItem);
form.append(userName);
form.append(password);
form.addCommand(cancel);
form.addCommand(login);
form.setCommandListener(this);
display.setCurrent(form);
}
public void commandAction(Command c, Displayable d) {
String label = c.getLabel();
if(label.equals("Cancel")) {
destroyApp(true);
} else if(label.equals("Login")) {
validateUser(userName.getString(), password.getString());
}
}
}
How can I fix this so that when I click on the terms and conditions link, it opens the page on a browser?
You have not initialized variable terms, so it remains null. Therefore condition cmd==terms is always false and you never enter the if statement.
Separate line termsItem.setDefaultCommand(new Command("terms", Command.ITEM, 1)); to two:
terms = new Command("terms", Command.ITEM, 1);
termsItem.setDefaultCommand(terms);
Now you have a chance.
BTW why not to debug you program? Run it in emulator, put break point into commandAction and see what happens.