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.
Related
I am trying to create Pong game and I need to add two figures. I used add() method but it only shows the second figure and clear the first one. My code is below:
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class Demo extends JFrame{
Paddle playerPaddle = new Paddle(26);
Paddle aiPaddle = new Paddle(576);
public Demo() {
super("Ping Pong");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(624, 351);
add(aiPaddle);
add(playerPaddle);
}
public static void main(String[] args){
Demo gui = new Demo();
gui.setBackground(Color.BLACK);
gui.setVisible(true);
}
}
So, it only shows playerPaddle. How can I write it to show both aiPaddle and playerPaddle? Thanks in advance))).
A JFrame by default, uses BorderLayout. When you jframe.add(component) with a border layout, it is equals to jframe.add(component, BorderLayout.CENTER). So you are adding 2 components to CENTER border layout constraints. However, BorderLayout can have only one component in its center. That's why you see this "override".
Change the layout, and you will see both components. Or change the constraints of at least one component:
add(aiPaddle,BorderLayout.PAGE_START);
add(playerPaddle);
I suggest you to take a look at a visual guide to layout managers.
I am attempting to write a simple program for now but the actual JButton is not appearing for some reason, here is my code below.
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame {
public static void main(String[] args) {
JFrame window = new JFrame("Shoes");
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setResizable(true);
window.setSize(400,500);
window.setVisible(true);
window.setLocationRelativeTo(null);
JButton welcome = new JButton("Click here");
welcome.setLocation(100,100);
welcome.setVisible(true);
// doesn't work, but is there another way to make it so?
//add(welcome);
}
}
You created the button, but did not add it.
You have to add it to the window. Simply using add(welcome) will add it to your frame, which you extend, but not to the window in which you want it to show.
Instead of:
add(welcome);
Just do:
window.add(welcome);
I would also like to mention that the reason the code on your commented out section didnt work, is because you're extending JFrame.
When you extend JFrame, you inherit all of the methods JFrame has. That includes add(). However, when you use this.add() you are adding the compononent to you Test Object (which is also a JFrame), not your window JFrame.
To add to the window you would use window.add(welcome);
To stop these weird confusions in the future I would also change
public class Test extends JFrame
to
public class Test
you extended JFrame yet in your code you use another JFrame that you created JFrame window = new JFrame("Shoes");, this is why add(welcome); is not working for you... since its trying to add the JButton to this instance of your Test class(which is not visible) and not the window you have created.
You have 2 ways of solving this:
The first one as mentioned by #Hackerdarshi is to add the button to the window you created. like : window.add(welcome);
The second way is to make use of your extension of the JFrame class(otherwhise why extend at all) and call all the methods on the window using this instance of your Test class:
public Test() {
super("Shoes");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(true);
setSize(400,500);
setVisible(true);
setLocationRelativeTo(null);
JButton welcome = new JButton("Click here");
welcome.setLocation(100,100);
welcome.setVisible(true);
// this will work since `this` instance is set to visible
add(welcome);
}
NOTE that to set the buttons location like: welcome.setLocation(100,100); you should use a null Layout
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
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();
I've been trying to create a class that decides which JPanel gets printed on a JFrame. The JPanels are "addNew" and "searchPanel". addNew is created by a class called "AddNew" and it contains content items that enables a user add new content into a database.
The searchPanel panel is in a different class "SearchPanel" that enables a user search content in a database.
The JFrame on which the two JPanels are drawn is in its own class and has only two buttons "Add new item" and "Search". No JPanel is drawn until one of these buttons is clicked.
Theres a third class that determines which JPanel gets drawn on the JFrame via a switch statement depending on a value (1 or 2) passed on "buttonClick", which is where I think I'm having problems.
My code so far:
import Panels.AddNew;
import SearchWakili.SearchPanel;
import javax.swing.JPanel;
public class Redirect {
public static JPanel panelRedirect = new JPanel();
public static JPanel value;
public static JPanel pageAddNewFunction () {
AddNew addNew = new AddNew();
panelRedirect.add(addNew);
return panelRedirect;
}
public static JPanel SearchPanelFunction () {
SearchPanel searchPanel = new SearchPanel();
panelRedirect.add(searchPanel);
return panelRedirect;
}
public static JPanel pageRedirect (int pageID) {
switch (pageID) {
case 1:
value = pageAddNewFunction();
break;
case 2:
value = SearchPanelFunction();
break;
}
return value;
}
}
The code does nothing. I don't get any code error messages, though. The JPanels print fine when I call the directly without redirecting via the "Redirect" class.
What is it that I'm doing wrong, and is there any other way I can use an independent class to decide on a JPanel to be drawn depending on the button clicked?
Thank you very much in advance.
Oh! And I don't want to use CardLayout. I'd like to learn how to code this myself.
Part of the code that draws the JFrame:
import java.awt.Color;
import java.lang.ProcessBuilder.Redirect;
import javax.swing.JFrame;
public class FrameContainer {
public static JFrame Home;
public static void createAndShowGUI() {
// Create and set up the Frame
JFrame.setDefaultLookAndFeelDecorated(true);
Home = new JFrame();
Home.setUndecorated(true);
Home.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Home.setResizable(false);
Home.setBounds(0, 0, 400, 400);
Home.setBackground(Color.gray);
// Redirect redirect = new Redirect();
Home.add(Redirect.panelRedirect);
// Display the window
Home.pack();
Home.setVisible(true);
}
}
Part of the Code that declares the event:
public class Home {
// The method that calls the type of JPanel (1) to be drawn
private void mouseClickedAddNew(java.awt.event.MouseEvent evt) {
// FrameContainer.createAndShowGUI();
Redirect.pageRedirect(1);
}
}
First off, it is not a good practice to initialize modules on request.
In other words, you should have a method that gets called in the main class constructor that will allocate space for the variables and do calculations, so when you actually click the button, the only command that you are running is the one that makes each panel visible.
This is most likely why what you are doing does not work.
So just make the code initially load both panels, then when a button is clicked, do show() or hide() (I believe those are the methods, but I don't use Swing often enough to know, so the wording may be different).