Hello I am writing a sort of Menu for an encryption program I am writing. I finished the core of it, and now i want to try to create a GUI for it. Here is the code for the first Menu:
package matrix_with_GUI;
import javax.swing.*;
import java.awt.event.* ;
import java.awt.* ;
public class Main_Menu extends JFrame implements ActionListener{
private JButton action1 = new JButton ("");
private JButton action2 = new JButton ("");
private JPanel pane = new JPanel();
private JLabel lbl;
public static void main(String[] args) {
Main_Menu main = new Main_Menu();
}
public Main_Menu(){
super();
JPanel pane=new JPanel();
setTitle ("Start Menu") ;
JFrame frame = new JFrame("");
setVisible(true);
setSize (380, 260) ;
setLocation (450, 200) ;
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) ;
action1 = new JButton("Start");
action2 = new JButton("Exit");
lbl = new JLabel ("Welcome to the Matrix Encoder/Decoder!!!");
setLayout(new FlowLayout());
add (lbl) ;
add(action1, BorderLayout.CENTER);
action1.addActionListener (this);
add(action2, BorderLayout.CENTER);
action2.addActionListener (this);
}
#Override
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
OptionsMenu x = new OptionsMenu();
if (event.getSource() == action1)
{
System.exit(0);
x.OptionsMenu();
}
else if(event.getSource() == action2){
System.exit(0);
}
}
}
When the Start Button is clicked, the new menu comes up all fine and good, but the first menu stays open. Is there a way to close this first menu AND open the second menu with the first button click? I'm very new to GUI so the simplest solution would be very helpful. On a side note is there a simple way to move the Start button to the next line? Thanks
You have 2 options: you can use a Window Listener, or you can use the dispose() method. To do the dispose() just type
* This is better to be used with subframes and 2nd level windows.*
this.dispose();
or check this link for using the window listener
Closing JFrame
In order to close the Main_Menu, you can just call its dispose method:
this.dispose();
instead of calling System.exit(0), which will terminate the JVM altogether.
Related
I'm working on an assignment for class where we need to create a JComboBox and each option opens a new window where you can do whatever you want on those new windows. Please keep in mind I'm very new to GUI and new to Java in general, in case my questions are dumb.
I have a question and an issue...
My question:
When the user selects "The Matrix" option a new window pops up with a quote and two buttons. Right now I have two JPanels (panel and panel2) panel adds the quote to the NORTH position and then panel2 adds the two buttons to the CENTER position both using BorderLayout. My question is am I doing this correctly...Could I use just panel to add the quote and the buttons or is it necessary to create separate panels for separate items being added to the JFrame? When I had them both added to the same panel the quote was not on the window when I ran the program.
panel.add(matrixQuote);
newFrame.add(panel, BorderLayout.NORTH);
That's how I had it when it wasn't showing up ^^^
I GOT THE ISSUE WITH CLEARING THE JFRAME FIXED
I am trying to add an ActionListener to the bluePill button and instead of opening another new window I thought I could clear everything from the existing window when the button is pressed and then display something new on said window. The only info I could find on this is how I have it in the actionPerformed method below. I'll post a snippet of what I'm talking about directly below and then all my code below that just in case.
All my code...
public class MultiForm extends JFrame{
private JComboBox menu;
private JButton bluePill;
private JButton redPill;
private JLabel matrixQuote;
private int matrixSelection;
private JFrame newFrame;
private JPanel panel;
private JPanel panel2;
private static String[] fileName = {"", "The Matrix", "Another Option"};
public MultiForm() {
super("Multi Form Program");
setLayout(new FlowLayout());
menu = new JComboBox(fileName);
add(menu);
TheHandler handler = new TheHandler();
menu.addItemListener(handler);
}
public void matrixPanel() {
TheHandler handler = new TheHandler();
//Create a new window when "The Matrix" is clicked in the JCB
newFrame = new JFrame();
panel = new JPanel();
panel2 = new JPanel();
newFrame.setLayout(new FlowLayout());
newFrame.setSize(500, 300);
newFrame.setDefaultCloseOperation(newFrame.EXIT_ON_CLOSE);
matrixQuote = new JLabel("<html>After this, there is no turning back. "
+ "<br>You take the blue pill—the story ends, you wake up "
+ "<br>in your bed and believe whatever you want to believe."
+ "<br>You take the red pill—you stay in Wonderland, and I show"
+ "<br>you how deep the rabbit hole goes. Remember: all I'm "
+ "<br>offering is the truth. Nothing more.</html>");
panel2.add(matrixQuote);
newFrame.add(panel2, BorderLayout.NORTH);
//Blue pill button and picture.
Icon bp = new ImageIcon(getClass().getResource("Blue Pill.png"));
bluePill = new JButton("Blue Pill", bp);
panel2.add(bluePill);
bluePill.addActionListener(handler);
//Red pill button and picture
Icon rp = new ImageIcon(getClass().getResource("Red Pill.png"));
redPill = new JButton("Red Pill", rp);
panel2.add(redPill);
newFrame.add(panel2, BorderLayout.CENTER);
newFrame.setVisible(true);
}
private class TheHandler implements ItemListener, ActionListener{
public void itemStateChanged(ItemEvent IE) {
//listen for an item to be selected.
if(IE.getStateChange() == ItemEvent.SELECTED) {
Object selection = menu.getSelectedItem();
if("The Matrix".equals(selection)) {
matrixPanel();
}
else if("Another Option".equals(selection)) {
}
}
}
public void actionPerformed(ActionEvent AE) {
if(AE.getSource() == bluePill) {
newFrame.remove(panel);
newFrame.remove(panel2);
newFrame.repaint();
}
}
}
//MAIN
public static void main(String[] args) {
MultiForm go = new MultiForm();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(400, 200);
go.setVisible(true);
}
}
Use a Card Layout. You can swap panels as required.
The tutorial has a working example.
You can use:
jpanel.removeAll();
Either to delete a certain JComponent by using the JComponent itself like:
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
frame.remove(panel);
panel.getGraphics().clearRect(0, 0, panel.getWidth(), panel.getHeight());
I'm creating a Java GUI using Swing with Eclipse and Window Builder Pro. I'm using JButtons and JToggleButtons. I want to change toggle button's state from another button.
For example, when I click the clear grid, all the toggle buttons will be 'not selected'.
How can I do this? What are the methods that I have to use for toggle buttons and buttons?
toggleButton.setSelected(boolean b)
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractButton;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
public class JToggleButtonAction {
public static void main(String args[]) {
JFrame frame = new JFrame("Selecting Toggle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JToggleButton toggleButton = new JToggleButton("Toggle Button");
final JToggleButton toggleButton1 = new JToggleButton("Another Toggle Button");
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
boolean selected = abstractButton.getModel().isSelected();
System.out.println("Action - selected=" + selected + "\n");
toggleButton1.setSelected(selected);
}
};
toggleButton.addActionListener(actionListener);
frame.add(toggleButton, BorderLayout.NORTH);
frame.add(toggleButton1, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}
Add actionListener to your JButton and in actionPerformed(ActionEvent) method change the state of all JToggleButtons. Make sure all your JToggleButton is accessible in this method. A simple example will be..
JFrame frame = new JFrame("Panel image demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLayout(new FlowLayout());
final JToggleButton[] button = new JToggleButton[10];
for (int i = 0; i < button.length; i++) {
button[i] = new JToggleButton("Toggle Us");
frame.add(button[i]);
}
JButton jButton = new JButton("Toggle that button");
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (JToggleButton jToggleButton : button) {
jToggleButton.setSelected(!jToggleButton.isSelected()); // <-- this will change the state of toggle button
}
}
});
frame.add(jButton);
frame.setVisible(true);
Register an ActionListener to the JButton instance and make sure you can access the toggle buttons therein to manipulate their state.
i was looking for this, this might help somebody out
B1.setSelected(false);
i made a method that make all my button false (unselect the toggles when i wanted it)
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).
A typical way to use JFileChooser includes checking whether user clicked OK, like in this code:
private void addModelButtonMouseClicked(java.awt.event.MouseEvent evt) {
JFileChooser modelChooser = new JFileChooser();
if(modelChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION ){
File selectedFile = modelChooser.getSelectedFile();
if(verifyModelFile(selectedFile)){
MetModel newModel;
newModel = parser.parse(selectedFile, editedCollection.getDirectory() );
this.editedCollection.addModel(newModel);
this.modelListUpdate();
}
}
}
I tried to mimic this behavior in my own window inheriting JFrame. I thought that this way of handling forms is more convenient than passing collection that is to be edited to the new form. But I have realized that if I want to have a method in my JFrame returning something like exit status of it I need to make it wait for user clicking OK or Cancel without freezing the form/dialog window.
So, how does showOpenDialog() work? When I tried to inspect the implementation, I found only one line methods with note "Compiled code".
I tried to mimic this behavior in my own window inheriting JFrame.
JFrame is not a modal or 'blocking' component. Use a modal JDialog or JOptionPane instead.
E.G.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
/** Typical output:
[JTree, colors, violet]
User cancelled
[JTree, food, bananas]
Press any key to continue . . .
*/
class ConfirmDialog extends JDialog {
public static final int OK_OPTION = 0;
public static final int CANCEL_OPTION = 1;
private int result = -1;
JPanel content;
public ConfirmDialog(Frame parent) {
super(parent,true);
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.setBorder(new EmptyBorder(5,5,5,5));
content = new JPanel(new BorderLayout());
gui.add(content, BorderLayout.CENTER);
JPanel buttons = new JPanel(new FlowLayout(4));
gui.add(buttons, BorderLayout.SOUTH);
JButton ok = new JButton("OK");
buttons.add(ok);
ok.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
result = OK_OPTION;
setVisible(false);
}
});
JButton cancel = new JButton("Cancel");
buttons.add(cancel);
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
result = CANCEL_OPTION;
setVisible(false);
}
});
setContentPane(gui);
}
public int showConfirmDialog(JComponent child, String title) {
setTitle(title);
content.removeAll();
content.add(child, BorderLayout.CENTER);
pack();
setLocationRelativeTo(getParent());
setVisible(true);
return result;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("Test ConfirmDialog");
final ConfirmDialog dialog = new ConfirmDialog(f);
final JTree tree = new JTree();
tree.setVisibleRowCount(5);
final JScrollPane treeScroll = new JScrollPane(tree);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b = new JButton("Choose Tree Item");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
int result = dialog.showConfirmDialog(
treeScroll, "Choose an item");
if (result==ConfirmDialog.OK_OPTION) {
System.out.println(tree.getSelectionPath());
} else {
System.out.println("User cancelled");
}
}
});
JPanel p = new JPanel(new BorderLayout());
p.add(b);
p.setBorder(new EmptyBorder(50,50,50,50));
f.setContentPane(p);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
});
}
}
I guess you wait for the user to click some button by constantly checking what button is pressed.
"I need to make it wait for user clicking OK or Cancel without freezing the form/dialog window."
May be you should use evens to get notified, when the user clicks on something, not waiting for them to press the button - maybe there is some OnWindowExit event?
Or maybe something like this:
MyPanel panel = new MyPanel(...);
int answer = JOptionPane.showConfirmDialog(
parentComponent, panel, title, JOptionPane.YES_NO_CANCEL,
JOptionPane.PLAIN_MESSAGE );
if (answer == JOptionPane.YES_OPTION)
{
// do stuff with the panel
}
Otherwise you might see how to handle window events, especially windowClosing(WindowEvent) here
i am trying to make an actionListener on a button in another button which has also an actionlistener and i just couldn't figure it out for some way. I am trying to make an action on the 2nd button but i couldn't figure it out.If anyone helps me i'd appreciate! here is the code below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class basic implements ActionListener{
public static void main(String[] args) {
basic process = new basic ();
}
public basic(){
JFrame fan = new JFrame("Scheme");
JPanel one = new JPanel(new BorderLayout());
fan.add(one);
JPanel uno = new JPanel();
uno.setLayout(new BoxLayout(uno, BoxLayout.Y_AXIS));
JButton addB = new JButton("first choice");
addB.setAlignmentX(Component.CENTER_ALIGNMENT);
uno.add(addB);
addDButton.setActionCommand("hehe");
addDButton.addActionListener(this);
one.add(uno,BorderLayout.CENTER);
fan.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fan.setSize(500,700);
fan.setLocationByPlatform(true);
fan.setVisible(true);
}
public void actionPerformed(ActionEvent evt) {
JPanel markP = new JPanel(new FlowLayout(FlowLayout.RIGHT,10,20));
JDialog dialog = new JDialog((JFrame)null);
dialog.getContentPane().add(markP,BorderLayout.CENTER);
if (evt.getActionCommand().equals("hehe")) {
JLabel title = new JLabel("Proceed");
title.setFont(new Font("Arial",Font.BOLD,15));
markP.add(title,BorderLayout.NORTH);
JButton exit = new JButton("Exit");
markP.add(exit);
//here i want to create another actionListener on the exit button only without affecting the other content which is in the button "addB " so that when i click on the addB button the J dialog pops up, and than when i click on exit button the program will return to the menu.I couldn't figure it out.
dialog.toFront();
dialog.setModal(true);
dialog.pack(); //
dialog.setLocationRelativeTo(null); //
dialog.setVisible(true);
}
// here the code goes on but the problem is that of the actionListener which is concerned.
JButton exit = new JButton("Exit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// you code here
}
});
You should use better variables names. It is not easy to follow your code
You could use the same ActionListener if you check the source of the action using
if (evt.getSource().equals(addDButton) { original code }
else { code for the other button }