passing frame as parameter in method - java

i want to pass a JFrame as parameter in a method,
is it possible to do that ?
here is what i want :
private void mouseClickedButtonsActions(JLabel l, Class c){
l.addMouseListener(new java.awt.event.MouseAdapter() {
#Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
c ma = new c();
ma.setVisible(true);
setVisible(false);
}
});
}

You shouldn't be sending Class in this situation, if you want to learn more about sending class as parameter check this out Passing class as parameter.
Now since you want to pass JFrame as parameter you can simply write methodName(JFrame frame), otherwise if you just want to make new JFrame you don't need to pass it but just create new one inside method:
myMethod(){
JFrame frame = new JFrame();
// Do something with it
}
So as you can see there is no need to pass an Class in other to make object of that class.
Here you can see example of how to pass JFrame as parameter and make new JFrame:
public void jframe() {
JFrame frame = new JFrame("Frame 1");
JButton btn = new JButton("Click Me");
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jframeAsParam(new JLabel("You added label to old JFrame"), frame);
//makeNewJFrame(new JLabel("You opened new JFrame"));
}
};
btn.addActionListener(al);
JPanel panel = new JPanel(new GridLayout(2, 1));
panel.add(btn);
frame.setContentPane(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 250);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void jframeAsParam(JLabel lbl, JFrame frame) {
frame.getContentPane().add(lbl);
frame.setVisible(true);
}
public void makeNewJFrame(JLabel lbl) {
JFrame frame = new JFrame("Frame 2");
JPanel panel = new JPanel(new BorderLayout());
panel.add(lbl, BorderLayout.CENTER);
frame.setContentPane(panel);
frame.setSize(300, 250);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
Uncomment makeNewJFrame(new JLabel("You opened new JFrame")); to see how opening new JFrame works.

c ma = new c();
First of all class names should:
Start with an upper case character
Be descriptive
i want to pass a JFrame as parameter in a method, is it possible to do that ?
There is no need to pass the frame as a parameter you can access the current frame by using code like:
Component component = (Component)evt.getSource();
Window window = SwingUtilities.windowForComponent( component );
window.setVisible( false );

Related

How to debug missing frame contents in Java Swing?

package me.daniel.practice;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Switch
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Password Login System");
frame.setSize(400, 100);
frame.setResizable(false);
frame.setVisible(true);
frame.setBackground(Color.WHITE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel label = new JLabel("Enter Password: ");
JPasswordField pass = new JPasswordField(10);
pass.setEchoChar('*');
pass.addActionListener(new AL());
panel.add(label, BorderLayout.WEST);
panel.add(pass, BorderLayout.EAST);
frame.add(panel);
}
private static String password = "daniel";
static class AL implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JPasswordField input = (JPasswordField) e.getSource();
char[] passy = input.getPassword();
String p = new String(passy);
if (p.equals(password))
{
JOptionPane.showMessageDialog(null, "Correct");
}
else
{
JOptionPane.showMessageDialog(null, "Incorrect");
}
}
}
}
I want a frame to open and within it, text that says, "Enter Password: " and on its right, a text box that you are able to type you password into. The password in this situation is "daniel."
When you enter the password correctly, another window pops up saying that it's correct. If not, a different window pops up saying that it's incorrect. However, when I run the program, only the frame shows up and not the actual content within the frame.
You should make your frame visible after adding contents to it:
frame.add(panel);
frame.setVisible(true); // move down here
}
P.S. JPanel have default layout manager which is FlowLayout so all the contents would appear inline. In short, panel.add(label, BorderLayout.WEST) won't give the expected output.
You just need to add frame.validate(); after frame.add(panel);.
Although the code you have will most likely work, ideally you should wrap any Java swing initialisation into a SwingUtilities.invokeLater(...) so that it runs on the swing thread:
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run()
{
JFrame frame = new JFrame("Password Login System");
frame.setSize(400, 100);
frame.setResizable(false);
frame.setVisible(true);
frame.setBackground(Color.WHITE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel label = new JLabel("Enter Password: ");
JPasswordField pass = new JPasswordField(10);
pass.setEchoChar('*');
pass.addActionListener(new AL());
panel.add(label, BorderLayout.WEST);
panel.add(pass, BorderLayout.EAST);
frame.add(panel);
frame.validate();
}
});
}
See oracle docs here for mode details.

cannot add dynamic jtextfields and save their values

In previos my questions I asked similar questions to this. But in my previous projects I used GUI builder, so now I would like to add JTextField to the Panel dynamically without Builder. I don't why but for some reason I cannot execute this code:
public class Reference {
JFrame frame = new JFrame();
JPanel MainPanel = new JPanel();
MainPanel main = new MainPanel();
JPanel SubPanel = new JPanel();
JButton addButton = new JButton();
JButton saveButton = new JButton();
private List<JTextField> listTf = new ArrayList<JTextField>();
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new Reference();
}
public Reference() {
frame.add(main);
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(addButton, BorderLayout.EAST);
frame.add(saveButton, BorderLayout.WEST);
frame.pack();
frame.setSize(500, 300);
frame.setVisible(true);
main.setLayout(new BorderLayout());
main.setBackground(Color.green);
main.add(SubPanel);
SubPanel.setBackground(Color.yellow);
addButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
main.add(new SubPanel());
main.revalidate();
}
});
saveButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
for (int i = 0; i < main.getComponentCount();) {
SubPanel panel = (SubPanel)main.getComponent(i);
JTextField firstName = panel.getFirstName();
String text = firstName.getText();
System.out.println( text );
}}
});
}
private class SubPanel extends JPanel {
JTextField firstName = new JTextField(15);
public SubPanel() {
this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
this.add(firstName);
listTf.add(firstName);
}
public JTextField getFirstName()
{
return firstName;
}
}
public class MainPanel extends JPanel
{
List<SubPanel> subPanels = new ArrayList<SubPanel>();
public MainPanel()
{
}
public void addSubPanel()
{
SubPanel panel = new SubPanel();
add(panel);
subPanels.add(panel);
}
public SubPanel getSubPanel(int index)
{
return subPanels.get(index);
}
}
}
And by saveButton trying to get value of JTextField, but without success. In output I can see just JFrame with 2 Buttons, but ActionListener of addButton and saveButton is not active. I cannot understand where is wrong.
Any help would be much appreciated.
In Swing, the order you do some things is very important, for example...
frame.add(main);
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(addButton, BorderLayout.EAST);
frame.add(saveButton, BorderLayout.WEST);
frame.pack();
frame.setSize(500, 300);
frame.setVisible(true);
You add main to your frame
You set the frames layout (!?)
You add your buttons
You pack the frame
You set it's size (!?)
You make it visible
The problem here is step #2. If, instead, we simply remove step #2 (step #4 and #5 aren't great either), you will find that your window now contains main...
frame.add(main);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(addButton, BorderLayout.EAST);
frame.add(saveButton, BorderLayout.WEST);
frame.pack();
frame.setVisible(true);
This...
for (int i = 0; i < main.getComponentCount();) {
SubPanel panel = (SubPanel) main.getComponent(i);
a bad idea of three reasons;
Your loop will never advance (i will always be 0)
You are blindly casting the contents of main without actually knowing what's on it
MainPanel already has a List of SubPanels...
You need to make sure that you are adding SubPanels via the addSubPanel method (and this should probably return an instance of the SubPanel) and provide a means by which you can access this List, maybe via a getter of some sort. Although, I'd be more interested in their values (ie the text field text) rather then the SubPanel itself ;)

Making a log in window to direct to another GUI in java

I am making a Log in window, so after enter username, password and click login button it will direct you to another frame, which is my GUI that use to insert, retrieve, update, and delete database. However, after click, it displayed nothing. Thank you! Here is my code:
It should redirect to GUI like this:
Login
public class Log extends JFrame {
public static void main(String[] args) {
Log frameTabel = new Log();
}
JButton blogin = new JButton("Login");
JPanel panel = new JPanel();
JTextField txuser = new JTextField(15);
JPasswordField pass = new JPasswordField(15);
Log() {
super("Login Autentification");
setSize(300, 200);
setLocation(500, 280);
panel.setLayout(null);
txuser.setBounds(70, 30, 150, 20);
pass.setBounds(70, 65, 150, 20);
blogin.setBounds(110, 100, 80, 20);
panel.add(blogin);
panel.add(txuser);
panel.add(pass);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
actionlogin();
}
public void actionlogin() {
blogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String puname = txuser.getText();
String ppaswd = pass.getText();
if ( puname.equals("test") && ppaswd.equals("12345") ) {
CarSearch regFace = new CarSearch();
// regFace.setVisible(true);
dispose();
} else {
JOptionPane.showMessageDialog(null,
"Wrong Password / Username");
txuser.setText("");
pass.setText("");
txuser.requestFocus();
}
}
});
}
Here is the CarSearch
public class CarSearch {
public static void main(String[] args) {
MainPanel logoPanel = new MainPanel();
JFrame frame = new JFrame("Cars Search");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(logoPanel, BorderLayout.NORTH);
JTabbedPane tabPage = new JTabbedPane();
// tabPage.addTab("Log In", new Log());
tabPage.addTab("Insert Data", new InsertPanel());
tabPage.addTab("Retrieve Data", new RetrievePanel());
tabPage.addTab("Update Data", new UpdatePanel());
tabPage.addTab("Delete Data", new DeletePanel());
frame.getContentPane().add(tabPage, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
First of all, I don't encourage the use of multiple frames, instead you should use a CardLayout, how ever. Your CarSearch class doesn't do anything, it only has static main method, which you never call.
I would change the class so it has a constructor which initialises the class and a method you can call so you can control when you want to the window shown
public class CarSearch {
private MainPanel logoPanel;
private JFrame frame;
public CarSearch() {
logoPanel = new MainPanel();
frame = new JFrame("Cars Search");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(logoPanel, BorderLayout.NORTH);
JTabbedPane tabPage = new JTabbedPane();
// tabPage.addTab("Log In", new Log());
tabPage.addTab("Insert Data", new InsertPanel());
tabPage.addTab("Retrieve Data", new RetrievePanel());
tabPage.addTab("Update Data", new UpdatePanel());
tabPage.addTab("Delete Data", new DeletePanel());
frame.getContentPane().add(tabPage, BorderLayout.CENTER);
}
public void show() {
frame.pack();
frame.setVisible(true);
}
}
Now, having said that, I'd strongly encourage you to use a CardLayout.
Start by creating a LoginPanel and a CarSearchPanel, then you can add each to the same frame and use the CardLayout to switch between them as needed
For (a slight over the top) example
If that is what you want to do then in your CarSearch class should be a JFrame and in your main method you should have CarSearch frame = new CarSearch("Cars Search") instead of JFrame frame = new JFrame("Cars Search"). Then introduce a method public void authenticated() which should contain the code for enabling the other tabs. Also your initialisation should have all the tabs other than the login tab disabled.
Now in your method public void actionlogin() in your validation condition if ( puname.equals("test") && ppaswd.equals("12345") ) you should have CarSearch frame = (CarSearch)getRootPane(); and after that you could call frame.authenticated(); which will disable the login tab and enable the other tabs.

JFrame not displaying contents

I know this question has been asked a lot, but ive read through about 10 different articles, all reccomending to different things such as "frame = this" nad frame.add(d)" Im not sure why, but none of these have been working. I typed something and the program worked fine, except the Jbuttons wouldnt show up until i clicked on the JFrame a few times. After some tweaking of that code, im back to the start. Now i just get a error:
Exception in thread "main" java.lang.NullPointerException
at Guis.Dynamic_JFrame.<init>(Dynamic_JFrame.java:37)
at Guis.Dynamic_JFrame.main(Dynamic_JFrame.java:46)
Heres my code:
public class Dynamic_JFrame extends JFrame{
static JFrame frame;
Graphics g;
Handler handler = new Handler();
JButton red = new JButton();
JButton green = new JButton();
JButton orange = new JButton();
public Dynamic_JFrame(){
red.setText("RED");
green.setText("GREEN");
orange.setText("orange");
add(green);
add(red);
add(orange);
red.addActionListener(handler);
green.addActionListener(handler);
orange.addActionListener(handler);
frame.setVisible(true);
}
public static void main(String[] args){
Dynamic_JFrame d = new Dynamic_JFrame();
frame = new JFrame("Changing colors");
frame.setPreferredSize(new Dimension(500,500));
frame.setMaximumSize(new Dimension(500,500));
frame.setMinimumSize(new Dimension(500,500));
frame.setLayout(new FlowLayout());
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class Handler implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getSource()==red){
getContentPane().setBackground(Color.RED);
}
if(e.getSource()==green){
getContentPane().setBackground(Color.GREEN);
}
if(e.getSource()==orange){
getContentPane().setBackground(Color.ORANGE);
}
}
}
}
New code, Minor Changes. Program works as intended except for the buttons not updating until i click where they should be:
JFrame frame;
public Dynamic_JFrame(){
frame = new JFrame();
frame = this;
red.setText("RED");
green.setText("GREEN");
frame.add(green);
frame.add(red);
frame.setVisible(true);
}
public static void main(String[] args){
Dynamic_JFrame d = new Dynamic_JFrame();
d.frame.setPreferredSize(new Dimension(500,500));
d.frame.setMaximumSize(new Dimension(500,500));
d.frame.setMinimumSize(new Dimension(500,500));
d.frame.setLocationRelativeTo(null);
d.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
d.frame.setLayout(new FlowLayout());
}
A number of things...
Firstly, Dynamic_JFrame extends from JFrame so I don't know why you've then gone and create another frame...
Secondly, when Dynamic_JFrame calls frame.setVisible in the constructor, frame is null as it has not being initialised.
From my perspective, the simplest solution would be to extend Dynamic_JFrame from something like JPanel instead and simply add it to an instance of JFrame
For example...
public class Dynamic_JFrame extends JPanel {
static JFrame frame;
// Not sure that this is a good idea...
Graphics g;
//...
public Dynamic_JFrame(){
// Don't use this...
//frame.setVisible(true);
}
public static void main(String[] args){
EventQueue.invokeLater(new Runnable() {
public void run() {
Dynamic_JFrame d = new Dynamic_JFrame();
frame = new JFrame("Changing colors");
frame.setLayout(new FlowLayout());
frame.add(d);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}

Why not jframe shows button?

public class Benim extends JFrame {
Container contentArea = getContentPane ();
public Benim(){
JFrame frame=new JFrame("Concentration");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
setSize(800, 800);
JButton start=new JButton("Start");
JPanel pane=new JPanel();
pane.add(start);
setVisible(true);
frame.add(start);
frame.add(pane);
/* setContentPane(Container)
JRootPane createRootPane()*/
}
public static void main (String []args){
new Benim();
}
}
My code is that. I tried adding to panel first then adding panel to frame, adding to frame directly. Adding a rootpane but still my button doesnot appear. I am trying to learn for 2 days but i am still at same point.
The instance of JFrame that is shown does not have the JButton added.
Instead invoke setVisible on the JFrame directly
You almost never want to extend JFrame as no new functionality is added
Other points to note
Call setVisible after components have been added
setSize is unnecessary - let pack determine container size
This is the result
public class Benim extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Concentration");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton start = new JButton("Start");
JPanel pane = new JPanel();
pane.add(start);
pane.add(start);
frame.add(pane);
frame.pack();
frame.setVisible(true);
}
});
}
}
Why another instance of JFrame? You are extending it, so just call super().
public class Benim extends JFrame {
Container contentArea = getContentPane ();
public Benim(){
super("Concentration");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setSize(800, 800);
JButton start=new JButton("Start");
JPanel pane=new JPanel();
pane.add(start);
add(pane);
setVisible(true);
}
public static void main (String []args){
new Benim();
}
}
Reimeus also rightfully points out that you don't need to extend JFrame if you don't plan on extending functionality. See his example for an alternative implementation.

Categories

Resources