I'm learning Swing and I have the following code:
public class SimView {
private JFrame frame;
private JLabel background;
private JPanel car_panel;
public SimView() {
frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 500);
frame.getContentPane().setLayout(null);
background = new JLabel("");
background.setIcon(new ImageIcon(
"C:\\Users\\D__\\Desktop\\background.png"));
background.setBounds(0, 0, 384, 462);
frame.getContentPane().add(background);
frame.setVisible(true);
car_panel = new JPanel();
car_panel.setBounds(175, 430, 16, 21);
car_panel.setVisible(true);
car_panel.setBackground(Color.BLACK);
background.add(car_panel);
MoveCarRunnable carMover = new MoveCarRunnable(car_panel);
}
private static class MoveCarRunnable implements Runnable {
private JPanel car;
MoveCarRunnable(final JPanel car) {
this.car = car;
}
#Override
public void run() {
// Should I call rePaint() on the car_panel here then ?
}
}
What I want to do is to move the JLabel called "car" 's y coordinates for every update to get the effect of it moving by itself i.e. no user interaction. I'm not quite sure how to do this, I suppose I need to have some sort of repaint() method redrawing the position of the JLabel for every update. But how do I get this class to know that it needs to update the position?
Any pointers (links/code) would be appreciated. I want to get the concept of how Swing and its components work in this case, rather than just employing a solution but of course I am interested in a solution so I can study it closer. Thanks
EDIT:
Please see my edit code above
You will have to create a separate Thread that would modify the location of your label and then call validate() and repaint() on the container (frame.getContentPane()). Don't forget to put some sleep() value inside the thread.
However, there would be a better approach to create a separate JPanel. Inside it you would override the paintComponent method or the paint method and there you would draw an image instead of moving JLabels around.
You should better add a JPanel instead of the label to your layout. Choose the dimensions of the JPanel so that it can contain your car in every phase.
Then overwrite the paint method of that panel to position the image on it.
Related
This is my first java project and I am trying to draw a simple rectangle on my JPanel inside my JFrame. Been trying to solve this issue with the help of the same topics on stackoverflow but still no success.
The exception I get when I run the program is java.lang.NullPointerException. From my understanding I can not draw on the JPanel itself? which is created in mainWindow.
Main:
public class Main {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GameBoard game = new GameBoard();
mainWindow view = new mainWindow(game);
mainModel model = new mainModel();
mainController cont = new mainController(model, view, game);
cont.controllerInit();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
View:
public class mainWindow{
public JFrame frame;
public JPanel panel;
GameBoard game = new GameBoard();
frame = new JFrame();
frame.getContentPane().setBackground(SystemColor.control);
frame.setBounds(100, 100, 728, 435);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(game);
frame.getContentPane().setLayout(null);
panel = new JPanel();
FlowLayout flowLayout = (FlowLayout) panel.getLayout();
panel.setBounds(166, 44, 550, 349);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
Game:
public class GameBoard extends JPanel{
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.BLUE);
g.drawRect(200, 200, 200, 200);
}
}
Never, ever call paintComponent directly, no external source has any reason to do so. Also, what do you thing would happen if you passed it null?
You should start by having a look at Performing Custom Painting and Painting in AWT and Swing to get a better understand of how paint in Swing works.
The Swing API basically uses a delegate model, where the system delegates responsibility of the paint of each component to the component. This is achieved by the system calling the components paint method, which in-turn calls (among a few others) paintComponent.
Swing also uses a passive rendering approaching, meaning that painting occurs at the discretion of the paint system. You component is notified of the need when its paint method is called. This may occur at any time.
In order for a component to be painted, it must first be added to container which is realised on the screen (has a native peer), in most cases, this means that the component hierarchy needs to resolve to some kind of window based class, like JFrame.
So, the answer to your question is:
Read the above documentation (and get a better understanding of how the API works)
Add your GameBoard to a container which can be resolved to a window based class
Never call paint or paintComponent directly
Reflection....
private mainWindow view;
private mainModel model;
public GameBoard(mainModel m, mainWindow v)
{
view = v;
model = m;
}
To me, this makes no sense. There is no reasonable reason why GameBoard needs a reference to mainWindow. GameBoard is, in of itself, a "view". If anything, the only thing you "should" be passing to GameBoard (assuming you're trying to use a MVC) is a controller
I'm trying to understand what actually paints components in Swing. I read this article about painting in AWT and Swing and now tried to write the following simple program:
//A simple wrapper to understan how paint() works
public class MyButton extends JButton{
/**
* Default serialVersionUID
*/
private static final long serialVersionUID = 1L;
private final JButton jButton;
public MyButton(JButton jButton) {
this.jButton = jButton;
}
#Override
public void paint(Graphics g){
jButton.paint(g);
}
}
But when I try to add MyButton to frame
JFrame frame = new JFrame("Hello swing");
JPanel panel = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.add(new MyButton(button));
frame.add(panel);
it renders nothing
But after deleting
#Override
public void paint(Graphics g){
jButton.paint(g);
}
it renders the empty button:
QUESTION: Why does it behave that way? Why does the delegating cause rendering to fail?
First of all when you post a question you should post a proper SSCCE that demonstrates the problem. We can't copy/compile random lines of code. Until a problem is solved, you don't know what part of the code is causing the problem.
Why does the delegating cause rendering to fail?
My guess would be that the size of the button is (0, 0) so there is nothing to paint.
When you get rid of the custom paint method, then the real button can be painted because it does have a size because the layout manager has done its job.
public class Demo extends JFrame{
public static void main(String[] args)
{
JPanel panel = new JPanel();
getContentPane().setLayout(new BorderLayout());
panel.add(new JButton("Test"));
this.getContentPane().add(panel, BorderLayout.CENTER);
this.setSize(200,200);
this.setVisible(true);
}
}
If you want to add UI Components do it like that, don't use paint in any way.
If you want to paint for example a rectangle follow this tutorial: https://docs.oracle.com/javase/tutorial/uiswing/painting/
Your paint method does not draw the MyButton object, but instead draws the JButton which is member of your class. The problem now is, that this Button has not been added to the panel and so it's drawn on nothing. By removing your paint method, super.paint(g) is called because your class has no paint method and so your button, but not the member JButton is drawn.
I hope you understand what I am trying to explain to you.
I know this question has been asked before but i cant seem to implement any of the other answers to my project. So i have my paint method in my player class here.
public void paintComponent(Graphics g)
{
//makes player(placeholder for real art)
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(x,y,50,30);
}
Then I have my main class here.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/**
* Write a description of class Main here.
*
* #author Richard Zins
* #V01
*/
public class Main extends JFrame
{
public static void main(String[]args)
{
Player p1 = new Player();
Main m = new Main(p1);
}
public Main(Player p1)
{
JFrame ar = new JFrame();
JLabel background = new JLabel(new ImageIcon("/Users/rizins/Desktop/PacManTestBackGround.jpg"));
ar.setTitle("Runner Maze");
ar.setSize(800,600);
ar.add(background);
ar.setVisible(true);
ar.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ar.add(p1);
}
}
Now I cant seem to get my player object to paint over my background any help would be appreciated!
There are a couple of mistakes...
JPanel by default is opaque, so you need to change it to be transparent
JFrame uses a BorderLayout by default, so only one component will be shown at the (default) center position, in this case, the last thing you add.
You should call setVisible last
Instead, set a layout manager for the JLabel and add your player class to it. Instead of adding the JLabel to the frame, you should make the label the contentPane for the frame, for example...
p1.setOpaque(false);
JFrame ar = new JFrame();
ar.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel background = new JLabel(new ImageIcon("/Users/rizins/Desktop/PacManTestBackGround.jpg"));
ar.setTitle("Runner Maze");
ar.setContentPane(background);
ar.setLayout(new BorderLayout());
ar.add(p1);
ar.pack();
ar.setVisible(true);
I should point out that using a JLabel to display a background image like this could cause you problems, as the JLabel only uses the text and icon properties to calculate its preferred size, this could cause some child components to be laid out beyond its visible range.
See How to set a background picture in JPanel for more details and a possible solution
You can make the JPanel transparent by setting the opaque to false. e.g:
panel.setOpaque(false)
Try is if this work for you.
Use a JLayeredPane and add your background at the index 0 (indexed with an Integer not an int). Then you add another JPanel that is not opaque (like in #Bahramdun Adil 's answer) and add your player to that.
This way you can have a background and display your player at the same time.
I'm creating a gui for my project. When the gui is first loaded only background is visible, so buttons are not visible, but when mouse over them, they are visible. What is the solve this problem?
public class Home extends JFrame{
//New JPanel
private JPanel home;
//Creating image url. You must be change url
ImageIcon icon = new ImageIcon("img//home1.jpeg");
//Home Class
public Home(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 960, 640);
setTitle("LoneyTunes Crush");
home = new JPanel();
home.setBorder(new EmptyBorder(5, 5, 5, 5));
home.setLayout(new BorderLayout(0, 0));
setContentPane(home);
getContentPane().setLayout(null);
JLabel background = new JLabel(new ImageIcon("img//giphy."));
getContentPane().add(background);
background.setLayout(new FlowLayout());
//Creating Buttons
JButton play = new JButton("Play");
play.setBounds(20, 20, 200, 30);
JButton setting = new JButton("Settings");
setting.setBounds(20, 60, 200, 30);
JButton exit = new JButton("Exit");
exit.setBounds(20, 100, 200, 30);
//Adding Buttons
home.add(play);
home.add(setting);
home.add(exit);
//ActionListeners
play.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
home.setVisible(false);
difficulty.setVisible(true);
}
});
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(1);
}
});
validate();
}
//Background paint method
public void paint(Graphics g){
g.drawImage(icon.getImage(), 0, 0, getWidth(), getHeight(), null);
}
}
Main Class
public class MainClass {
public static Home pencere;
public static void main(String args[]){
pencere=new Home();
pencere.setVisible(true);
}
}
Don't paint on top-level containers like JFrame as they already carry the burden of painting all of it's components.
Instead paint on JPanel or JComponent and Override it's paintComponent method.
On top of overriding paintComponent (or in your case paint), you need to also call super.paintComponent (in your case super.paint) inside the the method (first call under the method signature), as to not break the paint chain. Failing to do so may and probably will leave you with undesired paint artifacts.
Avoid using null layouts for a number of reason. Different platform will treat them differently. They are difficult to maintain, among many other reasons. Instead use layout managers, and let them do the laying out and sizing of the components, as they were designed to do with Swing apps. Learn more at Laying out components Within a Container
Setting Home pancere as a static class member of MainClass is completely pointless. Just declare and instantiate both in the main method.
Swing apps should be run on the Event Dispatch Thread (EDT). You can do so by wrapping your the code inside your main method with a SwingUtilities.invokeLater.... See more at Initial Threads
Instead of trying to make panels visible and not visible or adding an removing panel, consider using a CardLayout which will "layer" panels, and you can navigate through them with CardLayout's methods like show(), next(), previous(). See more at How to Use CardLayout
By time of deployments, the images you are using will need to become embedded resources, and should be loaded from the class path, and not from the file system. When you pass a String to ImageIcon, you are telling the program to look in the file system, which may work in your development environment, but that's it. See the wiki tag on embedded-resource an pay close attention to the very last link that will provide you will some resources on how to use and load embedded resources if the info doesn't provide enough detail.
Problem is with
getContentPane().setLayout(null);
remove it as you have already set the layout to a Border Layout and you will see all these buttons.
Just make sure that the setvisibility of all other panels except the one which you wish to display is set to false.I too had a similar problem but i had forgotten to set visibility of one of the 10 panels to false.Problem resolved once i set it to false.
I don't know how this worked for me I just typed jf.setVisible(true); at the end after adding all the GUI codes.
public Calculator(){
jf = new JFrame("Basic Calculator");
jf.setLayout(GridBagLayout);
jf.setSize(306, 550);
jf.setLocation(530, 109);
//all the GUI things like JButton, JLabel, etc...
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Try putting validate(); method on your main frame. I think it would help you.
I am currently learning Java, and I am stuck with something at the moment.
I was looking for a way to add an image to my JFrame.
I found this on the internet:
ImageIcon image = new ImageIcon("path & name & extension");
JLabel imageLabel = new JLabel(image);
And after implementing it to my own code, it looks like this (this is only the relevant part):
class Game1 extends JFrame
{
public static Display f = new Display();
public Game1()
{
Game1.f.setSize(1000, 750);
Game1.f.setResizable(false);
Game1.f.setVisible(true);
Game1.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Game1.f.setTitle("Online First Person Shooter");
ImageIcon image = new ImageIcon("C:\\Users\\Meneer\\Pictures\\image.png");
JLabel imageLabel = new JLabel(image);
add(imageLabel);
}
}
class Display extends JFrame
{
}
When running this code, it doesn't give me any errors, but it also doesn't show the picture. I saw some questions and people having the same problem, but their code was completely different from mine, they used other ways to display the image.
You don't need to use another JFrame instance inside the Game JFrame:
Calling setVisible(flag) from the constructor is not preferable. Rather initialize your JFrame from outside and put your setVisible(true) inside event dispatch thread to maintain Swing's GUI rendering rules using SwingUtilities.invokeLater(Runnable)
Do not give size hint by setSize(Dimension) of the JFrame. Rather use proper layout with your component, call pack() after adding all of your relevant component to the JFrame.
Try using JScrollPane with JLabel for a better user experience with image larger than the label's size can be.
All of the above description is made in the following example:
class Game1 extends JFrame
{
public Game1()
{
// setSize(1000, 750); <---- do not do it
// setResizable(false); <----- do not do it either, unless any good reason
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Online First Person Shooter");
ImageIcon image = new ImageIcon("C:\\Users\\Meneer\\Pictures\\image.png");
JLabel label = new JLabel(image);
JScrollPane scrollPane = new JScrollPane(label);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
add(scrollPane, BorderLayout.CENTER);
pack();
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Game1().setVisible(true);
}
});
}
}
do this after creating Jlabel
imageLabel.setBounds(10, 10, 400, 400);
imageLabel.setVisible(true);
also set the layout to JFrame
Game.f.setLayout(new FlowLayout);
You are adding the label to the wrong JFrame. Also, move the setVisible() to the end.
import javax.swing.*;
class Game1 extends JFrame
{
public static Display f = new Display();
public Game1()
{
// ....
Game1.f.add(imageLabel);
Game1.f.setVisible(true);
}
}
Also try to use image from resources, and not from hardcoded path from your PC
You can look in here, where sombody asked similar question about images in Jframe:
How to add an ImageIcon to a JFrame?
Your problem in next you add your JLabel to Game1 but you display another Frame(Display f). Change add(imageLabel); to Game1.f.add(imageLabel);.
Recommendations:
1)according to your problem: Game1 extends JFrame seems that Display is also a frame, use only one frame to display content.
2) use pack() method instead of setSize(1000, 750);
3)call setVisible(true); at the end of construction.
4)use LayoutManager to layout components.