Java GUI with JFrames - java

Today I started learning Java GUI and tried to create a simple window on my Ubuntu. I am using jre7 for now.
I wrote code exactly from tutorial because from experience there are stuff that doesn't work even if it's correctly typed onto my screen. So, now I used thenewboston's first tutorial with Java GUI. Typed all syntax correctly, classes seems fine, no errors.
He got window that was expected - mine only got blank window with no title and no text.
Screenshot with that
(source: scaleengine.net)
Code in JFrames.java file:
import java.awt.FlowLayout; // importē plūstošo skatu / default layout
import javax.swing.JFrame; // dod iespēju piekļūt pamata logu struktūrai
import javax.swing.JLabel; // ļauj rakstīt tekstu logos
public class JFrames extends JFrame {
private JLabel item1;
public JFrames() {
super("The Title Of The Program"); // parāda title bar ar tekstu
setLayout(new FlowLayout());
item1 = new JLabel("This is sentence with something");
item1.setToolTipText("This is tooltip on hover");
add(item1); // pievieno logam šo lietiņu
}
}
Please, ignore latvian comments, that's just for my reference.
So I want to know - why my window appears blank?

In the screenshot, your code says:
JFrame frame = new JFrame();
That should be JFrames with an s.
JFrames frame = new JFrames();

Related

Java button hovering

I'm new to Java programming and I'd like to know how to mess around with buttons, I have created a "Home Screen" and some buttons as well as text, however it's not as advanced as I'd like it to be, I want to know how to create things like image effects, so let's say I hover over a button, I want it to display a glowing animation behind it, or since I don't have that animation, if there's no easy way to create it, just displaying an image behind it is alright, also I don't have anything happening when pressing the button bcs IDK how to do that yet so if you could help with that it'd be awesome!
Here's the code I currently have:
package Menu;
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class BackgroundPanel extends JFrame {
private BufferedImage image;
public BackgroundPanel() {
ImageIcon icon = new ImageIcon("image_path.png");
JButton btn = new JButton(icon);
btn.setOpaque(false);
btn.setContentAreaFilled(false);
btn.setBorderPainted(false);
btn.setFocusPainted(false);
try {
image = ImageIO.read(new File("image_path.jpg"));
// Set your Image Here.
this.setContentPane(new JLabel(new ImageIcon(image)));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JPanel panel = new JPanel();
panel.add(new JLabel("Username:"));
panel.add(new JTextField("",20));
panel.add(new JLabel("Password:"));
panel.add(new JTextField("",20));
panel.add(btn);
//Adding components to Panel and JFrame
this.add(panel);
// JFrame Properties
this.setSize(1280,720);
this.setLayout(new FlowLayout());
this.setResizable(true);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Panel");
this.setVisible(true);
}
public static void main(String[] args) {
new BackgroundPanel();
}
}
[...] also I don't have anything happening when pressing the button bcs IDK how to do that yet so if you could help with that it'd be awesome [...]
You need to add an ActionListener to your button. There are various other ways to detect if the button was pressed, but this one is the (in my opinion) easiest. This is how you do it:
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
// code you write in here will be executed if the button was pressed
}
});
[...] let's say I hover over a button, I want it to display a glowing animation behind it, or since I don't have that animation, if there's no easy way to create it, just displaying an image behind it is alright [...]
For this, you'll have to deal with JLayeredPanes and MouseListeners. Here is an example that I created "on the run"; the layouting is very dirty and has to be improved. Anyhow, you'll notice that once you hover over the button, a black-bordered box containing LA- -LL! will appear behind the button. That's a JLabel and you can use it to display images and such by using the JLabel.setIcon method.
let's say I hover over a button, I want it to display a glowing animation behind it, or since I don't have that animation, if there's no easy way to create it, just displaying an image behind it is alright
This is not that easy, it requires jumping through a whole bunch of hoops, especially when the button isn't rectangle.
A while I ago a did a prototype of a "validation highlighter" which highlighted invalid fields, it makes use of JXLayer library, but which should be convertible to use the included JLayer library on the core libraries
See How can I change the highlight color of a focused JComboBox for more details
The other possibility we'd be to create a custom JPanel and override its paintComponent method and paint your effect there. You would place your button it and with a combination of a a layout manager and borders you should be able to get the button positioned where you need it.
The problem with this, is it will effect the over layout of your form, as the effect will be considered while the primary form is laid out
I really don't have anything happening when pressing the button bcs IDK how to do that yet so if you could help with that it'd be awesome
I suggest you have a look at How to use buttons and How to write ActionListeners

how to move JButton to specific position

this is a very easy code because I just started learning java.
how do I move the button to specific position/points. Please be brief and make your answer simple and easy to understand because I just started learning java.
this is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class finals extends JFrame implements ActionListener{
JButton login = new JButton("Log-In");
JButton enroll = new JButton("Enroll");
JPanel con = new JPanel();
JFrame frame = new JFrame();
public finals(){
frame.setTitle("Enrollment");
setContentPane(con);
setLayout(new FlowLayout());
login.setLocation(122, 120);
con.add(login);
System.out.println(login.getLocation());
frame.add(con);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,150);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e){
}
public static void main(String Args[]){
new finals();
}
}
make your answer simple and easy to understand
Don't attempt to specify a pixel location of a component! What is so special about (122, 12)? Nothing, its just a random number you picked.
Let the layout manager do its job. For example you can use a FlowLayout and set the alignment to CENTER so the component is centered on the row.
Or if you don't like that you can use a BoxLayout, and add a "horizontal strut" to the panel to help control positioning.
Read the section from the Swing tutorial on Layout Managers for more information and working examples.
I just started learning java.
Don't forget to check out the Table of Contents from the above tutorial link for more basic information about creating GUI's.
You have to put your JPanel layout to "null".
Just add this : con.setLayout(null);

bring Jinternal frame infront of everything

in this code when the new button is clicked, the Jinternalframe goes behind the button, even if i add anything else like, jlabel, jtextfield, etc, the internalframe opens behind everything. i tried the tofront() and movetofront() functions, but it doesnt seem to work. plz help, thanks.
code:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Messages2 extends JFrame {
JFrame frame;
JButton button1;
public static void main(String[] args) {
Messages2 window = new Messages2();
window.frame.setVisible(true);
}
public Messages2() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.WHITE);
frame.setBounds(100, 100, 220, 220);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//frame.getContentPane().setLayout(new FlowLayout());
JButton btnNew = new JButton("New Message");
btnNew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JDesktopPane desktopPane = new JDesktopPane();
JInternalFrame intFrame = new JInternalFrame(
"JInternalFrame demo");
intFrame.setMaximizable(true);
intFrame.setIconifiable(true);
intFrame.setResizable(true);
intFrame.setClosable(true);
intFrame.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
intFrame.setSize(320, 240);
// intFrame.pack();
intFrame.setVisible(true);
desktopPane.add(intFrame);
frame.add(desktopPane, BorderLayout.CENTER);
}
});
btnNew.setBounds(1, 35, 145, 31);
frame.getContentPane().add(btnNew);
}
}
when the new button is clicked, the Jinternalframe goes behind the button, even if i add anything else like, jlabel, jtextfield, etc,
Based on the code you posted in you last question (before you deleted it), you are attempting to add all your components directly to the frame. Swing paints components in the reverse order that a component is added. So since the internal frame is added last it is painted first and then all the other components are painted over top of it.
This is not the way you should be working with a JInternalFrame. You need to separate the JDesktopPane/JInternalFrames from your other components and work with each separately.
Read the section from the Swing tutorial on How to Use Internal Frames for basic information and examples.
the internal frame is added to a JDesktopPane which is added to the frame.
Don't use a null layout for your other components. Swing was designed to be used with layout managers. These components should be added to a panel and then the panel added to the frame.
The panel and the desktop pane must be added to different areas of the frame. For example:
frame.add(panel, BorderLayout.NORTH);
frame.add(desktopPane, BorderLayout.CENTER);
You're not using JInternalFrame correctly. It should only be placed within a JDesktopPane, something you're not doing and that I suggest that you start doing. Please check the appropriate tutorial on this.
Your button and your JInternalFrame now fill the field since you're using the JFrame's default BorderLayout. Suggestion:
First and foremost, explain fully just what exact effect/user experience you're trying to achieve. Are you sure that a JInternalFrame is your best choice here?
Learn about and use the layout managers to their best advantage.
If you're going to use a JInternalFrame, then while it's OK to add the JInternalFrame in your ActionListener, you're usually going to want to add the JDesktopPane to the GUI on GUI creation, not in the ActionListener.

Need advice on approaching a little graphics project [duplicate]

This question already has answers here:
Need to read input of two JTextfields after a button is clicked
(2 answers)
Closed 8 years ago.
So I made a fully functional credit card validator which uses Luhn's Algorithm and all that jazz to validate the card type and number. It currently only uses Scanner and the console to print out stuff, but I wanted to take my program to the next level.
I wanted to make an application with Java graphics that can take in a credit card number entered into my applet/japplet/whatever you suggest and can essentially do the same process as the previously mentioned program, but I want to give it the aesthetic appeal of graphics.
So I'm honestly a little overwhelmed with the graphics in Java (not sure if that's weird), but here's what I want advice on.
How should I approach my graphics project? Should I use JApplet, Applet, JFrame, or something else?
I want to make a text field that the user enters his or her credit card into, what is the method of doing that? I looked up JTextFields but I'm at a loss on how to use it. I looked at the API but it doesn't do a very good job of explaining things in my opinion.
My main problem is the textfield, can someone give me an example of a textfield that can take in data that the user types? Sort of like Scanner in the console but in my graphics application.
Sorry for my word wall, you guys have been very helpful to me in the past :)
Tips, tricks, and anything else you think would help me out would be greatly appreciated.
Here is an example of a text field using swing:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GUI extends JFrame { // The JFrame is the window
JTextField textField; // The textField
public GUI() {
textField = new JTextField(10); // The user can enter 10 characters into the textField
textField.addActionListener(new ActionListener() { // This will listen for actions to be performed on the textField (enter button pressed)
#Override
public void actionPerformed(ActionEvent e) { // Called when the enter button is pressed
// TODO Auto-generated method stub
String inputText = textField.getText(); // Get the textField's text
textField.setText(""); // Clear the textField
System.out.println(inputText); // Print out the text (or you can do something else with it)
}
});
JPanel panel = new JPanel(); // Make a panel to be displayed
panel.add(textField); // Add the textField to the panel
this.add(panel); // Add the panel to the JFrame (we extend JFrame)
this.setVisible(true); // Visible
this.setSize(500, 500); // Size
this.setDefaultCloseOperation(EXIT_ON_CLOSE); // Exit when the "x" button is pressed
}
public static void main(String[] args) {
GUI gui = new GUI();
}
}

How can I add a JButton to my full screen java program

I have followed thenewbostons java game tutorials on youtube and managed to create a base class which will be in full screen mode using a screenmanager class. Well all works just fine, I can draw images and strings and so on, but how the heck can I add JButtons etc etc.
I have uploaded my code on pastie.org so you can see it :)
Main.java
Screen
BaseFrame [the abstract frame]
Menu Frame [Inheritted from BaseFrame]
consider following code :
import javax.swing.JButton;
import javax.swing.JFrame;
public class NewClass5 extends JFrame
{
JButton b=new JButton("button");
NewClass5(){
this.add(b);
this.setSize(200, 200);
this.setVisible(true);
}
public static void main(String a[]){
new NewClass5();
}
}
Consider adding the button in ahead of time. Don't make it visible. Then when you want to give that option, setVisible(true). Unless you have many buttons that are dynamic and need to change on the fly or something, I think this should work.

Categories