JFrame paint does not overriding - java

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.

Related

Why using an if statement inside a paintComponent(Graphics g) method invalidates all code inside the method?

I'm trying to create a JFrame object which contains a JPanel object. Inside the JPanel object there are 3 JButtons that when clicked, are intended to change the background color of the JPanel.
I also want to draw an image which size equals the one of the JPanel object to give the impression of a background image but as you may imagine I want it to be drown only the first time, when the user hasn't clicked any buttons yet. Once a button is clicked I intend to call the repaint() method inherited from the Component class which in my understanding should make a call to the paintComponent(Graphics g).
Given the fact I want the image to be drawn only when the user hasn't clicked any buttons, inside the paintComponent(Graphics g) I'm trying to use an if statement so when the paintComponent(Graphics g) method is called the second time by the repaint() method, it will execute inside an else statement and simply call the super.paintComponent(Graphics g) method that in my understanding, should paint it without the image. The problem is that as soon as I put the if statement inside the paintComponent method it seems to invalidate the entire code inside the method.
Any suggestions or explanation on why is this happening would be appreciated.
The code is below:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class PruebaEventosSelf {
public static void main(String[] args) {
// TODO Auto-generated method stub
MarcoBotonSelf marco=new MarcoBotonSelf();
marco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class MarcoBotonSelf extends JFrame{
public MarcoBotonSelf() {
setExtendedState(MarcoBotonSelf.MAXIMIZED_BOTH);
setTitle("National Aeronautics and Space Administration NASA");
Image image=Toolkit.getDefaultToolkit().getImage("C:\\Users\\wagne\\OneDrive\\Desktop\\Nasa.png");
setIconImage(image);
LaminaBoton lamina=new LaminaBoton();
add(lamina);
setVisible(true);
}
}
class LaminaBoton extends JPanel implements ActionListener {
JButton botonAzul=new JButton("Blue");
JButton botonNegro=new JButton("Black");
JButton botonGris=new JButton("Gris");
boolean repaint=false;
public LaminaBoton() {
botonAzul.addActionListener(this);
add(botonAzul, Container.CENTER_ALIGNMENT);
botonNegro.addActionListener(this);
add(botonNegro, Container.LEFT_ALIGNMENT);
botonGris.addActionListener(this);
add(botonGris, Container.CENTER_ALIGNMENT);
}
public void paintComponent(Graphics g) {
if(repaint) {
super.paintComponent(g);
}else {
Image imagen=Toolkit.getDefaultToolkit().getImage("C:\\Users\\wagne\\OneDrive\\Desktop\\NASA.jpg");
g.drawImage(imagen, 0, 0, this);
}
}
public void actionPerformed(ActionEvent e) {
Object pulsado=e.getSource();
if (pulsado==botonAzul){
repaint=true;
repaint();
this.setBackground(Color.blue);
System.out.println("Blue is working!");
}else if(pulsado==botonNegro) {
System.out.println("Black is working!");
setBackground(Color.BLACK);
}else {
System.out.println("Gray is working!");
setBackground(Color.DARK_GRAY);
}
}
}
HERE'S ANOTHER WAY I TRIED:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class PruebaEventosSelf {
public static void main(String[] args) {
// TODO Auto-generated method stub
MarcoBotonSelf marco=new MarcoBotonSelf();
marco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class MarcoBotonSelf extends JFrame{
public MarcoBotonSelf() {
setExtendedState(MarcoBotonSelf.MAXIMIZED_BOTH);
setTitle("National Aeronautics and Space Administration NASA");
Image image=Toolkit.getDefaultToolkit().getImage("C:\\Users\\wagne\\OneDrive\\Desktop\\Nasa.png");
setIconImage(image);
LaminaBoton lamina=new LaminaBoton();
add(lamina);
setVisible(true);
}
}
class LaminaBoton extends JPanel implements ActionListener {
JButton botonAzul=new JButton("Blue");
JButton botonNegro=new JButton("Black");
JButton botonGris=new JButton("Gris");
boolean repaint=false;
public LaminaBoton() {
botonAzul.addActionListener(this);
add(botonAzul, Container.CENTER_ALIGNMENT);
botonNegro.addActionListener(this);
add(botonNegro, Container.LEFT_ALIGNMENT);
botonGris.addActionListener(this);
add(botonGris, Container.CENTER_ALIGNMENT);
}
public void paintComponent(Graphics g) {
Image imagen=Toolkit.getDefaultToolkit().getImage("C:\\Users\\wagne\\OneDrive\\Desktop\\NASA.jpg");
g.drawImage(imagen, 0, 0, this);
if (repaint) super.paintComponent(g);
}
public void actionPerformed(ActionEvent e) {
Object pulsado=e.getSource();
if (pulsado==botonAzul){
repaint=true;
repaint();
this.setBackground(Color.blue);
System.out.println("Blue is working!");
}else if(pulsado==botonNegro) {
System.out.println("Black is working!");
setBackground(Color.BLACK);
}else {
System.out.println("Gray is working!");
setBackground(Color.DARK_GRAY);
}
}
}
I've tried another 4 different ways but they all seem to lead to the same result of the image not being drown not even if the use hasn't clicked any buttons.
Your paintComponent() method should ALWAYS call super.paintCompnent(g); as the first statement in the method. Then it should draw the image only if the repaint variable is false.
It would be better - and more logically readable - to call that variable paintImage and set it initially to true, then the button listener sets it to false, and the paintComponent() method draws the image only if paintImage is true.

Calling #Override on paintComponent() when state changes

How do I override a paintComponent method with response to a state change?
Error message: void is an invalid type for the variable paintComponent
public class MyContainer extends Container {
public void paintComponent(Graphics m){
m.drawArc(100,100,100,100,100,100);
m.setColor(Color.green);
m.fillArc(100,100,100,100,100,100);
}
public static void main(String[] args){
Container y = new Container();
JFrame x = new JFrame();
JPanel gg = new JPanel();
x.add(y);
x.setTitle(" Shape Changer");
x.setBounds(100,50,500,300);
x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
x.getContentPane().add(new ContentPanel());
x.getContentPane().add(new ContnetPanel());
x.setContentPane(new ContnetPanel());
x.setVisible(true);
}
static class ContentPanel extends JPanel{
private Graphics g;
private JPanel ss;
public void paint(Graphics g){
g.drawArc(100,100,100,100,100,100);
g.fillRect(100, 100,100,100);
}
public ContentPanel(){
}
}
static class ContnetPanel extends JPanel implements ActionListener, ChangeListener{
JComboBox comboerbox;
class appres {
public void paint(Graphics h){
h.drawRect(100,100,100,100);
h.setColor(Color.red);
h.fillRect(100,100,100,100);
}
}
public ContnetPanel(){
comboerbox = new JComboBox();
comboerbox.addItem("Red Square");
comboerbox.addItem("Blue Square");
comboerbox.addItem("Green Square");
comboerbox.setSelectedIndex(1);
add(comboerbox);
setLayout(new GridLayout(2,1));
}
#Override
protected void paintComponent(Graphics h){
super.paintComponent(h);
h.drawArc(100,100,100,100,100,100);
h.setColor(Color.blue);
h.fillArc(100,100,100,100,100,100);
repaint();
}
int yy = 0;
public void actionPerformed(ActionEvent evt){
switch(comboerbox.getSelectedIndex()){
case 0:yy=0;
case 1: yy=1;
case 2: yy=2;
}
}
//evt.getSource()==comboerbox
public void stateChanged(ChangeEvent evt){
if(evt.getSource()==comboerbox){
#Override
protected void paintComponent(Graphics h){
super.paintComponent(h);
h.drawArc(100,100,100,100,100,100);
h.setColor(Color.blue);
h.fillArc(100,100,100,100,100,100);
repaint();
}
}
else
{
System.out.println("DONE");
}
}
}
}
Of course, the paintComponent method isn't a variable. How would I override paintComponent here? Or is a better way to change the shape with response to state change? That would be great too!
Thanks in advance, love you guys!
In your last question: How do I make the superclass go beyond just the content pane? you were given a link to the Swing tutorial for some Swing basics.
Well there is also a section on Custom Painting for you to read. You can then download the example and play with it to understand how painting works.
Basically the Container class doesn't have a paintComponent() method so you should not be trying to do custom painting in that class.
If you want to change a painting property, then you need to add a method to your class to change the state of the property and then invoke repaint() on itself.
So from the tutorial example in Step 3 you can see how the moveSquare(...) method changes the state of the class and then invokes repaint().
Note you should never invoke repaint() in the paintComponent() method since this will cause the painting to be continually rescheduled.

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

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.

Grapghic doesn't move

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.

Categories

Resources