I want to know how to open this JFrame form (1) when I click a button in the second JFrame (2). The problem is that I am unable to get the .setVisible method in the Form 2. Please help. Thanks & Regards ! :)
Form 1 (to be opened when a button is clicked on Form 2
public class FlightForm {
public FlightForm() {
initialize();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FlightForm window = new FlightForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
Form 2
public class MainMenu{
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainMenu window = new MainMenu();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainMenu() {
frame = new JFrame("Main Menu");
setBounds(100, 100, 830, 574);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Flight Form");
);
btnNewButton.setFont(new Font("Candara", Font.BOLD, 15));
btnNewButton.setBounds(169, 328, 193, 77);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("Passenger Form");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
PassengerForm window = new PassengerForm();
window.setVisible(true); // This is not working
You can call setVisible(true) on PassengerForm() only if PassengerForm class extends JFrame. If no you should use something like:
PassengerForm window = new PassengerForm();
window.getFrame().setVisible(true)
Related
I just started learning GUI programming and I'm facing a problem to load image.
I wanted to place a JButton on the WEST of BorderLayout, and display the image in the CENTER by clicking on that JButton.
Please refer to this picture:
The code is as shown below. I've been trying for a few hours but still couldn't make it.
public class Testing extends JFrame {
private JButton btn;
private JLabel pict;
private JPanel wpanel,cpanel;
private BufferedImage image;
Testing(){
Container cont = getContentPane();
setLayout(new BorderLayout());
//add button
wpanel = new JPanel();
cpanel = new JPanel();
btn = new JButton("Click me");
wpanel.add(btn);
//Clicking button to load image
//inner class
btn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
try {
loadImage();
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
createAndShowGUI();
}
});
} catch (IOException e) {
System.out.println("Couldn't load image.");
}
}
});
public void loadImage() throws IOException{
image = ImageIO.read(Testing.class.getResource("/path/.jpg"));
}
public void createAndShowGUI(){
pict = new JLabel();
pict.setIcon(new ImageIcon(image));
cpanel.add(pict);
}
//end of clicking button to load image
cont.add(wpanel,BorderLayout.WEST);
cont.add(cpanel,BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("JFrame");
setSize(300, 300);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Testing();
}
});
}
}
I am really new to GUI, got a little problem when I was trying to study it.
Ok here is my code.
public class Sample implements ActionListener{
public void go() {
JButton button = new JButton("Click");
JFrame frame = new JFrame();
frame.getContentPane().add(button);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(100,100);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
button.setText("Hello");
}
});
}
It keeps telling me that The method addActionListener(ActionListener) in the type AbstractButton is not applicable for the arguments (new ActionListener(){}). I don't get it because I remember I did it before and it could work.
......
I don't get an error but the action listener won't work because the action performed method of the ActionListener Interface needs to overriden.
button.addActionListener(new ActionListener() {
// add the annotation below
#Override
public void actionPerformed(ActionEvent e) {
button.setText("hello");
}
});
And typically you would build the JFrame in the main method. Later they added an Invoke Later runner that when the class extends JFrame it would create the window in a more object oriented manner.
public class App extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
JFrame frame = new App();
frame.setVisible(true);
} catch (Exception e){
e.printStackTrace();
}
}
});
}
public App(){
JButton button = new JButton("Click");
getContentPane().add(button);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(100,100);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
button.setText("hello");
}
});
}
}
I have two textfields and I control values user enters to that textfields. For both of the textfields I use focusLost. However, for example, when the user not enters any value (one of the controls) and clicks other textfield I get first and second textfields control's information message. I mean after focus lost from the first text field, the second text field's focusLost be triggered. Why this happens? How to prevent this?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
public class Test extends JFrame
{
private JPanel pa;
private JTextField myTF1, myTF2;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try{
Test frame = new Test();
frame.setVisible(true);
}
catch(Exception e) {
e.printStackTrace();
}
}
});
}
public Test()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100,100,450,300);
pa = new JPanel();
pa.setBorder(new EmptyBorder(5,5,5,5));
setContentPane(pa);
pa.setLayout(null);
myTF1 = new JTextField();
myTF1.addFocusListener(new FocusListener()
{
public void focusLost(FocusEvent arg)
{
if(myTF1.getText.equals(""))
JOptionPane.showMessageDialog(null, "Error1", "Error", JOptionPane.ERROR_MESSAGE);
}
public void focusGained(FocusEvent arg)
{
// This is empty.. I don't need it..
}
});
myTF1.setBounds(24,13,116,22);
pa.add(myTF1);
myTF1.setColumns(10);
myTF2 = new JTextField();
myTF2.addFocusListener(new FocusListener()
{
public void focusLost(FocusEvent arg)
{
if(myTF2.getText.equals(""))
JOptionPane.showMessageDialog(null, "Error2", "Error", JOptionPane.ERROR_MESSAGE);
}
public void focusGained(FocusEvent arg)
{
// This is empty.. I don't need it..
}
});
myTF2.setBounds(24,48,116,22);
pa.add(myTF2);
myTF2.setColumns(10);
}
}
When the option pane is opened, the option pane gains the focus, stealing it from either of the text fields that has it at that moment.
One approach to solving this is to display the error messages in a label within the main GUI. Here is an example:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
public class Test2 extends JFrame {
private JTextField myTF1, myTF2;
private JLabel output = new JLabel("Enter a value in both field 1 & field 2");
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test2 frame = new Test2();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
JPanel gui = new JPanel(new BorderLayout(5,5));
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(gui);
JPanel pa = new JPanel(new GridLayout(0, 1, 5, 5));
gui.add(pa, BorderLayout.LINE_START);
gui.add(output, BorderLayout.PAGE_END);
myTF1 = new JTextField(10);
myTF1.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent arg) {
if (myTF1.getText().equals("")) {
output.setText("Error: Field 1 must have a value!");
}
}
public void focusGained(FocusEvent arg) {
// This is empty.. I don't need it..
}
});
myTF1.setBounds(24, 13, 116, 22);
pa.add(myTF1);
myTF2 = new JTextField(10);
myTF2.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent arg) {
if (myTF2.getText().equals("")) {
output.setText("Error: Field 2 must have a value!");
}
}
public void focusGained(FocusEvent arg) {
// This is empty.. I don't need it..
}
});
myTF2.setBounds(24, 48, 116, 22);
pa.add(myTF2);
pack();
}
}
I have a JFrame which uses JPanel initialized from the JPanel.
This is the JFrame class : LoginPage
public class LoginPage extends JFrame
{
private JPanel contentPane;
static int cnf;
static String data;
private static LoginPage frame;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
frame = new LoginPage();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
//cnf = chk;
if( cnf == 1)
{
frame.dispose();
JFrame m = new MainPage();
m.setVisible(true);
}
}
/**
* Create the frame.
*/
public LoginPage()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel m = new MainLogin();
m.setBounds(0, 0, 448, 271);
contentPane.add(m);
}
}
And, this is the JPanel class : MainLogin
public class MainLogin extends JPanel
{
private JTextField uname;
private JPasswordField pass;
public static int chk;
public MainLogin()
{
setLayout(null);
uname = new JTextField();
uname.setBounds(236, 22, 167, 25);
add(uname);
uname.setColumns(10);
pass = new JPasswordField();
pass.setBounds(236, 53, 167, 25);
add(pass);
JButton login = new JButton("Login");
login.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String u = uname.getText();
char[] tp = pass.getPassword();
String p = new String(tp);
chk = authentication.verify(u, p);
System.out.println(chk);
}
});
login.setBounds(235, 90, 117, 25);
add(login);
}
}
As in the MainLogin Panel, there is a class authentication who has a method verify(), which returns an integer, and this integer is stored in chk.
Since, this chk resides in MainLogin JPanel class, I want to pass it to the LoginPage JFrame class.
Is there any way to do this other than using a File?
Open the main page from LoginPage instance not from the main method.
Add a login() method to the LoginPage
public class LoginPage extends JFrame {
//other parts
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
frame = new LoginPage();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
public LoginPage() {
//...
JPanel m = new MainLogin(this);
//...
}
public void login(int chk) {
JFrame m = new MainPage();
m.setVisible(true);
this.dispose();
}
}
And pass login frame to the panel as a parameter
public class MainLogin extends JPanel
{
private int chk;//no need to be static
public MainLogin(final LoginFrame loginFrame)
{
setLayout(null);//null layout is bad
//...
login.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//...
chk = authentication.verify(u, p);
loginFrame.login(chk);
}
});
//...
}
}
Not only does this question get asked quite a bit, it also has a number of possible solutions, including using a modal dialog or Observer Pattern depending on your needs
See How to Make Dialogs for more details
You might also like to take a look at
Open JFrame, only after successfull login verification with database. Using Eclipse?
Java and GUI - Where do ActionListeners belong according to MVC pattern?
for more discussion on the subject
The basic answer here is, you want to separate the areas of responsibility.
You need to:
Gather the user credentials
Validate those credentials
Take a appropriate action based on the success of that check
These are three distinct actions, all which should be separated, it's not the responsibility of the login panel to validate the credentials, that's someone else's responsibility, equally, it's not the validators responsibility to decide what should be done when the validation fails or succeeds, that's someone else's responsibility
I am having difficulty when trying to return to previous JFrame. In FirstFrame, it has a parameter. In secondFrame, how can I back to firstFrame since it does not has parameter ?
I am pulling my hair out of this. Any help would be appreciated.
FirstFrame.java
public class FirstFrame extends JFrame
{
public FirstFrame(final String name)
{
goToSecondFrame.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
SecondFrame sec= new SecondFrame();
sec.createAndShowGui();
sec.setVisible(true);
setVisible(false);
dispose();
}
});
}
}
SecondFrame.java
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
static void createAndShowGui() {
JFrame frame = new JFrame("Second Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Second());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public Second()
{
back.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
FirstFrame back = new FirstFrame(); // Getting error
back.setVisible(true);
setVisible(false);
dispose();
}
});
}
Define your frame first in the top of the class:
JFrame frame = new JFrame("Delete Admin");
and then do like this:
back.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
staffManagment back = new staffManagment("");
back.setVisible(true);
setVisible(false);
frame.dispose();
}
});