Opening a different frame with a button in Java - java

I am trying to open the menu frame using a button on the main frame. I added an event to the button and I tried calling the other class but it keeps giving me an error of ":: expected after this token"
This is my main frame
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Main extends JFrame {
public static JPanel mainPane;
public final JButton menuButton = new JButton("New button");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
mainPane = new JPanel();
mainPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(mainPane);
mainPane.setLayout(null);
menuButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Menu.main(String[] args);
}
});
menuButton.setBounds(76, 89, 104, 32);
mainPane.add(menuButton);
}
}
And this is my menu frame
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;
public class Menu extends JFrame {
public static JPanel menuPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu frame = new Menu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Menu() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
menuPane = new JPanel();
menuPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(menuPane);
menuPane.setLayout(null);
JLabel menuTitle = new JLabel("Menu");
menuTitle.setBounds(194, 11, 46, 14);
menuPane.add(menuTitle);
}
}

change your action event to this.no need to call main method .create a new instance of Menu class instead.
menuButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Menu menu = new Menu();
menu.setVisible(true);
}
});
if you relly want to call main method then use
menuButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Menu.main(new String[0]);
}
});
the error is here
Menu.main(String[] args);//error
this is not a correct way of passing arguments to a methods.this is declaration of parameter list.
you can correct error by changing it to ,
String args[] = null;
Menu.main(args); //correct

Related

Importing button and text field from another class to main class

I have two different classes (mainClass) and (visual). In the visual class I have a method and inside the method I put the required code for a simple JButton. In the main class I create an object to call the method from visual class, to show the button in the main class . But it does not work. I would appreciate any advice.
package init;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
public class mainClass {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainClass window = new mainClass();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public mainClass() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
In the code below I made an object and called the method from the visual class
visual bt = new visual();
bt.btn();
}
}
////////////////VISUAL CLASS//////////////////////
package init;
import javax.swing.JButton;
import javax.swing.JFrame;
public class visual {
public JFrame frame;
public void btn() {
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(141, 155, 151, 45);
frame.getContentPane().add(btnNewButton);
}
}
For what you are trying to achieve here you don't need 2 classes. You can do it like this:
import javax.swing.*;
import java.awt.*;
public class MainClass {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrame frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnNewButton = new JButton("New button");
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(btnNewButton);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}

java open a frame from another class

So I am trying to just make it so when I click a button it will open a frame from another class my filechooser frame just won't open.
This is the class called mainFrame:
package javatut;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class mainFrame {
private JFrame frmMainwindow;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainFrame window = new mainFrame();
window.frmMainwindow.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public mainFrame() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmMainwindow = new JFrame();
frmMainwindow.setTitle("Mainwindow");
frmMainwindow.setBounds(100, 100, 280, 150);
frmMainwindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmMainwindow.getContentPane().setLayout(null);
JButton btnBrowse = new JButton("Browse");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
myButtonAction();
}
});
btnBrowse.setBounds(155, 11, 100, 23);
frmMainwindow.getContentPane().add(btnBrowse);
textField = new JTextField();
textField.setBounds(10, 12, 135, 20);
frmMainwindow.getContentPane().add(textField);
textField.setColumns(10);
}
private void myButtonAction(){
Toolkit.getDefaultToolkit().beep();
}
}
And this is the FileChooser class called simply frame:
package javatut;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class frame {
private JFrame frmFilechooser;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame window = new frame();
window.frmFilechooser.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public frame() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmFilechooser = new JFrame();
frmFilechooser.setTitle("FileChooser");
frmFilechooser.setBounds(100, 100, 470, 350);
frmFilechooser.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmFilechooser.getContentPane().setLayout(new BorderLayout(0, 0));
JFileChooser fileChooser = new JFileChooser();
frmFilechooser.getContentPane().add(fileChooser);
}
}
The easiest and most logical solution is to change the myButtonAction() method to:
private void myButtonAction() {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(frmMainwindow);
if (result==JFileChooser.APPROVE_OPTION) {
// do something with the chosen file ..
}
}
If I understand you correctly, you're just missing two lines. The first in mainFrame's myButtonAction:
private void myButtonAction(){
// Toolkit.getDefaultToolkit().beep();
new frame();
}
And the other in frame's initialize:
private void initialize() {
frmFilechooser = new JFrame();
frmFilechooser.setTitle("FileChooser");
frmFilechooser.setBounds(100, 100, 470, 350);
frmFilechooser.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmFilechooser.getContentPane().setLayout(new BorderLayout(0, 0));
JFileChooser fileChooser = new JFileChooser();
frmFilechooser.getContentPane().add(fileChooser);
frmFilechooser.setVisible(true);
}
(I just added the setVisible line at the bottom)

How to close jframe panel or window

I have 2 frames/windows, I have Exit button on window 2, an from window 1 I launch window 2 and then exit it i.e setVisible(false);
When I execute window 2 I can easily click button exit and hide the current window, however when I launch window 2 from window 1, and then click exit button I get NullPointerException Error. then I instantiated it in the beginning with static and this error was gone, however the window 2 is not being closed/hidden its still there with no effect of button.
Window 1 code:
package com.my.jlms;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class LibrarianMenu extends JFrame {
private JPanel contentPane;
private static LibrarianMenu frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new LibrarianMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public LibrarianMenu() {
setTitle("Librarian");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 385, 230);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnPasswd = new JButton("Change Pass");
btnPasswd.setBounds(202, 76, 146, 39);
contentPane.add(btnPasswd);
btnPasswd.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
ChangePwd framee = new ChangePwd();
framee.setVisible(true);
}
});
}
}
Window 2 Code:
package com.my.jlms;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
public class ChangePwd extends JFrame {
private JPanel contentPane;
private static ChangePwd frame = new ChangePwd();;
private JButton btnExit;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new ChangePwd();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ChangePwd() {
setResizable(false);
setTitle("Password!");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 266, 154);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnExit = new JButton("Exit");
btnExit.setBounds(20, 80, 89, 30);
contentPane.add(btnExit);
btnExit.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent ae) {
frame.setVisible(false);
}
});
}
}
Is there a solution I can set window 2 to hide ?
The problem here is that you are creating your frame, as your class, and not on the object frame, but you hide the frame which represents the object frame.
Change this line (in your actionListener's actionPerformed() method):
frame.setVisible(false);
to:
setVisible(false);
You can use dispose function for the purpose.see how dispose works.
If you want to close a JFrame, you could use the dispose() method.
Example:
public void actionPerformer(ActionEvent e)
{
if(e.getSource().equals(closeFrameButton)
{
dispose(); //This will close the current JFrame
}
}
NOTE: this is different to System.exit(0);. Using this will close the Java virtual machine. if you just want to close the frame, use dispose()

Java Swing JTextField text one tick behind

I use this Java code for demonstration (Just created using eclipse)
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.JTextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class executor extends JFrame {
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
executor frame = new executor();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public executor() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
final JLabel lblNewLabel = new JLabel("New label");
contentPane.add(lblNewLabel, BorderLayout.NORTH);
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
lblNewLabel.setText(textField.getText());
}
});
contentPane.add(textField, BorderLayout.CENTER);
textField.setColumns(10);
}
}
and if you type anything into the textfield the label shows everything exactly except prior to the last
Buttonpress. Is there any way to fix that? thank you!
The text field contents change only after the key listener is notified. Instead of trying to track key presses, it is better to listen to the changes in the contents of the text field. This ensures that you also catch changes made by other means, such as cut and paste. The interface for doing that is DocumentListener:
textField.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
lblNewLabel.setText(textField.getText());
}
#Override
public void insertUpdate(DocumentEvent e) {
lblNewLabel.setText(textField.getText());
}
#Override
public void changedUpdate(DocumentEvent e) {
}
});

Java Swing processing status

I am trying to implement a swing frame. In this, I want to display a processing status in a textPanel using a different thread while performing the needed task. I tried the following code. Of course there is something wrong with the logic. Please provide me with the proper approach
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class SampleSwing {
private JFrame frame;
public static JTextField textField;
public static boolean processing=false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SampleSwing window = new SampleSwing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public SampleSwing() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(0, 31, 434, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
processing=true;
Processingstatus ps=new Processingstatus();
ps.start();
/*perform the actual task*/
processing=false;
}
});
btnNewButton.setBounds(174, 74, 89, 23);
frame.getContentPane().add(btnNewButton);
}
}
class Processingstatus extends Thread{
public void run() {
try {
while(SampleSwing.processing) {
SampleSwing.textField.setText("Processing");
Thread.sleep(1000);
SampleSwing.textField.setText("Processing..");
Thread.sleep(1000);
SampleSwing.textField.setText("Processing...");
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
First I thought, "you should be using a SwingWorker, as it has methods to handle progress and EDT updates..."
But when I looked closer, you don't actually really care about the process itself, you just want some where to show that a process is running...They are two separate entities, that are only related because one (the UI updates) will run so long as the other is running.
So, instead, I used a javax.swing.Timer. This allows me to schedule an event to occur every n milliseconds and have that triggered in the EDT, nice and clean...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.Timer;
public class SampleSwing {
private JFrame frame;
public static JTextField textField;
public static boolean processing = false;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SampleSwing window = new SampleSwing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public SampleSwing() {
initialize();
}
private Timer processTimer;
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
textField = new JTextField(25);
frame.add(textField, gbc);
processTimer = new Timer(500, new ActionListener() {
private StringBuilder dots = new StringBuilder(3);
#Override
public void actionPerformed(ActionEvent e) {
dots.append(".");
if (dots.length() > 3) {
dots.delete(0, dots.length());
}
textField.setText("Processing" + dots.toString());
}
});
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!processing) {
processing = true;
processTimer.start();
} else {
processTimer.stop();
processing = false;
textField.setText(null);
}
}
});
frame.add(btnNewButton, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
}
}
ps For the reason why your original code didn't work, see my comment in the above comments section ;)

Categories

Resources