I'm having a hard time calling the variable from first frame - java

here is how should my program be. In first frame, there is a textfield1 where a user input text and when he press a button, a new frame will be display with a textfield2 that displays the inputted text from the textfield1. please help me with the syntax. i'm still a beginner in java. much thanks guys.
First Frame:
textfield= new JTextField();
textfield.setPreferredSize( new Dimension(200,30) ) ;
textfield.setSize( textfield.getPreferredSize() ) ;
textfield.setLocation(95,198) ;
textfield.setSize(175,28);
cont.add(textfield);
public void actionPerformed(ActionEvent e) {
this.setVisible(false);
new Frame2().setVisible(true); //displays the 2nd frame right?
}
now i don't know what to do on my 2nd frame or where to start because i can't get the variable from the first frame

You can pass the desired variables in a constructor of Frame2:
Frame2 frame2 = new Frame2(textfield.getText());
frame2.setVisible(true);

All you need to do is - Define new constructor for second frame with textfield2:
public Frame2(String toDisplay){
textfield2 = new JTextField(toDisplay);
}

Try this:
(just copy into a new file named FrameTest.java in the default package)
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class FrameTest extends JFrame {
public static void main(String[] args) {
JFrame frame = new FrameTest();
frame.pack();
frame.setVisible(true);
}
public FrameTest() {
JPanel panel = new JPanel();
final JTextField textField = new JTextField();
textField.setPreferredSize(new Dimension(100, 20));
panel.add(textField);
JButton button = new JButton("press me");
panel.add(button);
setContentPane(panel);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
FrameTest.this.setVisible(false);
Frame2 secondFrame = new Frame2(textField.getText());
secondFrame.pack();
secondFrame.setVisible(true);
}
});
}
class Frame2 extends JFrame {
public Frame2(String text) {
getContentPane().add(new JTextField(text));
}
}
}

Related

Trying to create a window with two buttons which will each open new windows and close the original window when clicked

I'm attempting to create a launch page. I want to open an initial window where the user can either click an 'admin' or 'employee' button which will each open a corresponding window, and close the original window.
So far I'm finding that when clicked the two buttons don't do anything, despite the ActionListener methods in the code below. I'd really appreciate any advice on where I'm going wrong (am a beginner).
Main
package deskBooking;
public class Main {
public static void main(String[] args) {
LaunchWindow launchWindow = new LaunchWindow();
}
}
LaunchWindow
package deskBooking;
import javax.swing.*;
import java.awt.event.*;
public class LaunchWindow implements ActionListener{
// An initial window where users can declare sign in type (Administrator/employee)
// Depending on selection will direct user to an employee or administrator sign in journey
JFrame frame = new JFrame("Desk Booking step 1/4");
JPanel panel = new JPanel();
JButton employeeButton = new JButton("Employee");
JButton adminButton = new JButton("Admin");
LaunchWindow() {
frame.setSize(600,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
JLabel label = new JLabel("Welcome to the desk booking system! "+"\n"+"Please declare if you are an admin or a normal user:");
label.setBounds(50, 20, 80, 25);
panel.add(label);
panel.add(employeeButton);
employeeButton.addActionListener(this);
employeeButton.setBounds(100,160,200,40);
employeeButton.setFocusable(false);
panel.add(adminButton);
adminButton.addActionListener(this);
adminButton.setBounds(100,160,200,40);
adminButton.setFocusable(false);
frame.setVisible(true);
}
#Override
public void actionPerformed (ActionEvent e) {
if(e.getSource()=="employeeButton") {
frame.dispose();
EmployeeWindow employeeWindow = new EmployeeWindow();
}
else if(e.getSource()=="adminButton") {
frame.dispose();
AdminWindow adminWindow = new AdminWindow();
}
}
}
EmployeeWindow
package deskBooking;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class EmployeeWindow {
JFrame frame2 = new JFrame("Employee log-in 2/4");
JPanel employeePanel = new JPanel();
JLabel label = new JLabel("Username: ");
JLabel label2 = new JLabel("Password: ");
EmployeeWindow(){
frame2.setSize(200,200);
frame2.add(employeePanel);
employeePanel.add(label);
employeePanel.add(label2);
frame2.setVisible(true);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
AdminWindow
package deskBooking;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class AdminWindow {
JFrame frame3 = new JFrame("Admin log-in 2/4");
JPanel adminPanel = new JPanel();
JLabel label = new JLabel("Username: ");
JLabel label2 = new JLabel("Password: ");
AdminWindow(){
frame3.setSize(200,200);
frame3.add(adminPanel);
adminPanel.add(label);
adminPanel.add(label2);
frame3.setVisible(true);
frame3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

JPanel class is not adding to JFrame

I can't get my JFrame from main class to display JPanel from another class. Everything compiles without errors
This is my main class code which extends JFrame:
public OnlineCarSalesSystem(){
setTitle("Online Car Sales System");
setVisible(true);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(new Login());
}
public static void main(String[] args) {
new OnlineCarSalesSystem();
}
In the above code i have added add(new Login()); but it is not displaying that panel on my JFrame. And in the below code i extended my class with the JPanel. And this is the JPanel class code:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Login extends JPanel{
JLabel loginLabel = new JLabel("Login ID");
JLabel passwordLabel = new JLabel("Password");
JTextField loginTextField = new JTextField();
JPasswordField passwordTextField = new JPasswordField();
JButton submitButton = new JButton("Submit");
JButton registration = new JButton("new Registration");
JLabel noaccountLabel = new JLabel("No Account yet!!!");
public void Login(){
setBounds(0,0,500,500);
setBackground(Color.red);
setVisible(true);
loginLabel.setBackground(Color.cyan);
passwordLabel.setBackground(Color.cyan);
loginTextField.setBounds(680, 103,90,20);
add(loginTextField);
loginLabel.setBounds(600, 100,90,30);
add(loginLabel);
passwordTextField.setBounds(680, 153,90,20);
passwordTextField.setEchoChar('*');
add(passwordTextField);
passwordLabel.setBounds(600, 150,90,30);
add(passwordLabel);
add(submitButton);
submitButton.setBounds(640,200,90,30);
submitButton.addActionListener(new ActionListener() { //////Submit Button
public void actionPerformed(ActionEvent e) {
}
});
add(registration);
registration.setBounds(638,270,96,30);
add(noaccountLabel);
noaccountLabel.setBackground(Color.cyan);
noaccountLabel.setBounds(640,250,90,30);
registration.addActionListener(new ActionListener() { //////registration Button
public void actionPerformed(ActionEvent e) {
}
});
}
}
The problem is that the Login()-function isn't executed at any point in code. You might want to change
public void Login() { ... }
to
public Login() { ... }
so the code gets executed on object initialization

I want a JLabel to appear after pressing a JButton

I need help with this code, I'm trying to make a simple cookie clicker type game, I have most the code done, but for some reason, when I try to add the JLabel to the frame, it creates an error, I was hoping one of you guys could help me out, I'm fairly new to Java, thanks for the help!
//Variables
static int clicked = 0;
private FlowLayout layout;
private Container container;
public static void main(String [] args) {
//Declaring the buttons, panels, etc...
JButton button = new JButton("Click");
JPanel panel = new JPanel();
panel.add(button);
final JFrame frame = new JFrame("Button Pressed");
frame.setSize(400, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(panel);
//Action Listener Code
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Execute when button is pressed
clicked++;
System.out.println("Button pressed " + clicked + " times!");
}
}
}
You can add an JLabel then update its text when button is clicked.
Note: call JFrame.setVisible(true) in the end when all the component is added.
sample code:
// Declaring the buttons, panels, etc...
JButton button = new JButton("Click");
final JLabel label = new JLabel();
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
clicked++;
label.setText("Button pressed " + clicked + " times!");
}
});
JPanel panel = new JPanel();
panel.add(button);
panel.add(label);
final JFrame frame = new JFrame("Button Pressed");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(panel);
frame.setVisible(true);
Find more examples here and here
The basic principle is relatively easy. In order to add something to something else, you first need to have access (or a reference to) the thing you want to add to.
While there are a number of ways you might achieve this, the simplest might be to use an instance/class field. This field would then be accessible from anywhere within the class, for example
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ClickTest {
public static void main(String[] args) {
new ClickTest();
}
private JPanel panel;
public ClickTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
//Declaring the buttons, panels, etc...
JButton button = new JButton("Click");
panel = new JPanel();
panel.add(button);
final JFrame frame = new JFrame("Button Pressed");
frame.setSize(400, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(panel);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panel.add(new JLabel("You clicked me"));
panel.revalidate();
}
});
}
});
}
}
Take a look at Creating a GUI With JFC/Swing and Understanding Class Members for more details

Open new JFrame with JButton Click - Java Swing

I am trying to open a new JFrame window with a button click event. There is lots of info on this site but nothing that helps me because I think it is not so much the code I have, but the order it is executed (however I am uncertain).
This is the code for the frame holding the button that I want to initiate the event:
package messing with swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.border.EmptyBorder;
public class ReportGUI extends JFrame{
//Fields
private JButton viewAllReports = new JButton("View All Program Details");
private JButton viewPrograms = new JButton("View Programs and Majors Associated with this course");
private JButton viewTaughtCourses = new JButton("View Courses this Examiner Teaches");
private JLabel courseLabel = new JLabel("Select a Course: ");
private JLabel examinerLabel = new JLabel("Select an Examiner: ");
private JPanel panel = new JPanel(new GridLayout(6,2,4,4));
private ArrayList<String> list = new ArrayList<String>();
private ArrayList<String> courseList = new ArrayList<String>();
public ReportGUI(){
reportInterface();
allReportsBtn();
examinnerFileRead();
courseFileRead();
comboBoxes();
}
private void examinnerFileRead(){
try{
Scanner scan = new Scanner(new File("Examiner.txt"));
while(scan.hasNextLine()){
list.add(scan.nextLine());
}
scan.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
private void courseFileRead(){
try{
Scanner scan = new Scanner(new File("Course.txt"));
while(scan.hasNextLine()){
courseList.add(scan.nextLine());
}
scan.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
private void reportInterface(){
setTitle("Choose Report Specifications");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel(new FlowLayout());
add(panel, BorderLayout.CENTER);
setSize(650,200);
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
}
private void allReportsBtn(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(70, 50, 70, 25));
panel.add(viewAllReports);
viewAllReports.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
JFrame AllDataGUI = new JFrame();
new AllDataGUI();
}
});
add(panel, BorderLayout.LINE_END);
}
private void comboBoxes(){
panel.setBorder(new EmptyBorder(0, 5, 5, 10));
String[] comboBox1Array = list.toArray(new String[list.size()]);
JComboBox comboBox1 = new JComboBox(comboBox1Array);
panel.add(examinerLabel);
panel.add(comboBox1);
panel.add(viewTaughtCourses);
viewTaughtCourses.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFrame ViewCourseGUI = new JFrame();
new ViewCourseGUI();
}
});
String[] comboBox2Array = courseList.toArray(new String[courseList.size()]);
JComboBox comboBox2 = new JComboBox(comboBox2Array);
panel.add(courseLabel);
panel.add(comboBox2);
panel.add(viewPrograms);
add(panel, BorderLayout.LINE_START);
}
If you don't want to delve into the above code, the button ActionListener is here:
panel.add(viewTaughtCourses);
viewTaughtCourses.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFrame ViewCourseGUI = new JFrame();
new ViewCourseGUI();
}
});
This is the code in the class holding the JFrame I want to open:
package messing with swing;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
public class ViewCourseGUI extends JFrame{
private JButton saveCloseBtn = new JButton("Save Changes and Close");
private JButton closeButton = new JButton("Exit Without Saving");
private JFrame frame=new JFrame("Courses taught by this examiner");
private JTextArea textArea = new JTextArea();
public void ViewCoursesGUI(){
panels();
}
private void panels(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel rightPanel = new JPanel(new GridLayout(15,0,10,10));
rightPanel.setBorder(new EmptyBorder(15, 5, 5, 10));
JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(scrollBarForTextArea);
frame.add(panel);
frame.getContentPane().add(rightPanel,BorderLayout.EAST);
rightPanel.add(saveCloseBtn);
rightPanel.add(closeButton);
frame.setSize(1000, 700);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
Could someone please point me in the right direction?
As pointed out by PM 77-3
I had:
public void ViewCoursesGUI(){
panels();
}
When I should have had:
public ViewCourseGUI(){
panels();
}
A Combination of syntax and spelling errors.
Set the visibility of the JFrame you want to open, to true in the actionListener:
ViewCourseGUI viewCourseGUI = new ViewCourseGUI();
viewCourseGUI.setVisible(true);
This will open the new JFrame window once you click the button.
Let ReportGUI implement ActionListener. Then you will implement actionPerformed for the button click. On button click, create the second frame (if it doesn't exist). Finally, set the second frame visible (if it is currently not visible):
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ReportGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 8679886300517958494L;
private JButton button;
private ViewCourseGUI frame2 = null;
public ReportGUI() {
//frame1 stuff
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,200);
setLayout(new FlowLayout());
//create button
button = new JButton("Open other frame");
button.addActionListener(this);
add(button);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ReportGUI frame = new ReportGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
if (frame2 == null)
frame2 = new ViewCourseGUI();
if (!frame2.isVisible())
frame2.setVisible(true);
}
}
}
This is a simple example. You'll have to add the rest of your code here.

Unable to gain focus on JTextField used in JDialog for the second time on linux server

I am using a JDialog with 2 JTextfields and JButtons in it. When Jdialog opens for the first time I have a cursor on my first textfield. Now if I click somewhere outside Jdialog and then try clicking back the JDialog, I dont see the cursor on any of the textfields and I am unable to write or edit anything on the textfields.
I have set the modal to be true. So even If I click anywhere else my dialog still appears on the screen but gets deactivated.
This issue is only with linux server and not on windows. Windows works perfectly.
Adding a sample code here to get some picture of the issue.
Here TestClass is extending JFrame.
public TestClass(){
setSize(new Dimension(600,500));
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
myPanel = new JPanel();
JButton openDialog = new JButton("Click here");
openDialog.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
dialog = new JDialog(myFrame,true);
dialog.setSize(new Dimension(400,400));
JTextField myField = new JTextField(10);
JPanel innerPanel = new JPanel();
innerPanel.add(myField);
dialog.add(innerPanel);
dialog.setVisible(true);
//add(dialog);
}
});
myPanel.add(openDialog);
add(myPanel);
}
Your incomplete example could not be tested. The example below exhibits the expected behavior under Java 6 on both Mac OS X and Ubuntu 12. In particular, the text field remains functional after switching back from another program.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* #see http://stackoverflow.com/a/15576897/230513
*/
public class TestClass extends JFrame {
private static JFrame myFrame;
public TestClass() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton openDialog = new JButton("Click here");
JPanel myPanel = new JPanel();
myPanel.add(new JButton(new AbstractAction("Click here") {
#Override
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog(myFrame, true);
JTextField myField = new JTextField(10);
JPanel innerPanel = new JPanel();
innerPanel.add(myField);
dialog.add(innerPanel);
dialog.pack();
dialog.setSize(new Dimension(160, 120));
dialog.setLocationRelativeTo(myFrame);
dialog.setVisible(true);
}
}));
add(myPanel);
pack();
setSize(new Dimension(320, 240));
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
myFrame = new TestClass();
}
});
}
}

Categories

Resources