خرید بک لینک

Vote count: 0

I'm self-leaing Java, and I'm struggling a bit with Swing. I'm working on an exercise, and I caot figure out how to fix some odd painting behavior. I am placing a custom JPanel object in a null layout. The top-level places the custom object and sets the bounds. The JPanel is responsible for painting itself. The JPanel has no issues painting itself, but when a repaint() command is issued, it creates an identical duplicate object offset by the (x,y) coordinates in the setBounds() method.

Any ideas? Am I just going about this completely wrong?

I was able to isolate the behavior as much as I could. This will draw a single rectangle. When you click inside the rectangle, it creates another offset 24 pixels down and to the right. If you change the setBounds(x,y), it offsets it the amount you enter.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TestOddBehavior extends JPanel {

//----------Main----------//
public static void main(String[] args){
JFrame window = new JFrame("Odd");
TestOddBehavior content = new TestOddBehavior();
window.setContentPane(content);
window.pack();
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation( (screensize.width - window.getWidth())/2,
                    (screensize.height - window.getHeight())/2 );
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setResizable(false);  
window.setVisible(true);
} //end main

//----------Instance Variables----------//
private OddBoard board;

//----------Constructor----------//
public TestOddBehavior(){
setLayout( null );
setPreferredSize( new Dimension( 600, 600 ) );
setBackground(new Color(245,222,179));
board = new OddBoard( 200 );
add( board );
board.setBounds( 24, 24, 300, 300 );
} //end Constructor
} //end TestOddBehavior

This is the JPanel object.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class OddBoard extends JPanel implements MouseListener, MouseMotionListener {

private int rectSize;

public OddBoard( int rectSize ) {
addMouseListener(this);
addMouseMotionListener(this);
this.rectSize = rectSize;
} //end GoBoardGUI constructor

public void paintComponent( Graphics g ){

g.drawRect( 0, 0, rectSize, rectSize );

} //end paintComponent
public void mousePressed(MouseEvent evt) { }
public void mouseReleased(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { 
repaint();
}
public void mouseEntered(MouseEvent evt) { }
public void mouseExited(MouseEvent evt) { }
public void mouseDragged(MouseEvent evt) { }
public void mouseMoved(MouseEvent evt) { }
} //end GoBoardGUI

asked 1 min ago

برچسب: نویسنده: استخدام کار تاريخ: جمعه 31 ارديبهشت 1395 ساعت: 5:01

صفحه بندی