Grapghic doesn't move - java

I'm trying to make a code that will move a red ball with JButtons (and later add keybinders). There are no problems when I compile and when I run I see the ball but the JButtons won't affect him. I think the problem might be that the ball is drawed only once and then is called again and again without being drawed in the new position but I don't know how to fix that.
1) does anybody know how I can fix that?
2) is there a way to change the shape of a JPanel to a ball? (that would probably be a simpler way to move him)
package il.co.atlantis;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class KeyBinders implements ActionListener {
boolean right=true, left=false, up=false, down=false, inGame=true;
JPanel backgroundPanel, bannerPanel, scorePanel, applePanel;
JLabel currentScoreLabel, highestScoreLabel;
JButton upButton, downButton, rightButton, leftButton;
long millis =System.currentTimeMillis(), millisn =System.currentTimeMillis();
public static final int WID = 10, HEI = 10;
public static int x1 = 100, y1 = 100;
public class MyGraphics extends JComponent {
private static final long serialVersionUID = 1L;
MyGraphics() {
setPreferredSize(new Dimension(700, 500));
}
public void moveRight(){
++x1;
}
public void moveLeft(){
--x1;
}
public void moveUp(){
--y1;
}
public void moveDown(){
++y1;
}
public void paintComponent(Graphics g){
super.paintComponents(g);
g.setColor(Color.red);
g.fillOval(x1, y1, WID, HEI);
}
}
public JPanel CreateContentPane (){
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
backgroundPanel = new JPanel();
backgroundPanel.setBackground(Color.black);
backgroundPanel.setLocation(100, 10);
backgroundPanel.setSize(700, 500);
totalGUI.add(backgroundPanel);
upButton = new JButton("up");
upButton.setLocation(0,0);
upButton.setSize(50,50);
totalGUI.add(upButton);
downButton = new JButton ("down");
downButton.setLocation(0,50);
downButton.setSize(50,50);
totalGUI.add(downButton);
rightButton = new JButton("right");
rightButton.setLocation(0,100);
rightButton.setSize(50,50);
totalGUI.add(rightButton);
leftButton = new JButton("left");
leftButton.setLocation(0,150);
leftButton.setSize(50,50);
totalGUI.add(leftButton);
MyGraphics tr = new MyGraphics();
tr.setLocation(100, 100);
backgroundPanel.add(tr);
return totalGUI;
}
public void ActionPerformed(ActionEvent h){
if(h.getSource() == upButton) {
--y1;
}
else if(h.getSource() == downButton){
++y1;
}
else if(h.getSource() == leftButton){
--x1;
}
else if(h.getSource() == rightButton){
++x1;
}
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("[=] JButton Scores! [=]");
//Create and set up the content pane.
KeyBinders demo = new KeyBinders();
frame.setContentPane(demo.CreateContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(280, 190);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public KeyBinders() {
// TODO Auto-generated constructor stub
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}

When you invoke action event, actionPerformed() function gets called, as you did. You have change the drawing position too. you need to call Component.repaint() which tells Swing t hat the entire component, whichever one you specified to be repainted , must be updated . So add this function calling in your code. For example:
public void ActionPerformed(ActionEvent h){
if(h.getSource() == upButton) {
--y1;
}
else if(h.getSource() == downButton){
++y1;
}
else if(h.getSource() == leftButton){
--x1;
}
else if(h.getSource() == rightButton){
++x1;
}
repaint();
}
Check the tutorial: Performing Custom Painting.

There's a method called repaint() you should familiarize yourself with.
When called on a component (such as a JFrame) it'll repaint all the components within. Naturally you need to call it if you want your changes to become visible on the screen.
As for custom painting, you shouldn't use a Component at all, rather use the Graphics.fillRect/fillOval etc. methods to just draw what you want.
See here for the custom painting tutorial.

Related

My game is flickering due to my painting directly in JFrame. How do I use JPanel? [duplicate]

I think I need to put some code where the comment is (or maybe use non static method but I am not sure). The main method creates the window and then starts the graphics method. I would like the blue square to flash.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class paintTest extends JPanel{
private static JFrame theWindow = new JFrame("Window");
static boolean blueSqr = false;
public void paint(Graphics g) {
g.setColor(Color.RED);
g.fillRect(10, 10, 10, 10);
if(blueSqr){
g.setColor(Color.BLUE);
g.fillRect(10, 10, 10, 10);
}
}
public static void main(String[] args){
createWindow();
theWindow.getContentPane().add(new paintTest());
while(true){
blueSqr = false;
System.out.println("off");
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
blueSqr = true;
// Needs something here
System.out.println("on");
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
}
}
public static void createWindow(){
theWindow.setSize(500, 500);
theWindow.setLocationRelativeTo(null);
theWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theWindow.setVisible(true);
}
}
Any help would be really good.
Use a Swing Timer to call repaint(). Also, override paintComponent() in a JPanel, rather than paint().
Something like this:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PaintTest extends JPanel{
boolean blueSqr = false;
PaintTest() {
setPreferredSize(new Dimension(100,25));
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
blueSqr = !blueSqr;
repaint();
}
};
Timer timer = new Timer(1000,al);
timer.start();
}
public void paintComponent(Graphics g) {
Color c = (blueSqr ? Color.BLUE : Color.RED);
g.setColor(c);
g.fillRect(10, 10, 10, 10);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame theWindow = new JFrame("Window");
theWindow.getContentPane().add(new PaintTest());
createWindow(theWindow);
}
});
}
public static void createWindow(JFrame theWindow){
theWindow.pack();
theWindow.setLocationByPlatform(true);
theWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theWindow.setVisible(true);
}
}
There were other improvements I could not be bothered documenting (code speaks louder than words). If you have any questions (check the docs first, then) ask.
your issues are
1) by calling Thread.sleep(int) in the Swing related code, never do that, for delaying in Swing (there are lots of topics about why not use sleep in programing languages ...) use Swing Timer
2) your JPanel doesn't returns any XxxSize
3) for Swing use paintComponent(), only if you have got really important reasons then use method paint() more about repaint and animating Graphics in the 2D Graphics tutorial
4) Swing GUI should be built in the Event Dispatch Thread

Java Graphics Update/Repaint Graphic

I'm trying to work with the Java paint
utility and it's been a bit of a hassle.
I'm trying to do something which I assume is quite basic.
I'm drawing a square Graphic to a JPanel and then trying
to move it using repaint
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
public class testGui {
static gui gc_gui;
static int gv_x;
static int gv_y;
public static void main(String[] args) {
gc_gui = new gui();
gv_x = 50;
gv_y = 50;
gc_gui.cv_frame.setVisible(true);
}
public static class gui {
JFrame cv_frame;
content cv_content;
public gui() {
cv_frame = new JFrame();
cv_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cv_frame.setTitle("Test GUI");
cv_frame.setSize(600, 400);
cv_frame.setLayout(new FlowLayout());
cv_content = new content();
cv_content.setBackground(Color.Black);
cv_content.setPreferredSize(new Dimension(500, 300));
cv_frame.add(cv_content);
gv_x = 0;
gv_y = 0;
cv_content.update();
}
}
public static class content extends JPanel {
public void paint(Graphics graphic) {
super.paint(graphic);
draw(graphic);
}
public void update() {
super.repaint();
}
public void draw(Graphics graphic) {
Graphics2D graphic2D = (Graphics2D) graphic;
graphic2D.setPaint(Color.Red);
graphic2D.fillRect(gv_x, gv_y, 100, 100);
}
}
}
I don't know why the call to the update function isn't doing
anything though.
It draws the square at 50x and 50y, the sets it to 0x and 0y
immediately and then when I call repaint I expected it to
be moved to it's new coordinates although it's still at
50x and 50y.
Why is this?
Your solution is to use KeyBindings.
https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
and also.
You need to create a Swing Timer, Thread, or Loop , that manages the frames to be painted. and such
Here is a link for Swing Timers as they are pretty easy to implement:
https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html
A lot of programs I see also have this ( AKA. working with threads.):
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});

Java mouseClicked complication

Code works, my bad. But I'm still open to suggestions on how to improve or make the code more elegant.
I have created this layout and I want to be able to draw a circle whenever the user clicks on the white area.
Couldn't post an image, so here is the link
The white area is basically a rectangle. But something with my code isn't working, it just doesn't respond to mouse clicks. When I tried to see if it responds to mouseDragged it worked perfectly but this isn't what I need.
Here is my code, some "tests" are put as /comments/ but neither of them work as intended.
I would be very grateful for help. Here is my code:
import java.awt.*;
import java.awt.Graphics;
import javax.swing.*;
public class CitiesMapPanel extends JPanel implements MouseListener {
private JButton cmdAddWay, cmdFindPath, cmdClearMap, cmdClearPath;
private JLabel lblFrom, lblTo;
private JTextField txtFrom, txtTo;
public CitiesMapPanel() {
cmdAddWay = new JButton("Add Way");
cmdFindPath = new JButton("Find Path");
cmdClearMap = new JButton("Clear Map");
cmdClearPath = new JButton("Clear Path");
lblFrom = new JLabel("From");
lblTo = new JLabel("To");
txtFrom = new JTextField(6);
txtTo = new JTextField(6);
this.addMouseListener(this);
setLayout(new BorderLayout());
add(buildGui(), BorderLayout.SOUTH);
}
private JPanel buildGui() {
JPanel buttonsBar = new JPanel();
//The "south" of the BorderLayout consist of a (2,4) GridLayout.
buttonsBar.setLayout(new GridLayout(2,4));
buttonsBar.add(lblFrom);
buttonsBar. add(txtFrom);
buttonsBar.add(lblTo);
buttonsBar.add(txtTo);
buttonsBar.add(cmdAddWay);
buttonsBar.add(cmdFindPath);
buttonsBar.add(cmdClearMap);
buttonsBar.add(cmdClearPath);
return buttonsBar;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.white);
g.fillRect(0, 0, this.getSize().height, this.getSize().width);
}
public static void main(String[] args) {
JFrame frame = new JFrame("layout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(530, 550);
CitiesMapPanel gui = new CitiesMapPanel();
frame.add(gui);
frame.setVisible(true);
}
/*abstract private class MyMouseListner implements MouseListener{
public void mouseClicked(MouseEvent e){
int x = e.getX();
int y = e.getY();
Graphics g = getGraphics();
g.setColor(Color.black);
g.fillOval(x,y,15,15);
}
}*/
#Override
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
Graphics g = getGraphics();
g.setColor(Color.black);
g.fillOval(x,y,15,15);
System.out.println("test");
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
The click listener is not the problem. Your approach to painting is simply wrong. You can't do a getGraphic, paint on it, and expect the result to be presented. In Swing (AWT) things work fundamentally different. You need to either create an off screen image that you paint to and that you then present on screen in your paintComponent method, or you need to track the objects you want to paint in a data structure and paint those in your paintComponent method. You can trigger a repaint in your click listener by calling repaint so the UI subsystems knows about the changed state that requires a repaint of your component.
Read more about the basics in the Swing painting tutorial.

To create JButton, JSlider and Graphics in a program file

Help me to create a class file which consists of JButton and JSlider and Java Graphics.
I tried a lot of methods but not working in netbeans 7.2: Jpanel, Jcomponent, paint(), paintComponent().
Can any one give me a class file for example to create that one?
My code is here:
package floating;
import designs.*;
import java.awt.*;
import javax.swing.*;
public class Test extends JFrame
{
String frame_name;
boolean START,PASS;
int SPEED=1;
JSlider jSlider1 = new javax.swing.JSlider();
JSeparator js=new JSeparator();
JToggleButton jToggleButton1 = new javax.swing.JToggleButton("START");
JToggleButton jToggleButton2 = new javax.swing.JToggleButton("PASS");
Test(String a)
{
JFrame jf=new JFrame(a);
Dimension dim=Toolkit.getDefaultToolkit().getScreenSize();
jf.setSize(dim.width,dim.height-30);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
js.setOrientation(SwingConstants.VERTICAL);
js.setForeground(Color.red);
js.setLocation(dim.width/2,0);
js.setPreferredSize(dim);
js.setSize(10,dim.height);
jf.add(js);
jSlider1.setLocation(dim.width-300,20);
jSlider1.setSize(250,50);
jSlider1.setToolTipText("Set to Seconds");
jSlider1.setMinimum(1);jSlider1.setMaximum(5);jSlider1.setMajorTickSpacing(1);jSlider1.setMinorTickSpacing(1);jSlider1.setValue(1);
jSlider1.setPaintLabels(true);
jSlider1.setPaintTicks(true);
jSlider1.setPaintTrack(true);
jSlider1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jSlider1MouseClicked(evt);
}
});
jf.add(jSlider1);
jToggleButton1.setLocation((dim.width/2)+30,25);
jToggleButton1.setSize(100,30);
jToggleButton1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jToggleButton1ItemStateChanged(evt);
}
});
jToggleButton2.setLocation((dim.width/2)+50+100,25);
jToggleButton2.setSize(100,30);
jToggleButton2.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jToggleButton2ItemStateChanged(evt);
}
});
jf.add(jToggleButton1);
jf.add(jToggleButton2);
jf.setLayout(null); \\if layout is null the only all buttons and slider at positions and showing in JFrame
jf.setVisible(true);
}
public void jToggleButton1ItemStateChanged(java.awt.event.ItemEvent evt)
{
if(jToggleButton1.getActionCommand()=="START")
{
System.out.printf(jToggleButton1.getText());
jToggleButton1.setText("STOP");
this.START=true;
System.out.println(this.START);
}
else
{
System.out.printf(jToggleButton1.getText());
jToggleButton1.setText("START");
this.START=false;
System.out.println(this.START);
}
}
public void jToggleButton2ItemStateChanged(java.awt.event.ItemEvent evt)
{
if( jToggleButton2.getActionCommand()=="PASS")
{
System.out.printf(jToggleButton2.getText());
jToggleButton2.setText("RESUME");
this.PASS=true;
System.out.println(" "+this.PASS);
}
else
{
System.out.printf(jToggleButton2.getText());
jToggleButton2.setText("PASS");
this.PASS=false;
System.out.println( " " +this.PASS);
}
}
private void jSlider1MouseClicked(java.awt.event.MouseEvent evt)
{
this.SPEED=jSlider1.getValue();
System.out.println(SPEED);
}
public static void main(String args[])
{
Test a=new Test("Test");
}
public void paint(Graphics g) // for example but not shwowing in JFrame.
{
g.setColor(Color.red);
RRectangle a=new RRectangle(60,100,250,190,60,60);
a.drawShape(g);
System.out.println(a);
}
}
Your class extends JFrame, but then within your class you create an instance of JFrame and you add all the components to this instance of JFrame and make this frame visible. The extended class is never used or displayed.
So the paint() method that you override does nothing.
you should NOT be extending JFrame.
custom painting is done by overriding the paintComponent() method of a JPanel and then you add the panel to the frame
I gave you a link to the Swing tutorial in my comment above. Read the section on Custom Painting for a working example.

JFrame paint does not overriding

to execute flow chart Symbols.
But JFrame paint method is not working for this method.
package floating;
import designs.*; //mydesings for executing flow chart Symbols
import java.awt.*;
import javax.swing.*;
public class Test extends JFrame
{
boolean START,PASS; //for using
int SPEED=1;
JSlider jSlider1 = new javax.swing.JSlider();
JSeparator js=new JSeparator();
JToggleButton jToggleButton1 = new javax.swing.JToggleButton("START");
JToggleButton jToggleButton2 = new javax.swing.JToggleButton("PASS");
Test(String a)
{
JFrame jf=new JFrame(a);
Dimension dim=Toolkit.getDefaultToolkit().getScreenSize();
jf.setSize(dim.width,dim.height-30);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jToggleButton1.setLocation((dim.width/2)+30,25);
jToggleButton1.setSize(100,30);
jToggleButton1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jToggleButton1ItemStateChanged(evt);
}
});
jToggleButton2.setLocation((dim.width/2)+50+100,25);
jToggleButton2.setSize(100,30);
jToggleButton2.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jToggleButton2ItemStateChanged(evt);
}
});
js.setOrientation(SwingConstants.VERTICAL);
js.setForeground(Color.red);
js.setLocation(dim.width/2,0);
js.setPreferredSize(dim);
js.setSize(10,dim.height);
jf.add(js);
jSlider1.setLocation(dim.width-300,20);
jSlider1.setSize(250,50);
jSlider1.setToolTipText("Set to Seconds");
jSlider1.setMinimum(1);jSlider1.setMaximum(5);jSlider1.setMajorTickSpacing(1);
jSlider1.setMinorTickSpacing(1);jSlider1.setValue(1);
jSlider1.setPaintLabels(true);
jSlider1.setPaintTicks(true);
jSlider1.setPaintTrack(true);
jSlider1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jSlider1MouseClicked(evt);
}
});
jf.add(jSlider1);
jf.add(jToggleButton1);
jf.add(jToggleButton2);
jf.setLayout(null);
jf.setVisible(true);
}
public void jToggleButton1ItemStateChanged(java.awt.event.ItemEvent evt)
{
if(jToggleButton1.getActionCommand()=="START")
{
System.out.printf(jToggleButton1.getText());
jToggleButton1.setText("STOP");
this.START=true;
System.out.println(this.START);
}
else
{
System.out.printf(jToggleButton1.getText());
jToggleButton1.setText("START");
this.START=false;
System.out.println(this.START);
}
}
public void jToggleButton2ItemStateChanged(java.awt.event.ItemEvent evt)
{
if( jToggleButton2.getActionCommand()=="PASS")
{
System.out.printf(jToggleButton2.getText());
jToggleButton2.setText("RESUME");
this.PASS=true;
System.out.println(" "+this.PASS);
}
else
{
System.out.printf(jToggleButton2.getText());
jToggleButton2.setText("PASS");
this.PASS=false;
System.out.println( " " +this.PASS);
}
}
private void jSlider1MouseClicked(java.awt.event.MouseEvent evt)
{
this.SPEED=jSlider1.getValue();
System.out.println(SPEED);
}
#Override
public void paint(Graphics g) //testing paint method
{
super.paint(g);
g.drawLine(10, 20, 50, 70);
repaint();
}
public static void main(String args[])
{
Test a=new Test("Test");
}
}
Test class extends JFrame. So if you want to have overridden paint method to work, you have to create an object of Test class. And make it setVisible(true)
In stead, you are creating another JFrame object in Test's constructor. Don't create it. The object of Test itself is a JFrame. Add all components to Test object in stead of JFrame object (jF).
Hope this helps.
Don't invoke repaint() from a painting method. This will cause an infinite loop.
Custom painting is done by overriding the paintComponent() method of a JPanel (or JComponent) and then you add the panel to the frame. Read the section from the Swing tutorial on Custom Painting for more information and examples. Start with the example from the tutorial and make changes so your class is better designed.
Don't use "==" for string comparisons. Use the equals(...) method.
Also, in the future, post a proper SSCCE when you ask a question. Your question is about painting so most of the code you posted is unrelated to the question.

Categories

Resources