How to debug missing frame contents in Java Swing? - java

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.

Related

How to create multiple frames or windows in GUI?

I am new to creating GUI. I want to know how to create multiple windows. I want to show another frame if a button is to be clicked. I have searched how and i saw that some people are making another GUI form and just calling the other form i a button was clicked, but i dont understand how.
There are numerous ways to do this. One of the main ways is to create a new Java Class with its own properties. Here is a nexample:
JButton button = new JButton("Button_Leads_To_This_Window");
button.addActionListener( new ActionActionListener()
{
public void actionPerformed(ActionEvent e)
{
NewFrame();
}
});
This will allow the button to call a new window, similar as the way you called the "My Empire" window. For example NewFrame() class will look like this:
public static void newFrame()
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setOpaque(true);
JTextArea textArea = new JTextArea(15, 50);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
textArea.setFont(Font.getFont(Font.SANS_SERIF));
JScrollPane scroller = new JScrollPane(textArea);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
JPanel inputpanel = new JPanel();
inputpanel.setLayout(new FlowLayout());
JTextField input = new JTextField(20);
JButton button = new JButton("Enter");
DefaultCaret caret = (DefaultCaret) textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
panel.add(scroller);
inputpanel.add(input);
inputpanel.add(button);
panel.add(inputpanel);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setResizable(false);
input.requestFocus();
}
});
}
Here is more information to the matter:
https://www.thoughtco.com/create-a-simple-window-using-jframe-2034069
https://www.youtube.com/watch?v=RMz9LYY2g4A
Good luck.

passing frame as parameter in method

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 );

how can I make an undecorated window containing a button with java?

I've created a round window with java , It's undecorated ..the problem is when I tried to add a button or a label in the frame ,nothing is shown inside.
could someone Please help me ?
edited
this is the code I made :
public class main {
static public JPanel p;
public static JLabel label1 ;
public static JLabel label2 ;
public static void main(String[] args) {
label1 = new JLabel("Name : ");
label2= new JLabel("surname : ");
p=new JPanel();
p.add(label1);
p.add(label2);
JFrame frame = new JFrame();
frame.add(p);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
frame.setShape(new RoundRectangle2D.Double(200, 200, 200, 200, 200, 200));
frame.setSize(500, 500);
frame.setContentPane(p);
frame.setVisible(true);
}
}

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 ;)

Swing Methods on submission of button

How to close current frame (Frame1) and open a new frame (Frame2) already created and pass the data to frame2 from frame1 on the clicking of button?
Use a CardLayout1. Either that or one JFrame and one or more JDialog2 instances.
How to Use CardLayout
How to Make Dialogs
The very best way to accomplish this, is very much told to you by #Andrew Thompson.
And the other way to accomplish, the motive of the question as described in the code. Here as you make object of your new JFrame, you have to pass the things you need in the other class as an argument to the other class, or you can simply pass the object(with this you be passing everything in one go to the other class)
A sample code for a bit of help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoFramesExample
{
public JFrame frame;
private JPanel panel;
private JButton button;
private JTextField tfield;
private SecondFrame secondFrame;
public TwoFramesExample()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(new BorderLayout());
tfield = new JTextField(10);
tfield.setBackground(Color.BLACK);
tfield.setForeground(Color.WHITE);
button = new JButton("NEXT");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
// Here we are passing the contents of the JTextField to another class
// so that it can be shown on the label of the other JFrame.
secondFrame = new SecondFrame(tfield.getText());
frame.dispose();
}
});
frame.setContentPane(panel);
panel.add(tfield, BorderLayout.CENTER);
panel.add(button, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TwoFramesExample();
}
});
}
}
class SecondFrame
{
private JFrame frame;
private JPanel panel;
private JLabel label;
private JButton button;
private TwoFramesExample firstFrame;
public SecondFrame(String text)
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(new BorderLayout());
label = new JLabel(text);
button = new JButton("BACK");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
firstFrame = new TwoFramesExample();
frame.dispose();
}
});
frame.setContentPane(panel);
panel.add(label, BorderLayout.CENTER);
panel.add(button, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
}
Hope this be of some help.
Regards

Categories

Resources