Hello,
I am using Java Swing and I want to close a window on a button click. I don't know using an actionlistener as the best way to do this but currently I am having compilation errors with it so its must be incorrect.
Here my code:
public class assignment2
{
public static void main(String[] args){
MyFrame f = new MyFrame(); //open the inital gui interface
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true); //set it visibile
}
}
//this is the initial gui screen, presenting user with options for which action they would like to take
//al actions for the gui are commenced here
class MyFrame extends JFrame{
public MyFrame(){
buttonPanel1 p = new buttonPanel1(); // add the buttons for this frame
add(p);
setSize(800,600);
setTitle("Travel Console");
setLocationRelativeTo(null);
}
}
class buttonPanel1 extends JPanel{
public buttonPanel1(){
//create buttons
JButton addItem = new JButton("Add an Item");
JButton deleteItem = new JButton("Delete an item");
JButton listItem = new JButton("List items");
JButton editItem = new JButton("Edit an item");
JButton bookFlight = new JButton("Book a flight");
JButton save = new JButton("Save data");
JButton load = new JButton("Load data");
JButton exit = new JButton("Exit");
//set layout manager for button panel
setLayout(new GridLayout(8,1,1,5));
//create buttons
add(addItem);
add(deleteItem);
add(listItem);
add(editItem);
add(bookFlight);
add(load);
add(save);
add(exit);
addItemListener addList = new addItemListener();
addItem.addActionListener(addList);
exitListener exitList = new exitListener();
exit.addActionListener(exitList);
}
}
//listener classes for the inital gui page. each button has its own actionlistener which launches the selected option
class addItemListener implements ActionListener{
public void actionPerformed(ActionEvent event){ //launch add item
addItemFrame addItem = new addItemFrame();
addItem.setDefaultCloseOperation(addItemFrame.DISPOSE_ON_CLOSE);
addItem.setVisible(true);
}
}
class addItemFrame extends JFrame{
public addItemFrame(){
addItemButtonPanel b = new addItemButtonPanel(); // add the buttons for this frame
add(b);
setSize(800,500);
setTitle("Add an Item");
setLocationRelativeTo(null);
}
}
//part of addItemFrame class
class addItemButtonPanel extends JPanel{
public addItemButtonPanel(){
JLabel selectItem = new JLabel("Select which item you would like to add:");
JButton newCustomer = new JButton("Customer");
JButton newflight = new JButton("Flight");
JButton newMovie = new JButton("Movie");
JButton goBack = new JButton("Return to main menu");
setLayout(new GridLayout(5,1,1,5));
add(selectItem);
add(newCustomer);
add(newflight);
add(newMovie);
add(goBack);
goBackListener gbList = new goBackListener();
goBack.addActionListener(gbList);
}
}
//listener classes for the addItemFrame
class goBackListener implements ActionListener{
public void actionPerformed(ActionEvent event){
addItemFrame.dispose();
}
}
The problem I am having is with the last class listed goBackListener, which effectively just closes the current window so the main menu screen is displayed again. I need a static reference to addItemFrame created in the addItemListener class. But changing it to static is an invalid modifier?
How can I fix it?
try this
//listener classes for the addItemFrame
class goBackListener implements ActionListener{
private addItemFrame frame;
public goBackListener(addItemFrame frame){
this.frame= frame;
}
public void actionPerformed(ActionEvent event){
frame.dispose();
}
}
and send an instance of addItemFrame to it's constructor
Related
public class Button {
public static void main(String[] args) {
int numClicks = 0;
JButton button1 = new JButton ();
button1.setText("1 click = 1 dollar for animals you love");
JFrame god = new JFrame ();
JPanel panel = new JPanel();
god.getContentPane().add(button1);
god.add(button1);
god.setSize(new Dimension(400, 400));
god.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
}
}
Can anyone help me figure out how to make the actionlistener count the number of times the button is clicks? Im a noobie coder (3 months) and Im really stuck on this
You need to add ActionListener to you button.
button1.addActionListener(new MyActionList());
//MyActionList is an object which implements ActionListener
In your case is the same object.
//---implements ActionListener---
public class Button implements ActionListener{
private int clickCount;
public Button() {
clickCount = 0;
JFrame god = new JFrame ();
god.setSize(new Dimension(400, 400));
//if you don't do this, your program still running, even if you click on X.
god.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
god.add(panel);
JButton button1 = new JButton("1 click = 1 dollar for animals you love");
//here we add ActionListener
button1.addActionListener(this);
//'this' refer to the current object. In our case 'new Button()' from 'main'...
//...which has implemented ActionListener.
panel.add(button1);
god.setVisible(true);
}
public static void main(String[] args){
new Button();
}
//Override from Interface ActionListener and...
//...here describe what happend when button was pressed.
#Override
public void actionPerformed(ActionEvent e) {
clickCount++;
System.out.println(clickCount);
}
}
When i run this program sometimes shows me all buttons, but sometimes only 2 or 3 or 4 or 5 or even just 1.. why is that??
I really do not get it. There should always be 6 buttons, but it doesnt show them. Is there any logical reason?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class testnet
{
public static void main (String[] args)
{
JFrame frame = new JFrame("Knjigarna");
frame.setVisible(true);
frame.setSize(800,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button1 = new JButton("Prikazi vse");
panel.add(button1);
button1.addActionListener (new Action1());
JButton button2 = new JButton("Prikazi knjigo");
panel.add(button2);
button2.addActionListener (new Action2());
JButton button3 = new JButton("Dodaj knjigo");
panel.add(button3);
button3.addActionListener (new Action3());
JButton button4 = new JButton("Brisi knjigo");
panel.add(button4);
button4.addActionListener (new Action4());
JButton button5 = new JButton("Uredi knjigo");
panel.add(button5);
button5.addActionListener (new Action5());
JButton button6 = new JButton("Izhod");
panel.add(button6);
button6.addActionListener (new Action6());
}
static class Action1 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame2 = new JFrame("Pikaz vseh knjig");
frame2.setVisible(true);
frame2.setSize(500,800);
JLabel label = new JLabel("Seznam vseh knjig:");
JPanel panel = new JPanel();
JTextField text1=new JTextField("Naslov: ");
JTextField text2=new JTextField("Avtor: ");
frame2.add(panel);
panel.add(label);
panel.add(text1);
panel.add(text2);
}
}
static class Action2 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame3 = new JFrame("Prikaz knjige");
frame3.setVisible(true);
frame3.setSize(600,300);
JLabel label = new JLabel("Vpisi naslov knjige:");
JPanel panel = new JPanel();
frame3.add(panel);
panel.add(label);
}
}
static class Action3 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame4 = new JFrame("Dodajanje knjige");
frame4.setVisible(true);
frame4.setSize(600,300);
JLabel label = new JLabel("Vpisi podtke o knjigi");
JPanel panel = new JPanel();
frame4.add(panel);
panel.add(label);
}
}
static class Action4 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame5 = new JFrame("Brisanje knjige");
frame5.setVisible(true);
frame5.setSize(600,300);
JLabel label = new JLabel("Vpisi naslov knjige, ki jo zelis brisati");
JPanel panel = new JPanel();
frame5.add(panel);
panel.add(label);
}
}
static class Action5 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame6 = new JFrame("Urejanje knjige");
frame6.setVisible(true);
frame6.setSize(600,300);
JLabel label = new JLabel("Vpisi naslov knjige, ki jo zelis urejati");
JPanel panel = new JPanel();
frame6.add(panel);
panel.add(label);
}
}
static class Action6 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
System.exit(0);
}
}
}
try something with layout. JFrame and or remove managed by inside with a content pane. content pane default layout is BorderLayout. so you need to try border layout stuff.
or you can try this code in you main method
frame.setLayout(new FlowLayout());
this will add component by one by one.
for more about layout you can get in here
This is just a fix and not really an explanation of why the problem is occurring.
Call frame.revalidate() after adding all the buttons.
From the Java Docs,
public Component add(Component comp)
This method
changes layout-related information, and therefore, invalidates the
component hierarchy. If the container has already been displayed, the
hierarchy must be validated thereafter in order to display the added
component.
I have added buttons and text fields to a panel, but when I try to add the panel to the MenuItem nothing happens. I have defined an ActionListener for the MenuItem in which I am adding the JPanel. No error is detected by the compiler, but nothing happens when I click the MenuItem. How can I resolve this issue?
public class MenuFrame extends JFrame {
private JMenu customers;
private JMenu purchase;
private JPanel panel1 = new JPanel();
public MenuFrame() {
JButton button = new JButton();
panel1.add(button);
customers = new JMenu("Customers");
JMenuItem createInvoice = new JMenuItem("Create");
JMenuItem updateInvoice = new JMenuItem("Update");
JMenuItem deleteInvoice = new JMenuItem("Delete");
sales.add(createInvoice);
PanelHandler p = new PanelHandler(panel1);
createInvoice.addActionListener(p);
}
private class PanelHandler implements ActionListener {
private JPanel panel;
public PanelHandler(JPanel p) {
this.panel = p;
}
public void actionPerformed(ActionEvent e) {
// getContentPane().removeAll();
// getContentPane().setVisible(true);
// JButton b=new JButton("Enter");
// panel.add(b);
panel.setVisible(true);
add(panel, BorderLayout.SOUTH);
getContentPane().doLayout();
// update(getGraphics());
}
}
}
Don't invoke doLayout() directly.
When add (or remove) components from a visible GUI the basic code is:
panel.add(...);
panel.realidate(); // to invoke the layout manager
panel.repaint(); to repaint components
I am trying to transit from a UserAdminPanel to AdminLogin within the same JPanel when I press the Admin button.
UserAdmin Panel
transit to AdminLogin Panel
The problem I have now is that I am opening up a new panel instead of changing the current panel to the new panel.
This is my code for the UserAdminPanel
public class SelectAdminUserPanel extends JPanel
{
public SelectAdminUserPanel()
{
setLayout(new GridLayout(3,1));
JButton b1 = new JButton("User Login");
JButton b2 = new JButton("Admin Login");
JButton b3 = new JButton("Exit");
b1.addActionListener(new SelectUserButtonListener() );
b2.addActionListener(new SelectAdminButtonListener());
b3.addActionListener(new SelectExitButtonListener() );
add(b1);
add(b2);
add(b3);
}
private class SelectAdminButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
AdminModule am = new AdminModule();
am.run();
}
}
private class SelectUserButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
GameModule gm = new GameModule();
gm.run();
}
}
private class SelectExitButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
}
}
}
This is the code for the AdminLogin Panel
public class AdminLoginPanel extends JPanel
{
AdminLoginPanel()
{
JLabel pwlabel = new JLabel("Password");
JPasswordField pwfield = new JPasswordField(20);
JButton loginbutton = new JButton("Login");
add(pwlabel);
add(pwfield);
add(loginbutton);
}
}
I have looked at the following example and this example but it's not very applicable because it talks about CardLayout instead of like rewriting the current JPanel.
I think that you should have a reference to your main frame and just remove the components from it based on the button pressed and add only the required components. From what you say, UserAdminPanel is your main panel. I think it's added to a frame for which you can obtain a reference. When you click a button, you want to remove all the content shown on it and display only what the button clicked should show. I think it should look something like this:
private class SelectAdminButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
frame.getContentPane().removeAll();
AdminModule am = new AdminModule();
frame.add(am.getNewPanel());
frame.pack();
// am.run(); //it's not clear what does for you
}
}
Where the method getNewPanel() would return the underlying JPanel. I'm assuming that AdminModule has a reference to the AdminLoginPanel.
I'm trying to learn Swing and JFrame, so I'm creating a really simple program that asks for your name and then displays a box telling you what you've entered.
I'm trying to use a separate class from the first to act as the ActionListener and display the name that was typed in. However it's not working for me. I tried creating a constructor in the second class that sets an instance variable to the value taken in the JTextfield but it's not showing up as I expected. Please have a look;
And here's my code (I've imported all libraries properly but omitted for space's sake)
This is the main class...
public class NamePrompt extends JFrame{
private static final long serialVersionUID = 1L;
String name;
public NamePrompt(){
setLayout(new BorderLayout());
JLabel enterYourName = new JLabel("Enter Your Name Here:");
JTextField textBoxToEnterName = new JTextField(21);
JPanel panelTop = new JPanel();
panelTop.add(enterYourName);
panelTop.add(textBoxToEnterName);
JButton submit = new JButton("Submit");
submit.addActionListener(new SubmitButton(textBoxToEnterName.getText()));
JPanel panelBottom = new JPanel();
panelBottom.add(submit);
//Add panelTop to JFrame
add(panelTop, BorderLayout.NORTH);
add(panelBottom, BorderLayout.SOUTH);
//JFrame set-up
setTitle("Name Prompt Program");
//setSize(300, 150);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
NamePrompt promptForName = new NamePrompt();
promptForName.setVisible(true);
}
}
And this is the ActionListener class:
public class SubmitButton implements ActionListener {
String nameInput;
public SubmitButton(String textfield){
nameInput = textfield;
}
#Override
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + nameInput );
}
}
You are passing in an empty String into the ActionListener class SubmitButton when it is created and it is never updated once the text changes in the JTextField textBoxToEnterName so nothing is ever displayed.
You could pass the textBoxToEnterName JTextField to gain access to the value when required:
class SubmitButtonListener implements ActionListener {
private JTextField textfield;
public SubmitButtonListener(JTextField textfield) {
this.textfield = textfield;
}
#Override
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame, "You've Submitted the name "
+ textfield.getText());
}
}
I think you should have the SubmitButton class as an inner class of the NamePrompt class. This way you can use the text field's variable without having to pass it along to a new class, which might complicate things.
class SubmitButton implements ActionListener {
// Do not need this
// public SubmitButton(String textfield){
// nameInput = textfield;
// }
#Override
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + textBoxToEnterName.getText());
}
But be sure to define the variables outside of the constructor so it can be used by the inner class:
public class NamePrompt extends JFrame{
private static final long serialVersionUID = 1L;
JLabel enterYourName;
JextField textBoxToEnterName;
JPanel panelTop;
JButton submit;
JPanel panelBottom;
String name;
public NamePrompt(){ ..... (set up the variables here)
The final class would look like:
public class NamePrompt extends JFrame{
private static final long serialVersionUID = 1L;
String name;
JLabel enterYourName;
JTextField textBoxToEnterName;
JPanel panelTop;
JButton submit;
JPanel panelBottom;
public NamePrompt(){
setLayout(new BorderLayout());
enterYourName = new JLabel("Enter Your Name Here:");
textBoxToEnterName = new JTextField(21);
panelTop = new JPanel();
panelTop.add(enterYourName);
panelTop.add(textBoxToEnterName);
submit = new JButton("Submit");
submit.addActionListener(new SubmitButton(textBoxToEnterName.getText()));
panelBottom = new JPanel();
panelBottom.add(submit);
//Add panelTop to JFrame
add(panelTop, BorderLayout.NORTH);
add(panelBottom, BorderLayout.SOUTH);
//JFrame set-up
setTitle("Name Prompt Program");
//setSize(300, 150);
pack();
setLocationRelativeTo(null);
}
class SubmitButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + textBoxToEnterName.getText());
}
}
public static void main(String[] args) {
NamePrompt promptForName = new NamePrompt();
promptForName.setVisible(true);
}
}
There is the problem:
submit.addActionListener(new SubmitButton(textBoxToEnterName.getText()))
To the listener you are passing a String instead of the textfield, change it to accept textfield :)
And at
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + nameInput );
}
ask the textfield current value