import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CirclePanel extends JPanel {
private JTextField xField, yField, diameterField;
private JButton Redraw;
private JLabel xLabel, yLabel, rLabel;
Circle myCircle = new Circle (150, 150, 30, Color.red, Color.white);
Graphics g;
//Paint objects on panel
public void paintComponent (Graphics page) {
super.paintComponent(page);
g = page;
myCircle.draw(g);
}
public CirclePanel(){
xLabel = new JLabel("X= ");
yLabel = new JLabel("Y= ");
rLabel = new JLabel("R= ");
xField = new JTextField(5);
xField.addActionListener(new TempListener());
yField = new JTextField(5);
yField.addActionListener(new TempListener());
diameterField = new JTextField(5);
diameterField.addActionListener(new TempListener());
Redraw = new JButton("Redraw!");
Redraw.addActionListener(new ButtonListener());
add(xLabel);
add(xField);
add(yLabel);
add(yField);
add(rLabel);
add(diameterField);
add(Redraw);
setPreferredSize(new Dimension(500, 500));
setBackground(Color.white);
}
private class ButtonListener implements ActionListener{
public void actionPerformed (ActionEvent event) {
//Update page
myCircle.draw(g);
//repaint panel
repaint();
}
private class TempListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
int x, y, newbase, newhei;
String text = xField.getText();
String text2 = yField.getText();
x = Integer.parseInt (text);
y = Integer.parseInt (text2);
myCircle.draw(g);
repaint();
}
}
}
}
Hi guys I'm tring to make java application that draw a circle and redraw it with the new values that are in JTextField. I wrote three class for it. One of them is contain accessor, mutators, constructor. one of the class has the main method of course and a one of the class is above. But TempListener not working. Can you help me?
You should get the Graphics field, g, out of your program. Instead use the local Graphics variable, the one you call page inside of your paintComponent method, but don't use it anywhere else.
Suggestions:
Have your ActionListener make changes to the state of the myCircle object, your code does not do this.
Then have it call repaint().
Get this, myCircle.draw(g); out of your ActionListener as it doesn't belong there.
Read the Swing graphics tutorials: Lesson: Performing Custom Painting
Related
I am working on a simple object drawing program using Swing in Java.
My program simply should draw shapes according to buttons when clicked, and move any shapes with the mouse. I have four buttons which draw rectangle, circle and square on screen. So far I did managed to draw to shapes when you click on buttons. but i want to move the shapes on screen which it did not work out.
The problem is this: When I click on circle shape to drag it around with mouse, it clears all the screen and noting is on the screen.
And, is there a way to clean all the screen when I click on clear button?
Thank you?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PaintProject extends JComponent implements ActionListener,
MouseMotionListener {
private int CircleX=0;
private int CircleY=0;
private int RectX=100;
private int RectY=100;
private int SquareX=300;
private int SquareY=200;
public static void main(String[] args) {
JFrame frame = new JFrame("NEW PAINT PROGRAME!");
JButton CircleButton = new JButton("Circle");
CircleButton.setActionCommand("Circle");
JButton RectangleButton = new JButton("Rectangle");
RectangleButton.setActionCommand("Rectangle");
JButton SquareButton = new JButton("Square");
SquareButton.setActionCommand("Square");
PaintProject paint = new PaintProject();
CircleButton.addActionListener(paint);
RectangleButton.addActionListener(paint);
SquareButton.addActionListener(paint);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(paint);
frame.add(CircleButton);
frame.add(RectangleButton);
frame.add(SquareButton);
frame.addMouseMotionListener(paint);
frame.pack();
frame.setVisible(true);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
private void drawCircle() {
Graphics g = this.getGraphics();
g.setColor(Color.red);
g.fillOval(CircleX, CircleY, 100, 100);
}
private void drawRectangle() {
Graphics g = this.getGraphics();
g.setColor(Color.green);
g.fillRect(RectX, RectY, 100, 300);
}
private void drawSquare() {
Graphics g = this.getGraphics();
g.setColor(Color.blue);
g.fillRect(SquareX, SquareY, 100, 100);
}
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("Circle")) {
drawCircle();
}
else if (command.equals("Rectangle")) {
drawRectangle();
}
else if (command.equals("Square")) {
drawSquare();
}
}
#Override
public void mouseDragged(MouseEvent e) {
CircleX=e.getX();
CircleY=e.getY();
repaint();
}
}
As noted here and here, getGraphics() is not how to perform custom painting in Swing. Instead, override paintComponent() to render the desired content. It looks like you want to drag shapes using the mouse. A basic approach to moving a selected object is shown here; substitute your fillXxx() invocation for the drawString() shown there. For multiple shapes, use a List<Shape>; the clear command then becomes simply List::clear. A complete example is cited here; it features moveable, selectable, resizable, colored nodes connected by edges.
I am new to swing, can anyone help me out with this...
It is not showing my "label" , instead it shows me only components which are in the "panel" class.
One more question, can anyone clarify me about LayoutManagers ?
Can 2 or more LayoutManagers be used in a frame ? like for the frame i will be using FlowLayout and i have a JPanel added to the frame for which i will be using BoxLayout ... is it possible in the first place ??
import javax.swing.*;
import java.awt.event.*;
import java.awt.Graphics;
public class JForm1 extends JFrame
{
public JForm1()
{
init();
}
public static void main(String[] args)
{
JForm1 form = new JForm1();
}
public void init()
{
JFrame frame = new JFrame("My Form 1");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));
JLabel label = new JLabel("Enter your Name : ");
panel MyPanel = new panel();
frame.getContentPane().add(label);
frame.getContentPane().add(MyPanel);
frame.setVisible(true);
}
}
class panel extends JPanel implements ActionListener
{
JButton submitButton;
JTextField text;
panel()
{
this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
}
public void paintComponent(Graphics g)
{
text = new JTextField("Enter Name here");
text.setSize(100,25);
submitButton = new JButton("Submit");
submitButton.setSize(50,90);
submitButton.setBounds(200, 0, 80, 80);
submitButton.addActionListener(this);
this.add(text);
this.add(submitButton);
}
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==submitButton)
{
System.out.println("The Entered Name is : "+text.getText());
}
}
}
What is this ?:
public void paintComponent(Graphics g)
{
text = new JTextField("Enter Name here");
text.setSize(100,25);
submitButton = new JButton("Submit");
submitButton.setSize(50,90);
submitButton.setBounds(200, 0, 80, 80);
submitButton.addActionListener(this);
this.add(text);
this.add(submitButton);
}
This code has nothing to do in paintComponent. paintComponent is about "painting a component", ie, paint a rectangle, draw a line, fill an oval, etc... This is absolutely not the place where to add your components. Instead, call that code in your constructor.
Additionally, if you are using LayoutManager's (which you should), calling setSize/setBounds/setLocation is useless (dimply remove those calls).
A few more things:
If you override paintComponent, make sure to invoke the super-method
Don't extends JFrame if not needed (here it is clearly not needed)
Follow Java naming conventions (class names should start with an UpperCase letter, variables and methods with a lowerCase letter)
All Swing-related code must be called on the EDT. Start your UI within a SwingUtilities.invokeLater() block.
Try by changing layout to FlowLayout for mypanel.
mypanel.setLayout(new FlowLayout());
I have this code and want to repaint my graphic when the Button gets pressed:
public class JDraw extends JFrame {
/**
* Draws a figur in a JFrame.
* The color of it is random and can get changed by a button.
*/
public static JButton okButton = new JButton("change color");
public JDraw(String newTitel) {
super.setTitle(newTitel);
}
//Main method
public static void main(String str[]) {
JDraw window = new JDraw("Graphic");
window.setSize(300, 450);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(okButton, BorderLayout.SOUTH);
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//JDraw.repaint(); <-- problem
}
});
}
#Override
public void paint(final Graphics g) {
super.paint(g);
Random rand = new Random();
int r1 = rand.nextInt(255);
int b1 = rand.nextInt(255);
int g1 = rand.nextInt(255);
g.setColor(new Color(r1, g1, b1));
//head
g.drawOval(100, 50, 100, 100);
g.fillOval(100, 50, 100, 100); // filled
//more drawing stuff.....
}
}
However I have no idea how to do it, because I cant do the repaint in my ActionPerfomed.
Error: non-static method repaint() cannot be referenced from a static context
I hope somebody can help. :)
You need to make the following call in your actionPerformed:
window.repaint();
To be able to reference window from within you actionPerformed, you need to make your window variable final:
final JDraw window = ...;
However, if I can suggest a few improvements:
Don't extend JFrame
Don't override paint(Graphics) of JFrame
Instead create a class that extends JComponent or JPanel and set it as the content pane of the JFrame
Instead of overrding paint(Graphics), rather override paintComponent(Graphics)
Your okButton should not be static. Instead move all your code in a non-static method like initUI() and have a code like new JDraw().initUI();
Wrap the code starting your UI in a SwingUtilities.invokeLater(Runnable) so that your UI is properly initiated from the Event Dispatching Thread.
You can't refer to the class JDraw. You should use an object instead. The object in your case is window. So, use:
window.repaint();
It is like saying: Human, walk to the door. Human is the class. You can't tell Human to do something, you need an instance of Human, like Obama or Santa Claus. In your case: you can't tell JDraw to repaint, but the object of type JDraw, i.e.: window.
I have a poker game where I designed a nice pretty GUI that displays the cards and players. I did it all extending JPanel inside paint() with a lot of g2d.drawImage's and g2d.drawString()'s, with definite x and y locations.
My problem now is that I need to have a couple interactive buttons underneath it.. but whenever I try to add a JButton, it appears top and center. I've used setLocation(x, y) and setLayout(null) and everything I've seen in other replies, but none of them seem to match my need (Or at least I don't have a very well understanding of where to put it)
This is how my code is set up:
pokerserver.java
public class pokerserver extends JFrame {
public pokerserver() {
add(new drawing());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(720, 640);
setLocationRelativeTo(null);
setTitle("Poker HANGOUTS");
setResizable(false);
setVisible(true);
}
public static void main(String args[]) {
new pokerserver();
}
And then in drawing.class
public drawing() {
setFocusable(true);
setBackground(new Color(39,91,46));
setDoubleBuffered(true);
gameCards = new cards();
gameCards.shuffle();
for (int i = 0; i < 10; i++)
seats[i] = -1;
HQ = new HeadQuarters(this);
HQ.start();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
//All my UI code
}
My last attempt was trying to add
JButton button = new JButton("TEST");
add(button);
button.setLocation(10, 500);
at the end of public drawing(). I Keep seeing things on layout management, but it's not helping me -- mainly because I'm not sure how to implement it
Here's a screenshot to help visualize what I'm talking about->
http://i.imgur.com/ttvif.png
Trying to get the button underneath. Unless there's a way to add an ActionListener to a drawImage()?
For your main panel use a BorderLayout.
Then to the "CENTER" you can add your game panel with all your custom painting.
Then create a panel and add the buttons to it. Now you can add this panel to the NORTH of the main panel.
In other words you are not restricted to using a single panel.
Also, custom painting should be done in the paintComponent() method of your panel, NOT the paint() method.
I'm not really sure what you are after, but here are two interpretations.
I suspect you want the 1st one 'Buttons over custom painting', but as a user I'd prefer the 2nd, with 'Buttons below custom painting'.
import java.awt.image.*;
import java.awt.*;
import javax.swing.*;
class PaintPanel extends JPanel {
BufferedImage bg;
PaintPanel(LayoutManager2 layout) {
super(layout);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (bg==null) {
bg = new BufferedImage(500,500,BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bg.createGraphics();
GradientPaint gp = new GradientPaint(
0,0,Color.RED,500,500,Color.BLUE);
g2.setPaint(gp);
g2.fillRect(0,0,500,500);
g2.dispose();
}
g.drawImage(bg,0,0,getWidth(),getHeight(),this);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPanel buttons = new JPanel(
new FlowLayout(FlowLayout.CENTER));
buttons.setOpaque(false);
buttons.add(new JButton("Start"));
buttons.add(new JButton("Stop"));
PaintPanel pp = new PaintPanel(new BorderLayout());
pp.setPreferredSize(new Dimension(200,100));
pp.add(buttons, BorderLayout.SOUTH);
JOptionPane.showMessageDialog(null,pp);
JPanel gui = new JPanel(new BorderLayout());
gui.setBackground(Color.ORANGE);
gui.add(pp, BorderLayout.CENTER);
gui.add(buttons, BorderLayout.SOUTH);
JOptionPane.showMessageDialog(null,gui);
}
});
}
}
I'm creating a small game, you click buttons (up, down, left and right) to control a cat (represented by a rectangle) to chase a mouse (represented by another rectangle). Lame I know... anyway I'm using the mvc design pattern and I am having problems calling the repaint method from button listeners in the controller on the panel where the two rectangles are to be 'painted'. They paint successfully the first time but not any further time.
I've implemented the the paintComponent() method in two ways but both didn't work
Create a separate class that extends JPanel and does the paintComponent business, creating a new object of that class in the view and using it to paint the rectangles.
Creating a JPanel and writing the paintComponent stuff in the parenthesis of the new JPanel object.
and I've implemented the code to in the controller to repaint in two ways and both didn't work
Call a method from the view that returns the jpanel that uses the paintComponent method and calling repaint on it.
Creating a jpanel in the controller and assigning the panel from the view to it then calling repaint on that.
The code for the view and controller (which is long, sorry!) is below, it also includes the commented out stuff I couldn't get to work from the two methods to approaching the problem mentioned before...
View
/*
* gameView.java
*/
package game;
import java.awt.;
import java.awt.event.;
import javax.swing.*;
public class gameView extends JFrame{
//components
private JButton up = new JButton("Up");
private JButton down = new JButton("Down");
private JButton left = new JButton("Left");
private JButton right = new JButton("Right");
//panels
private JPanel content = new JPanel();
//boardPanel leftPanel = new boardPanel();
private Stroke drawingStroke = new BasicStroke(1);
private JPanel leftPanel = new JPanel(){
#Override
protected void paintComponent(Graphics g) {
super.paintComponents(g);
myPaint(g);
}
};
private JPanel rightPanel = new JPanel();
//model
private gameModel model;
//mouse and cat
private Rectangle cat;
private Rectangle mouse;
public void myPaint(Graphics g){
Graphics2D g1 = (Graphics2D)g;
Graphics2D g2 = (Graphics2D)g;
g1.setStroke(drawingStroke);
g1.draw(cat);
g1.setPaint(Color.yellow);
g1.fill(cat);
g2.setStroke(drawingStroke);
g2.draw(mouse);
g2.setPaint(Color.red);
g2.fill(mouse);
}
//constructor
public gameView(gameModel _model){
model = _model;
//cat and mouse
cat = new Rectangle(_model.getCatX(), _model.getCatY(), 10, 10);
mouse = new Rectangle(_model.getMouseX(), _model.getMouseY(), 10, 10);
//layout
content.setSize(500, 400);
content.setLayout(new GridLayout(0,2));
leftPanel.setSize(200, 200);
leftPanel.setBackground(Color.blue);
rightPanel.setSize(100, 400);
rightPanel.setLayout(new FlowLayout());
rightPanel.add(new JLabel("Controls"));
rightPanel.add(up);
rightPanel.add(down);
rightPanel.add(left);
rightPanel.add(right);
content.add(leftPanel);
content.add(rightPanel);
this.setSize(500, 400);
this.setContentPane(content);
this.setTitle("Cat & Mouse Game");
}
//returns the leftPanel to repaint in the controller
public JPanel getLeft(){
return leftPanel;
}
//listeners for buttons
public void addUpListener(ActionListener moveUp){
up.addActionListener(moveUp);
}
public void addDownListener(ActionListener moveDown){
down.addActionListener(moveDown);
}
public void addLeftListener(ActionListener moveLeft){
left.addActionListener(moveLeft);
}
public void addRightListener(ActionListener moveRight){
right.addActionListener(moveRight);
}
public void addCloseListener(WindowListener close){
this.addWindowListener(close);
}
//
public Rectangle getCat(){
return cat;
}
public Rectangle getMouse(){
return mouse;
}
//left side board panel
/*class boardPanel extends JPanel{
Stroke drawingStroke = new BasicStroke(1);
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g1 = (Graphics2D)g;
g1.setStroke(drawingStroke);
g1.draw(cat);
g1.setPaint(Color.yellow);
g1.fill(cat);
Graphics2D g2 = (Graphics2D)g;
g2.setStroke(drawingStroke);
g2.draw(mouse);
g2.setPaint(Color.red);
g2.fill(mouse);
}
}
public JPanel getLeft(){
return leftPanel;
}*/
}
Controller
/*
* gameController.java
*/
package game;
import java.awt.event.;
import javax.swing.;
public class gameController {
private gameModel model;
private gameView view;
private JPanel lp = new JPanel();
public gameController(gameModel _model, gameView _view){
model = _model;
view = _view;
lp=_view.getLeft();
//listeners
view.addUpListener(new UpListener());
view.addDownListener(new DownListener());
view.addLeftListener(new LeftListener());
view.addRightListener(new RightListener());
view.addCloseListener(
new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
//DOWN
class DownListener implements ActionListener{
public void actionPerformed(ActionEvent e){
model.setCatY((model.getCatY()+10));
//do a random move for the mouse
//model.randomMove();
//view.getLeft().repaint();
lp.repaint();
System.out.println("x="+model.getCatX()+"y="+model.getCatY());
}
}
//LEFT
class LeftListener implements ActionListener{
public void actionPerformed(ActionEvent e){
model.setCatY((model.getCatY()-10));
//do a random move for the mouse
//model.randomMove();
//view.getLeft().repaint();
lp.repaint();
System.out.println("x="+model.getCatX()+"y="+model.getCatY());
}
}
//RIGHT
class RightListener implements ActionListener{
public void actionPerformed(ActionEvent e){
model.setCatY((model.getCatY()+10));
//do a random move for the mouse
//model.randomMove();
//view.getLeft().repaint();
lp.repaint();
System.out.println("x="+model.getCatX()+"y="+model.getCatY());
}
}
}
Looks like your button listeners update the model, but nothing actually updates the coordinates of the cat and mouse rectangles. They get their initial bounds from the model, but then are never updated.
The view should probably listen to the model to sync the cat and mouse's locations to the actual Rectangle objects.