The graphics should repaint with a new color after a mouse click, but they don´t.
I´ve already implemented the MouseListener in the component and in the frame, but in both versions it did´nt work.
The Frame and MouseListener:
public class frame extends Frame
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
String string = new String("1 2 3 4 5 6 7");
final int FRAME_WIDTH = 527;
final int FRAME_HEIGHT = 77;
frame.setAlwaysOnTop(true);
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("Praxis");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
// JFrame zentriert positionieren; selbst berechnet:
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
frame.setLocation((int) ((d.width)-700), (int) (0));
Font font = new Font("Jokerman", Font.BOLD, 35);
JLabel textLabel = new JLabel(string);
textLabel.setFont(font);
test component = new test();
frame.add(component);
MouseListener listen = new MouseListener()
{
public void mouseClicked(MouseEvent e) {
GlobalVar obj = new GlobalVar();
obj.fillColor1 = obj.farben[1];
component.repaint();
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
};
component.addMouseListener(listen);
frame.setVisible(true);
}
}
The File where they get the Color from:
public class GlobalVar{
public static final Color[] farben = new Color[4];{
farben[0] = Color.LIGHT_GRAY;
farben[1] = Color.RED;
farben[2] = Color.GREEN;
farben[3] = Color.PINK;
}
Color fillColor1 = farben[0];
Color fillColor2 = farben[0];
Color fillColor3 = farben[0];
Color fillColor4 = farben[0];
Color fillColor5 = farben[0];
Color fillColor6 = farben[0];
Color fillColor7 = farben[0];
}
The Component which draws the graphics:
public class test extends JComponent
{
GlobalVar obj = new GlobalVar();
#Override
public void paintComponent(Graphics g)
{
if(g instanceof Graphics2D) {
// Recover Graphics2D
Graphics2D g2 = (Graphics2D) g;
// Construct a rectangle and draw it
Rectangle box1 = new Rectangle(2, 2, 71, 71);
g2.setColor(Color.BLACK);
g2.draw(box1);
g2.setColor(obj.fillColor1);
g2.fill(box1);
Rectangle box2 = new Rectangle(77, 2, 71, 71);
g2.setColor(Color.BLACK);
g2.draw(box2);
g2.setColor(obj.fillColor2);
g2.fill(box2);
Rectangle box3 = new Rectangle(152, 2, 71, 71);
g2.setColor(Color.BLACK);
g2.draw(box3);
g2.setColor(obj.fillColor3);
g2.fill(box3);
Rectangle box4 = new Rectangle(227, 2, 71, 71);
g2.setColor(Color.BLACK);
g2.draw(box4);
g2.setColor(obj.fillColor4);
g2.fill(box4);
Rectangle box5 = new Rectangle(302, 2, 71, 71);
g2.setColor(Color.BLACK);
g2.draw(box5);
g2.setColor(obj.fillColor5);
g2.fill(box5);
Rectangle box6 = new Rectangle(377, 2, 71, 71);
g2.setColor(Color.BLACK);
g2.draw(box6);
g2.setColor(obj.fillColor6);
g2.fill(box6);
Rectangle box7 = new Rectangle(452, 2, 71, 71);
g2.setColor(Color.BLACK);
g2.draw(box7);
g2.setColor(obj.fillColor7);
g2.fill(box7);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
Font f = new Font("Dialog", Font.PLAIN, 30);
g2.setFont(f);
g2.setColor(Color.BLACK);
g2.drawString("1", 30, 48);
g2.drawString("2", 105, 48);
g2.drawString("3", 180, 48);
g2.drawString("4", 255, 48);
g2.drawString("5", 330, 48);
g2.drawString("6", 405, 48);
g2.drawString("7", 480, 48);
}
}
private Color fillColor1;
private Color fillColor2;
private Color fillColor3;
private Color fillColor4;
private Color fillColor5;
private Color fillColor6;
private Color fillColor7;
}
As I said, I expected the graphics to repaint with the first square to be filled with the color red, but the actual result is, that nothing happens when I click on the frame.
Instead of having the test class extending JComponent, I would make it into a JPanel and then put the JPanel on top of the JFrame.
Then I would remove the mouselistener from the JFrame and add it onto the JPanel, by doing this the only command needed to repaint is repaint();.
I believe that this way is more simple and more organized than what you are currently doing.
This should do the trick (note: I made this in netbeans, that is why there is some autogenerated code.):
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
public class Test extends javax.swing.JPanel {
/**
* Creates new form Test
*/
public Test() {
initComponents();
}
GlobalVar obj = new GlobalVar();
#Override
public void paintComponent(Graphics g)
{
if(g instanceof Graphics2D) {
// Recover Graphics2D
Graphics2D g2 = (Graphics2D) g;
// Construct a rectangle and draw it
Rectangle box1 = new Rectangle(2, 2, 71, 71);
g2.setColor(Color.BLACK);
g2.draw(box1);
g2.setColor(obj.fillColor1);
g2.fill(box1);
Rectangle box2 = new Rectangle(77, 2, 71, 71);
g2.setColor(Color.BLACK);
g2.draw(box2);
g2.setColor(obj.fillColor2);
g2.fill(box2);
Rectangle box3 = new Rectangle(152, 2, 71, 71);
g2.setColor(Color.BLACK);
g2.draw(box3);
g2.setColor(obj.fillColor3);
g2.fill(box3);
Rectangle box4 = new Rectangle(227, 2, 71, 71);
g2.setColor(Color.BLACK);
g2.draw(box4);
g2.setColor(obj.fillColor4);
g2.fill(box4);
Rectangle box5 = new Rectangle(302, 2, 71, 71);
g2.setColor(Color.BLACK);
g2.draw(box5);
g2.setColor(obj.fillColor5);
g2.fill(box5);
Rectangle box6 = new Rectangle(377, 2, 71, 71);
g2.setColor(Color.BLACK);
g2.draw(box6);
g2.setColor(obj.fillColor6);
g2.fill(box6);
Rectangle box7 = new Rectangle(452, 2, 71, 71);
g2.setColor(Color.BLACK);
g2.draw(box7);
g2.setColor(obj.fillColor7);
g2.fill(box7);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
Font f = new Font("Dialog", Font.PLAIN, 30);
g2.setFont(f);
g2.setColor(Color.BLACK);
g2.drawString("1", 30, 48);
g2.drawString("2", 105, 48);
g2.drawString("3", 180, 48);
g2.drawString("4", 255, 48);
g2.drawString("5", 330, 48);
g2.drawString("6", 405, 48);
g2.drawString("7", 480, 48);
}
}
private Color fillColor1;
private Color fillColor2;
private Color fillColor3;
private Color fillColor4;
private Color fillColor5;
private Color fillColor6;
private Color fillColor7;
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
formMouseClicked(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>
private void formMouseClicked(java.awt.event.MouseEvent evt) {
GlobalVar obj = new GlobalVar();
obj.fillColor1 = obj.farben[1];
repaint();
// TODO add your handling code here:
}
// Variables declaration - do not modify
// End of variables declaration
}
Related
So, if I try to move the shape, it actually moves, but there is no motion animation. In order for the moved shape to be drawn, the application window must be minimized or maximized.
Here is the PentaminoShape class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
public class PentominoShape extends JFrame implements MouseListener, MouseMotionListener {
JPanel shapePane;
Container contentPane;
private Polygon currPolygon;
private int x, y;
ArrayList<Polygon> polygons = new ArrayList<Polygon>();
JFrame frame;
public PentominoShape(JFrame frame){
this.frame = frame;
initShape();
}
private void initShape() {
Polygon fig1 = new Polygon(new int[]{10, 50, 50, 10}, new int[]{10, 10, 200, 200}, 4);
Polygon fig2 = new Polygon(new int[]{130, 210, 210, 170, 170, 130, 130, 90, 90, 130}, new int[]{80, 80, 120, 120, 200, 200, 160, 160, 120, 120}, 10);
Polygon fig3 = new Polygon(new int[]{290, 330, 330, 250, 250, 290}, new int[]{50, 50, 200, 200, 160, 160}, 6);
Polygon fig4 = new Polygon(new int[]{10, 90, 90, 50, 50, 10}, new int[]{280, 280, 400, 400, 360, 360}, 6);
Polygon fig5 = new Polygon(new int[]{170, 210, 210, 170, 170, 130, 130, 170}, new int[]{240, 240, 360, 360, 400, 400, 320, 320}, 8);
Polygon fig6 = new Polygon(new int[]{250, 370, 370, 330, 330, 290, 290, 250}, new int[]{280, 280, 320, 320, 400, 400, 320, 320}, 8);
Polygon fig7 = new Polygon(new int[]{10, 50, 50, 90, 90, 130, 130, 10}, new int[]{480, 480, 520, 520, 480, 480, 560, 560}, 8);
Polygon fig8 = new Polygon(new int[]{170, 250, 250, 290, 290, 170}, new int[]{520, 520, 440, 440, 560, 560}, 6);
Polygon fig9 = new Polygon(new int[]{330, 370, 370, 410, 410, 450, 450, 410, 410, 330}, new int[]{520, 520, 480, 480, 440, 440, 520, 520, 560, 560}, 10);
Polygon fig10 = new Polygon(new int[]{10, 50, 50, 90, 90, 130, 130, 90, 90, 50, 50, 10}, new int[]{680, 680, 640, 640, 680, 680, 720, 720, 760, 760, 720, 720}, 12);
Polygon fig11 = new Polygon(new int[]{170, 210, 210, 250, 250, 210, 210, 170}, new int[]{640, 640, 600, 600, 760, 760, 680, 680}, 8);
Polygon fig12 = new Polygon(new int[]{330, 410, 410, 370, 370, 290, 290, 330}, new int[]{640, 640, 680, 680, 760, 760, 720, 720}, 8);
polygons.add(fig1);
polygons.add(fig2);
polygons.add(fig3);
polygons.add(fig4);
polygons.add(fig5);
polygons.add(fig6);
polygons.add(fig7);
polygons.add(fig8);
polygons.add(fig9);
polygons.add(fig10);
polygons.add(fig11);
polygons.add(fig12);
Color[] c = new Color[12];
c[0] = new Color(25, 165, 25);
c[1] = new Color(255, 165, 25);
c[2] = new Color(255, 50, 50);
c[3] = new Color(150, 45, 90);
c[4] = new Color(25, 165, 150);
c[5] = new Color(25, 165, 255);
c[6] = new Color(255, 40, 190);
c[7] = new Color(180, 90, 60);
c[8] = new Color(90, 80, 70);
c[9] = new Color(70, 80, 90);
c[10] = new Color(150, 30, 20);
c[11] = new Color(80, 80, 80);
shapePane = new JPanel(){
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(c[0]); g2.fill(fig1);
g2.setColor(c[1]); g2.fill(fig2);
g2.setColor(c[2]); g2.fill(fig3);
g2.setColor(c[3]); g2.fill(fig4);
g2.setColor(c[4]); g2.fill(fig5);
g2.setColor(c[5]); g2.fill(fig6);
g2.setColor(c[6]); g2.fill(fig7);
g2.setColor(c[7]); g2.fill(fig8);
g2.setColor(c[8]); g2.fill(fig9);
g2.setColor(c[9]); g2.fill(fig10);
g2.setColor(c[10]); g2.fill(fig11);
g2.setColor(c[11]); g2.fill(fig12);
}
};
/*contentPane = this.getContentPane();
contentPane.add(shapePane);
this.pack();*/
frame.add(shapePane);
shapePane.addMouseListener(this);
shapePane.addMouseMotionListener(this);
/*shapePane.addMouseListener(this);
shapePane.addMouseMotionListener(this);*/
}
public void mousePressed(MouseEvent e) {
for(Polygon polygon: polygons) {
if (polygon.contains(e.getPoint())) {
System.out.println("Pressed");
currPolygon = polygon;
x = e.getX();
y = e.getY();
}
}
}
public void mouseDragged(MouseEvent e) {
try {
if (currPolygon.contains(x, y)) {
System.out.println("Dragged");
int dx = e.getX() - x;
int dy = e.getY() - y;
currPolygon.translate(dx, dy);
x += dx;
y += dy;
repaint();
}
}catch (NullPointerException ex){
}
}
public void mouseReleased(MouseEvent e){
currPolygon = null;
}
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseMoved(MouseEvent e){}
}
And the main Pentamino class:
import javax.swing.*;
public class Pentomino extends JFrame {
JFrame frame;
PentominoShape shape;
PentominoPanel panel;
public Pentomino(){
initUI();
}
private void initUI(){
frame = new JFrame("Пентамино");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(1500, 900);
setResizable(false);
shape = new PentominoShape(frame);
panel = new PentominoPanel(frame);
/*frame.add(shape);
frame.add(panel);*/
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
Pentomino game = new Pentomino();
}
}
I'm new to Java and I don't understand how to solve this problem. Tried searching the internet for a similar problem but couldn't find anything.
Your bug is here:
public void mouseDragged(MouseEvent e) {
try {
if (currPolygon.contains(x, y)) {
System.out.println("Dragged");
int dx = e.getX() - x;
int dy = e.getY() - y;
currPolygon.translate(dx, dy);
x += dx;
y += dy;
repaint(); // ***** here ****
}
}catch (NullPointerException ex){
}
}
You're calling repaint() on the enclosing class, a JFrame, one that is never displayed, and this will have not have the effect desired.
In fact, ask yourself, why this...
public class PentominoShape extends JFrame // ...
Why is PentominoShape extending JFrame at all, when it isn't behaving as a JFrame, when it shouldn't be behaving as a JFrame?
Instead, call repaint on the JPanel that holds the shapes, the shapePane JPanel, and yes, get rid of catching the NullPointerException. That should never be in your code:
public void mouseDragged(MouseEvent e) {
if (currPolygon == null) {
return;
}
if (currPolygon.contains(x, y)) {
System.out.println("Dragged");
int dx = e.getX() - x;
int dy = e.getY() - y;
currPolygon.translate(dx, dy);
x += dx;
y += dy;
shapePane.repaint(); // now we're repainting the correct JPanel!
}
}
Side note: I'd clean things up a bit including
Not having any class extend JFrame if possible
Create my own polygon type of class:
public class PentominoShape2 {
private Polygon polygon;
private Color color;
public PentominoShape2(Polygon polygon, Color color) {
this.polygon = polygon;
this.color = color;
}
public void draw(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(color);
g2.fill(polygon);
}
public Polygon getPolygon() {
return polygon;
}
public Color getColor() {
return color;
}
public boolean contains(Point p) {
return polygon.contains(p);
}
}
and then in the drawing JPanel
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (PentominoShape2 poly : polys) {
poly.draw(g);
}
}
same for the mouse listener
I changed a program (see below) I nabbed and have managed to get it to do some of what I want. I need a number of rows/bands/stripes of 3 to blink in sequence. If you could imagine three sets of three vertical bars/bands and each bar numbered 1-3. I want to get each band/bar numbered 1 of each group to blink. So all bands numbered 1 blinks for a finite time, then bands numbered 2, then 3 then repeat. So when looking at it it looks like vertical stripes blinking 1,2,3,1,2,3 etc.
What's set out below and what I have described as boxes below refers to the bands I am talking about
class BelishN {
private Timer timer;
public class Drawing extends JPanel {
private int x = 125;// Not required - it was for the ball!
private int y = 80;
private boolean changeColors = false;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
//creating the shapes
Rectangle box1 = new Rectangle(1, 1, 10, 770);
//Rectangle box2 = new Rectangle(165, 225, 20, 45);
Rectangle box3 = new Rectangle(10, 1, 10, 770);
//Rectangle box4 = new Rectangle(165, 315, 20, 45);
Rectangle box5 = new Rectangle(20, 1, 10, 770);
// Rectangle box6 = new Rectangle(165, 405, 20, 45);
//drawing the shapes
//Ellipse2D.Double ball = new Ellipse2D.Double(x, y, 100, 100);
//g2.draw(ball);
g2.draw(box1);
//g2.draw(box2);
//g2.draw(box3);
//g2.draw(box4);
//g2.draw(box5);
//g2.draw(box6);
//coloring the shapes
g2.setColor(Color.BLACK);
g2.fill(box1);
g2.fill(box3);
g2.fill(box5);
g2.setColor(Color.ORANGE);
//g2.fill(ball);
changeColors = !changeColors;
if (changeColors) {
g2.setColor(Color.white);
//g2.fill(new Ellipse2D.Double(x, y, 100, 100));
g2.fill(box1 = new Rectangle(1, 1, 10, 770));//3 vertical bands are flashing together
g2.fill(box3 = new Rectangle(10, 1, 10, 770));
g2.fill(box5 = new Rectangle(20, 1, 10, 770));
}
}
public void changeColors() {
changeColors = true;
repaint();
}
}
public BelishN() {
//Creation of frame
JFrame frame = new JFrame();
frame.setSize(800, 770); //Screen size
frame.setTitle("Belisha Beacon");
frame.setLayout(new BorderLayout(0, 0));
final Drawing shapes = new Drawing();
timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
shapes.repaint();
}
});
JButton jbtFlash = new JButton("Flash");
jbtFlash.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
}
});
final JButton jbtSteady = new JButton("Steady");
jbtSteady.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
timer.stop();
}
});
//Positioning
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout(1, 2, 0, 0));
controlPanel.add(jbtFlash);
controlPanel.add(jbtSteady);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.add(shapes);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// in last line here, start the timer:
timer.start();
}
public static void main(String[] args) {
new BelishN();
}
}
i need some help with this code.
I already have the functions of paint the objects and clear the objects from the window but how i can make that when i make a resize or when i minimize the windows the objects doesn't disappear?
This is the code i have at the moment:
public class miClass implements ActionListener{
JFrame ventana;
JPanel panel;
JButton p,c;
Graphics g;
Image img;
Font font1,font2,font3;
public miClass(){
ventana = new JFrame("Aplicacion.");
p = new JButton("P");
c = new JButton("C");
panel = new JPanel();
ventana.setLayout(null);
ventana.setBounds(100,100,600,600);
ventana.getContentPane().add(panel);
ventana.add(p);
p.addActionListener(this);
c.addActionListener(this);
p.setBounds(20,20,120,45);
ventana.add(c);
c.setBounds(200,20,120,45);
ventana.setFocusable(true);
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ventana.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
g = ventana.getGraphics();
Toolkit tool = Toolkit.getDefaultToolkit();
img = tool.getImage("prueba.png");
g.drawImage(img,0,100,null);
font1 = new Font("Helvetica",Font.PLAIN,22);
g.setFont(font1);
g.drawString("Hola", 100, 300);
font2 = new Font("TimesRoman",Font.BOLD,20);
g.setFont(font2);
g.drawString("Mundo", 100, 340);
font3 = new Font("Courier",Font.BOLD+Font.ITALIC,25);
g.setFont(font3);
g.drawString("WASAAAA!", 100, 400);
g.setColor(Color.green);
g.drawOval(300, 200, 150, 100);
g.setColor(Color.red);
g.drawArc(200, 400, 250, 64, 135, 46);
g.setColor(Color.blue);
g.drawLine(400, 200, 150, 100);
g.setColor(Color.magenta);
g.drawRect(300, 250, 160, 50);
g.setColor(Color.cyan);
g.fillRect(100,400,20,240);
g.setColor(Color.lightGray);
g.fillOval(100,340,14,30);
if(e.getSource() == c){ //Clean all objects on the window//
g.clearRect(0,100,900,800);
}
}
public static void main(String args[]){
miClass GUI = new miClass();
}
}
Your frame is reset to its initial state when it is resized, and your code only redraws it when a button is clicked, not when it is resized. The paintComponent method on any subclass of Component is called after the parent frame is resized, so you can fix this issue by overriding that method.
package SO;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class miClass implements ActionListener {
JFrame ventana;
JPanel panel;
JButton p, c;
Graphics g;
Image img;
Font font1, font2, font3;
public miClass() {
ventana = new JFrame("Aplicacion.");
p = new JButton("P");
c = new JButton("C");
panel = new JPanel() {
#Override
public void paintComponent(Graphics g) {
// your stuff
font1 = new Font("Helvetica", Font.PLAIN, 22);
g.setFont(font1);
g.drawString("THIS GETS REDRAWN", 100, 300);
}
};
panel.setSize(400, 400);
ventana.setLayout(null);
ventana.setBounds(100, 100, 600, 600);
ventana.getContentPane().add(panel);
ventana.add(p);
p.addActionListener(this);
c.addActionListener(this);
p.setBounds(20, 20, 120, 45);
ventana.add(c);
c.setBounds(200, 20, 120, 45);
ventana.setFocusable(true);
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ventana.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
g = panel.getGraphics();
Toolkit tool = Toolkit.getDefaultToolkit();
img = tool.getImage("prueba.png");
g.drawImage(img, 0, 100, null);
font1 = new Font("Helvetica", Font.PLAIN, 22);
g.setFont(font1);
g.drawString("Hola", 100, 300);
font2 = new Font("TimesRoman", Font.BOLD, 20);
g.setFont(font2);
g.drawString("Mundo", 100, 340);
font3 = new Font("Courier", Font.BOLD + Font.ITALIC, 25);
g.setFont(font3);
g.drawString("WASAAAA!", 100, 400);
g.setColor(Color.green);
g.drawOval(300, 200, 150, 100);
g.setColor(Color.red);
g.drawArc(200, 400, 250, 64, 135, 46);
g.setColor(Color.blue);
g.drawLine(400, 200, 150, 100);
g.setColor(Color.magenta);
g.drawRect(300, 250, 160, 50);
g.setColor(Color.cyan);
g.fillRect(100, 400, 20, 240);
g.setColor(Color.lightGray);
g.fillOval(100, 340, 14, 30);
if (e.getSource() == c) { // Clean all objects on the window//
g.clearRect(0, 100, 900, 800);
}
}
public static void main(String args[]) {
miClass GUI = new miClass();
}
}
I am making a GUI that has Graphics2D objects drawn on a JPanel within a JFrame. When I resize the window the Graphics2D objects reduce into a tiny rectangle. How can I set the drawing to resize with the JFrame when the user resizes the window?
I have tried using gridlayout, flowlayout, borderlayout, and settled on gridbaglayout. This helps with the resizing of btnPanel and the JButton but not for the Graphics2D objects.
Here is my self contained example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class DrawPanelMain extends JPanel {
/*
* Variables used to set the value of preferred height and width
*/
public static final double version = 0.0;
JPanel btnPanel = new JPanel();
JPanel switchPanel = new JPanel();
DrawEllipses drawEllipses = new DrawEllipses(POINT_LIST);
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
initializePointList();
createAndShowGui();
}
});
}
public static java.util.List<Point> POINT_LIST = new ArrayList<>();
/*
* This loop will initialize POINT_LIST with the set of points for drawing the ellipses.
* The for each loop initializes points for the top row and the second for loop draws the
* right triangle.
*/
public static void initializePointList() {
int ellipsePointsYCoordinate[] = {140, 200, 260, 320, 380, 440, 500, 560, 620};
int ellipsePointsXCoordinate[] = {140, 200, 260, 320, 380, 440, 500, 560, 620, 680};
int xx = 80;
for (int aXt : ellipsePointsXCoordinate) {
POINT_LIST.add(new Point(aXt, xx));
}
for (int i = 0; i < ellipsePointsYCoordinate.length; i++) {
for (int j = i; j < ellipsePointsYCoordinate.length; j++) {
POINT_LIST.add(new Point(ellipsePointsXCoordinate[i], ellipsePointsYCoordinate[j]));
}
}
}
public DrawPanelMain() {
switchPanel.setBorder(BorderFactory.createLoweredSoftBevelBorder());
switchPanel.setBackground(Color.DARK_GRAY);
switchPanel.add(drawEllipses);
switchPanel.revalidate();
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// first column
c.gridx = 0;
add(switchPanel, c);
// second column
c.gridx = 1;
add(switchPanel, c);
// first row
c.gridy = 0;
// second row
c. gridy = 1;
add(btnPanel, c);
btnPanel.add(new JButton(new AddSwitchAction("Add Switch Panel")));
}
public static void createAndShowGui() {
JFrame frame = new JFrame("RF Connection Panel " + version);
frame.setLayout(new BorderLayout());
frame.add(new DrawPanelMain());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(false);
//frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
/*
* AddSwitchAction will add a new pane to the tabbedPane when the add switch button is clicked
*/
private class AddSwitchAction extends AbstractAction {
public AddSwitchAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
String title = "Switch ";
DrawEllipses tabComponent = new DrawEllipses(POINT_LIST);
switchPanel.add(title, tabComponent);
}
}
}
#SuppressWarnings("serial")
class DrawEllipses extends JPanel {
private final int PREF_W = 750; //Window width
private final int PREF_H = 750; //Window height
private final int OVAL_WIDTH = 30;
private static final Color INACTIVE_COLOR = Color.RED;
private static final Color ACTIVE_COLOR = Color.green;
private java.util.List<Point> points;
private java.util.List<Ellipse2D> ellipses = new ArrayList<>();
private Map<Ellipse2D, Color> ellipseColorMap = new HashMap<>();
/*
* This method is used to populate "ellipses" with the initialized ellipse2D dimensions
*/
public DrawEllipses(java.util.List<Point> points) {
this.points = points;
for (Point p : points) {
int x = p.x - OVAL_WIDTH / 2;
int y = p.y - OVAL_WIDTH / 2;
int w = OVAL_WIDTH;
int h = OVAL_WIDTH;
Ellipse2D ellipse = new Ellipse2D.Double(x, y, w, h);
ellipses.add(ellipse);
ellipseColorMap.put(ellipse, INACTIVE_COLOR);
}
MyMouseAdapter mListener = new MyMouseAdapter();
addMouseListener(mListener);
addMouseMotionListener(mListener);
}
/*
* paintComponent is used to paint the ellipses
*/
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for (Ellipse2D ellipse : ellipses) {
g2.setColor(ellipseColorMap.get(ellipse));
g2.fill(ellipse);
g2.setColor(Color.BLACK);
g2.setStroke(new BasicStroke(2));
g2.draw(ellipse);
}
/*
* Set the font characteristics, color, and draw the row labels.
*/
g.setFont(new Font("TimesRoman", Font.BOLD, 18));
g.setColor(Color.BLACK);
//Along the top row
g.drawString("External Port", 10, 50);
g.drawString("1", 135, 50);
g.drawString("2", 195, 50);
g.drawString("3", 255, 50);
g.drawString("4", 315, 50);
g.drawString("5", 375, 50);
g.drawString("6", 435, 50);
g.drawString("7", 495, 50);
g.drawString("8", 555, 50);
g.drawString("9", 615, 50);
g.drawString("10", 672, 50);
//Along the Y-axis
g.drawString("Radio 2", 40, 145);
g.drawString("3", 90, 205);
g.drawString("4", 90, 265);
g.drawString("5", 90, 325);
g.drawString("6", 90, 385);
g.drawString("7", 90, 445);
g.drawString("8", 90, 505);
g.drawString("9", 90, 565);
g.drawString("10", 90, 625);
//Along the X-Axis
g.drawString("1", 135, 670);
g.drawString("2", 195, 670);
g.drawString("3", 255, 670);
g.drawString("4", 315, 670);
g.drawString("5", 375, 670);
g.drawString("6", 435, 670);
g.drawString("7", 495, 670);
g.drawString("8", 555, 670);
g.drawString("9", 615, 670);
//Draws a 3DRect around the top row of ellipse2D objects
g2.setColor(Color.lightGray);
g2.draw3DRect(120, 60, 580, 40, true);
g2.draw3DRect(121, 61, 578, 38, true);
g2.draw3DRect(122, 62, 576, 36, true);
}
/*
* MouseAdapter is extended for mousePressed Event that detects if the x, y coordinates
* of a drawn ellipse are clicked. If the color is INACTIVE it is changed to ACTIVE and
* vice versa.
*/
private class MyMouseAdapter extends MouseAdapter {
#Override
/*
* When mousePressed event occurs, the color is toggled between ACTIVE and INACTIVE
*/
public void mousePressed(MouseEvent e) {
Color c;
for (Ellipse2D ellipse : ellipses) {
if (ellipse.contains(e.getPoint())) {
c = (ellipseColorMap.get(ellipse) == INACTIVE_COLOR) ? ACTIVE_COLOR : INACTIVE_COLOR;
ellipseColorMap.put(ellipse, c);
}
}
repaint();
}
}
/*
* This method will set the dimensions of the JFrame equal to the preferred H x W
*/
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
/*
* Used for button click action to change all ellipses to ACTIVE_COLOR
*/
public void activateAll(){
for (Ellipse2D ellipse : ellipses){
ellipseColorMap.put(ellipse, ACTIVE_COLOR);
}
repaint();
}
/*
* Used for button click action to change all ellipses to INACTIVE_COLOR
*/
public void deactivateAll(){
for (Ellipse2D ellipse : ellipses){
ellipseColorMap.put(ellipse, INACTIVE_COLOR);
}
repaint();
}
}
This method will set the dimensions of the JFrame equal to the preferred H x W
No it set the preferred size of the panel. The size of the frame will be the preferred size of all the components added to it plus the frame decorations (title bar, borders).
When I resize the window the Graphics2D objects reduce into a tiny rectangle.
The GridBagLayout respects the preferred size of the component. When there is not enough space to display the component it will shrink to its "minimum size".
You probably need to override the getMinimumSize() method to equal the preferred size. Then in this case the component should just be truncated if space is not available.
If you want you actually painting to shrink then you need to build the logic into your painting code so that the painting is done relative to the space available on the panel.
Try adding your 2D object to a JLabel as BufferedImage of ImageIcon. You can do this by:
JLabel label2 = new JLabel(new ImageIcon(//Location of your Image);
Or I think you can also add Graphics2D objects directly creating them inside label bu I'm not sure about that
I have small issue. In main i have such thing:
JTabbedPane tabsPane = new JTabbedPane();
add(tabsPane,BorderLayout.CENTER);
JPanel tab1Panel = new JPanel();
JPanel tab2Panel = new JPanel();
//DrawingWindow drawingWindow= new DrawingWindow();
//add(drawingWindow);
tabsPane.addTab("Animacja", tab1Panel);
tabsPane.addTab("Wykresy", tab2Panel);
JButton test = new JButton("Press");
tab2Panel.add(test);
Drawing Window class
public class DrawingWindow extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
public static Balls balls=new Balls();
public DrawingWindow() {
MakeBall();
}
private void MakeBall()
{
balls=new Balls(10,205,5,10);
}
public void paint(Graphics gg){
super.paint(gg);
Graphics2D g = (Graphics2D) gg;
g.setColor(Color.GRAY);
g.fillRect(0,70,515,410);
g.setColor(Color.WHITE);
g.drawLine(10, 285, 57, 265);
g.drawLine(10, 285, 57, 305);
g.drawLine(515, 285, 458, 265);
g.drawLine(515, 285, 458, 305);
for(int ii=0;ii<Parameters.numberOfCovers;ii++)
{
if(Parameters.whatCovers[ii]==0)
{
g.setColor(Color.YELLOW);
g.fillRect(132+(57*2*ii), 205, 29+2*Parameters.cmCovers[ii], 150 );
}
if(Parameters.whatCovers[ii]==1)
{
g.setColor(Color.GREEN);
g.fillRect(132+(57*2*ii), 205, 29+2*Parameters.cmCovers[ii], 150 );
}
// Ellipse2D.Double shape = new Ellipse2D.Double(balls.getX(), balls.getY(), balls.getVelocity(),balls.getRadius());
// g.fill(shape);
repaint();
}
}
public void funkcja()
{
repaint();
}
}
And my question is after uncommenting the // in Main my JTabbedPanel disappears.
I want paint to draw in JTab.
http://forum.4programmers.net/Java/232952-jtabbedpanel_i_paint?mode=download&id=6326 <-- While it is commented
http://forum.4programmers.net/Java/232952-jtabbedpanel_i_paint?mode=download&id=6327 <-- After uncommenting.
Iam kinda newbie in Java so I would like to get easy answers :P.
Hej,
replace this
JPanel tab1Panel = new JPanel();
with that
JPanel tab1Panel = new DrawingWindow();
up to now, you add the DrawingPanel to another JPanel, but if you want to draw on your Tab, then add create a JPanel, which you'll add to your JTabbedPane with addTab().