I've read the similar questions regarding this problem, tried few methods but none is working.
I have 2 JFrame forms. I want to input information in the first form and submit it to the database. When I click a button, the second form will open and load the information
When I re-input new information in the first form and click the the button again, I want the second form to reload the new information inputted from the database.
This is my code so far.
time t = new time();
private void OrderButtonActionPerformed(java.awt.event.ActionEvent evt) {
if(t.isVisible()){
t.dispose();
t.revalidate();
t.repaint();
t.setVisible(true);
t.setLocationRelativeTo(null);
}
else{
t.setVisible(true);
t.setLocationRelativeTo(null);
}
You don't need to play with JFrames for that. See below example :
JLabel toe = new JLabel("I'm primary text");
JFrame cow = new JFrame("Primary Window");
JPanel cowpanel = new JPanel();
cowpanel.add(toe);
cow.setContentPane(cowpanel);
cow.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
cow.pack();
cow.setVisible(true);
JButton tow = new JButton("Change");
tow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
toe.setText("Hi!, I'm secondary text!");
}
});
JFrame dog = new JFrame("Secondary Window");
JPanel dogPanel = new JPanel();
dog.setContentPane(dogPanel);
dogPanel.add(tow);
dog.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
dog.pack();
dog.setVisible(true);
Clicking the 'Change' button from Frame 2 will change the JLabel's text in Frame 1.
Related
I am developing a card flip flop game in java Swing(using java swing for 1st time). I am using netbeans, I have a menu like new game.. I want that when the user clicks new game button then the game starts. But i dont know how to do this, like when user clicks button , then in event handling action function,is it like this?
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFrame myframe = new JFrame();
//and the game functionality here
}
You are doing the right thing if you want to have a new window open upon click a button. In your sample code, you need to make the new frame visible.
public class NewGame {
public static void main(String[] args) {
JFrame frame = new JFrame("Start up frame");
JButton newGameButton = new JButton("New Game");
frame.setLayout(new FlowLayout());
frame.add(newGameButton);
frame.setVisible(true);
newGameButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFrame newGameWindow = new JFrame("A new game!");
newGameWindow.setVisible(true);
newGameWindow.add(new JLabel("Customize your game ui in the new window!"));
newGameWindow.pack();
}
});
frame.pack();
}
}
I'm trying to make a little game that will first show the player a simple login screen where they can enter their name (I will need it later to store their game state info), let them pick a difficulty level etc, and will only show the main game screen once the player has clicked the play button. I'd also like to allow the player to navigate to a (hopefully for them rather large) trophy collection, likewise in what will appear to them to be a new screen.
So far I have a main game window with a grid layout and a game in it that works (Yay for me!). Now I want to add the above functionality.
How do I go about doing this? I don't think I want to go the multiple JFrame route as I only want one icon visible in the taskbar at a time (or would setting their visibility to false effect the icon too?) Do I instead make and destroy layouts or panels or something like that?
What are my options? How can I control what content is being displayed? Especially given my newbie skills?
A simple modal dialog such as a JDialog should work well here. The main GUI which will likely be a JFrame can be invisible when the dialog is called, and then set to visible (assuming that the log-on was successful) once the dialog completes. If the dialog is modal, you'll know exactly when the user has closed the dialog as the code will continue right after the line where you call setVisible(true) on the dialog. Note that the GUI held by a JDialog can be every bit as complex and rich as that held by a JFrame.
Another option is to use one GUI/JFrame but swap views (JPanels) in the main GUI via a CardLayout. This could work quite well and is easy to implement. Check out the CardLayout tutorial for more.
Oh, and welcome to stackoverflow.com!
Here is an example of a Login Dialog as #HovercraftFullOfEels suggested.
Username: stackoverflow Password: stackoverflow
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
public class TestFrame extends JFrame {
private PassWordDialog passDialog;
public TestFrame() {
passDialog = new PassWordDialog(this, true);
passDialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new TestFrame();
frame.getContentPane().setBackground(Color.BLACK);
frame.setTitle("Logged In");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
});
}
}
class PassWordDialog extends JDialog {
private final JLabel jlblUsername = new JLabel("Username");
private final JLabel jlblPassword = new JLabel("Password");
private final JTextField jtfUsername = new JTextField(15);
private final JPasswordField jpfPassword = new JPasswordField();
private final JButton jbtOk = new JButton("Login");
private final JButton jbtCancel = new JButton("Cancel");
private final JLabel jlblStatus = new JLabel(" ");
public PassWordDialog() {
this(null, true);
}
public PassWordDialog(final JFrame parent, boolean modal) {
super(parent, modal);
JPanel p3 = new JPanel(new GridLayout(2, 1));
p3.add(jlblUsername);
p3.add(jlblPassword);
JPanel p4 = new JPanel(new GridLayout(2, 1));
p4.add(jtfUsername);
p4.add(jpfPassword);
JPanel p1 = new JPanel();
p1.add(p3);
p1.add(p4);
JPanel p2 = new JPanel();
p2.add(jbtOk);
p2.add(jbtCancel);
JPanel p5 = new JPanel(new BorderLayout());
p5.add(p2, BorderLayout.CENTER);
p5.add(jlblStatus, BorderLayout.NORTH);
jlblStatus.setForeground(Color.RED);
jlblStatus.setHorizontalAlignment(SwingConstants.CENTER);
setLayout(new BorderLayout());
add(p1, BorderLayout.CENTER);
add(p5, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
jbtOk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (Arrays.equals("stackoverflow".toCharArray(), jpfPassword.getPassword())
&& "stackoverflow".equals(jtfUsername.getText())) {
parent.setVisible(true);
setVisible(false);
} else {
jlblStatus.setText("Invalid username or password");
}
}
});
jbtCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
parent.dispose();
System.exit(0);
}
});
}
}
I suggest you insert the following code:
JFrame f = new JFrame();
JTextField text = new JTextField(15); //the 15 sets the size of the text field
JPanel p = new JPanel();
JButton b = new JButton("Login");
f.add(p); //so you can add more stuff to the JFrame
f.setSize(250,150);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Insert that when you want to add the stuff in. Next we will add all the stuff to the JPanel:
p.add(text);
p.add(b);
Now we add the ActionListeners to make the JButtons to work:
b.addActionListener(this);
public void actionPerforemed(ActionEvent e)
{
//Get the text of the JTextField
String TEXT = text.getText();
}
Don't forget to import the following if you haven't already:
import java.awt.event*;
import java.awt.*; //Just in case we need it
import java.x.swing.*;
I hope everything i said makes sense, because sometimes i don't (especially when I'm talking coding/Java) All the importing (if you didn't know) goes at the top of your code.
Instead of adding the game directly to JFrame, you can add your content to JPanel (let's call it GamePanel) and add this panel to the frame. Do the same thing for login screen: add all content to JPanel (LoginPanel) and add it to frame. When your game will start, you should do the following:
Add LoginPanel to frame
Get user input and load it's details
Add GamePanel and destroy LoginPanel (since it will be quite fast to re-create new one, so you don't need to keep it memory).
Currently I am calling a method (showFrames) which pops up a JFrame which contains many editable text fields. I am storing the value of these text fields in a list (editedFields) which I need to use in the calling method. My issue is that my calling method is not waiting for the user to select ok/cancel before continuing so the list is not populated when I am trying to take action on it. I tried to overcome this by using a modal dialog to no avail. the method is being called here...
...
showFrames(longToShortNameMap);
if (editedFields != null) {
for (JTextField field : editedFields) {
System.out.println(field.getText());
}
}
...
and the showFrames method is implemented as:
private static void showFrames(Map<String, String> longToShortNameMap) {
final ToolDialog frame = new ToolDialog("Data Changed");
frame.setVisible(true);
frame.setModal(true);
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(400, 500);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
JPanel panel = new JPanel(new GridLayout(0, 2));
JPanel buttonPanel = new JPanel(new GridLayout(2, 0));
List<String> keys = new ArrayList(longToShortNameMap.keySet());
final List<JTextField> textFields = new ArrayList<>();
for (String key : keys) {
JLabel label = new JLabel(key);
JTextField textField = new JTextField(longToShortNameMap.get(key));
panel.add(label);
panel.add(textField);
textFields.add(textField);
}
JButton okButton = new JButton("OK"); //added for ok button
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
editedFields = textFields;
frame.setVisible(false);
frame.dispose();
}
});
JButton cancelButton = new JButton("Cancel");//added for cancel button
cancelButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
frame.dispose();
}
});
okButton.setVisible(true);//added for ok button
cancelButton.setVisible(true);//added for cancel button
buttonPanel.add(okButton);//added for ok button
buttonPanel.add(cancelButton);//added for cancel button
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setVisible(true);
scrollPane.setSize(500, 500);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.SOUTH);
}
the current behavior I observe is that when the JFrame pops up, all the fields will immediately print out instead of waiting for the user to click "OK". Effectively this means I am receiving the default values in the text fields instead of the edited values.
Note: ToolDialog extends JDialog
The basic problem that you have is that you are instantiating the Dialog first, making it visible, and then adding fields to it.
That is essentially incorrect. All objects should be added to it while you are instantiating the Frame/Dialog, preferably in the constructor call. Then, you make it visible when everything is ready.
Of course, you can add a new field to the frame after showing it already, but that is typically done based on some event, for example, when user clicks "Add a new number", then you add new text fields, etc to it.
So, the fix for you is simple, move the logic that adds the buttons, the lists, the panels etc, to the constructor, and then make that window visible.
You have 2 different issues here :
Waiting for a dialog.
Displaying the dialog correctly.
1.- Waiting for a dialog.
You should use a JDialog instead of a JFrame to make the window modal.
The window is not modal because you are showing it before setting it to modal. See JDialog.setModal :
Note: changing modality of the visible dialog may have no effect until
it is hidden and then shown again.
You need to switch theese two lines :
frame.setVisible(true);
frame.setModal(true);
An alternate way is to synchronize with a countdown latch:
CountDownLatch latch = new CountDownLatch(1);
.......
showFrames(longToShortNameMap);
latch.await(); // suspends thread util dialog calls latch.countDown
if (editedFields != null) {
.......
/// Dialog code
latch.countDown(); // place it everywhere you are done with the dialog.
dispose();
2.- Displaying the dialog correctly.
Place frame.setVisible(true) as the last line of showFrames.
Im trying to get it so that when i click on a menu option, the windows changes from the 'welcome text' to 4 buttons which the user can then click on. However, when i click on the simulation button, nothing happens.. the window doesnt change at all.. Ive summarized my code to the basic stuff by the way. anyone see anything i cant?
JFrame GUI = new JFrame("Graphical User Interface");
public gui()
{
JMenuBar menubar = new JMenuBar();
JMenu Simulation = new JMenu("Simulation");
theLabel = new JLabel("Welcome to the Main Menu. ",JLabel.CENTER);
GUI.add(theLabel);
menubar.add(Simulation);
Simulation.add(Simulationmenu);
Simulationmenu.addActionListener(this);
GUI.setJMenuBar(menubar);
GUI.setLocation(500,250);
GUI.setSize(300, 200);
GUI.setVisible(true);
}
public void actionPerformed(ActionEvent E){
if(E.getSource() == Simulationmenu){
// Buttons in the menu i want to output once clicked on 'simulation'
thePanel = new JPanel(new GridLayout(4,0));
Run = new JButton("Run");
Pause = new JButton("Pause");
Reset = new JButton("Reset");
DisplayMaps = new JButton("Display Maps?");
// Add the components to the panel:
thePanel.add("West", Run);
thePanel.add("Center", Pause);
thePanel.add("East", Reset);
thePanel.add("West", DisplayMaps);
// Add the panel to the contentPane of the frame:
GUI.add(thePanel);
// add this object as listener to the two buttons:
Run.addActionListener(this);
Seems your problem in next, you add a new panel(thePanel) to your JFrame(GUI) when it is showing, but in this case you must to call revalidate() method of JFrame(GUI).
Add GUI.revalidate() after GUI.add(thePanel);, it helps you.
I'm trying to make a little game on Java using the Swing components (Boggle-type game).
The way I have it set up right now, it basically opens up to the game right away - but I want to have a start up window with two buttons - "Tutorial" and "Play". I already have the functionality (my Tutorial button just opens a new Window with all the things on it) I'm just not sure how to create a second JFrame and then switch to it when I press Play (or rather, create a JFrame, then switch to the one I've already created when the JButton is pressed). I guess I could cause a new JFrame to open on the same location and the old one to become non-visible - but I was hoping for a simpler solution.
I also want to do this on completion of the game, switching again automatically to a little stat page - so any info will be appreciated.
This is what I have so far in case you guys want to see my code (I haven't yet hooked up the Enter key send the userWord to be validated and scored in my other classes, or filled in the tileGrid with Tile Objects, or the timer.... but that will all come later!)
public class Game implements Runnable {
public void run(){
final JFrame frame = new JFrame("Boggle");
frame.setLocation(500,200);
// Input - holds typing box
final JLetterField typingArea = new JLetterField(1);
typingArea.setFocusTraversalKeysEnabled(false);
typingArea.setEditable(true);
typingArea.setFocusable(true);
typingArea.requestFocusInWindow(); //also this request isn't being granted..
//if anyone could explain why i would love you
// I want the focus on the TextField on startup
frame.add(typingArea, BorderLayout.SOUTH);
typingArea.addKeyListener(new KeyAdapter() {
public void keyPressed (KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) { // enter key is pressed
String userWord = typingArea.getText().toLowerCase();
typingArea.setText("");
}
}
});
final JLabel status = new JLabel("Running...");
// Main playing area
GridLayout tileGrid = new GridLayout(4,4);
final JPanel grid = new JPanel(tileGrid);
frame.add(grid, BorderLayout.CENTER);
// Reset button
final JPanel control_panel = new JPanel();
frame.add(control_panel, BorderLayout.NORTH);
final ImageIcon img = new ImageIcon("Instructions.png", "My Instructions...");
final JButton info = new JButton("Help");
info.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final JFrame infoFrame = new JFrame("Tutorial");
infoFrame.setLocation(500,50);
JLabel tutorialImg = new JLabel(img);
int w = img.getIconWidth();
int h = img.getIconHeight();
infoFrame.setSize(w, h);
infoFrame.add(tutorialImg);
infoFrame.setVisible(true);
}
});
control_panel.add(info);
// Put the frame on the screen
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Game());
}
}
use CardLayout instead of second JFrame, your concept is heading to OutOfMemory
use JFrame.pack(after switch betweens Cards in CardLayout) if you want to change JFrames bounds on runtime,