Painting components over images


I've exteneded a JFrame and overridden it's paint() method because I want to draw an image in the background and then display a component on top of it (label, button, etc). But my component is not displaying in the right place. It only displays in the top left corner, even though I've set the location to something else. I don't think I'm painting it right somehow.

Here's a snippet:


JLabel label1 = new JLabel("hello");
label1.setSize(150, 50);
label1.setLocation(200, 200);
...

public void paint(Graphics g)
{
Graphics offScreenGraphics = offScreenImage.getGraphics();

offScreenGraphics.drawImage(myImage, 0, 0, 800, 600, 0, 0, 800, 600, this);

paint(offScreenGraphics);

label1.paint(offScreenGraphics);

g.drawImage(offScreenImage, 0, 0, this);

offScreenGraphics.dispose();
}


Posted On: Tuesday 23rd of October 2012 11:12:16 PM Total Views:  491
View Complete with Replies

RELATED TOPICS OF Swing / AWT / SWT PROGRAMMING LANGUAGE




Repainting /clipping area?

One way would be to get the bounds of the rectangle before the move, move the rectangle, repaint both the original and the new area.
VIEWS ON THIS POST

154

Posted on:

Friday 21st September 2012
View Replies!

Repainting my buttons does not work

there, I'm trying to make a nice vector game. The algorithm is quite easy, you start with a numer you choose between 3 an 5. For example, you choose 3 so the next turn could be 2, 3or 4 (3-1, 3again or 3+1). I'm writing those numbers in an array and update them. My Array looks like this for example: [4|0|0|3|4|5|0|...|0] than I make the next step with 3 for example: [4|0|0|3|0|2|3|4|0|0|...|0] than I make the next step with 4 for example: [4|0|0|3|0|0|0|4|0|0|3|4|5|0|0|...|0] But when I try to get it in an gui, I fail. I make Buttons which are enable when they are not 0 and lable them like the number in the array. Until here, I have no problems. But when I press a butten, the buttons will not change. Here's my Code: Button class import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; public class Button { public static void makeStartButton(int von, final int bis) { // TODO Auto-generated method stub for (int i=von;i
VIEWS ON THIS POST

247

Posted on:

Sunday 30th September 2012
View Replies!

painting nested JComponents

Goal: create a threaded "WaitIndicator" JComponent that itself consists of 12 "LightSegment" JComponents arranged in a circle like on the face of a clock. When triggered, WaitIndicator should sequentially paint a LightSegment its base color and the previous LightSegment set to grey. This code does not yet try the threading or triggering or sequencing, just initializes an instance of WaitIndicator. For the moment I've hardcoded the initial colors of the 12 LightSegments to make debugging easier. Problem: I'm not seeing the 12 LightSegments initialized to their correct colors - all appear black. So I'm obviously doing something wrong. import java.util.*; import java.lang.reflect.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.*; import javax.swing.event.*; public class WaitIndicatorTest extends JFrame { class LightSegment extends JComponent { Ellipse2D circle = new Ellipse2D.Double(); Point2D position; Color color; int dia; int border; boolean active; //constructors public LightSegment(double coord_x, double coord_y, Color color, int radius) { this.circle.setFrame( new Point2D.Double(coord_x, coord_y), new Dimension(12, 12)); this.setPreferredSize( new Dimension( 12, 12)); this.color = color; this.dia = radius; this.border = 1; this.active = true; } //methods public void turnOn(Color color) { this.color = color; this.active = true; repaint(); } public void turnOff() { this.color = Color.GRAY; this.active = false; repaint(); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setColor(this.color); g2.draw(circle); g2.fill(circle); } } public class WaitIndicator extends JComponent { ArrayList segArray = new ArrayList(); int height = 100; int width = 100; Point2D position; Color color; boolean active; //constructors WaitIndicator() { double center_x = 50.0; double center_y = 50.0; this.segArray.add(new LightSegment( center_x+0 , center_y+50, Color.magenta, 10)); this.segArray.add(new LightSegment( center_x+25.0, center_y+43.3, Color.black, 10)); this.segArray.add(new LightSegment( center_x+43.3, center_y+25.0, Color.orange, 10)); this.segArray.add(new LightSegment( center_x+50, center_y+0, Color.red, 10)); this.segArray.add(new LightSegment( center_x+43.3, center_y-25.0, Color.green, 10)); this.segArray.add(new LightSegment( center_x+25.0, center_y-43.3, Color.blue, 10)); this.segArray.add(new LightSegment( center_x+0 , center_y-50, Color.yellow, 10)); this.segArray.add(new LightSegment( center_x-25.0, center_y-43.3, Color.pink, 10)); this.segArray.add(new LightSegment( center_x-43.3, center_y-25.0, Color.white, 10)); this.segArray.add(new LightSegment( center_x-50, center_y+0, Color.cyan, 10)); this.segArray.add(new LightSegment( center_x-43.3, center_y+25.0, Color.gray, 10)); this.segArray.add(new LightSegment( center_x-25.0, center_y+43.3, Color.blue, 10)); this.active = false; } //methods public void turnOn(Color color) { this.color = color; this.active = true; repaint(); } public void turnOff() { this.color = Color.GRAY; this.active = false; repaint(); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; for( int ii = 0 ; ii < 12 ; ii++ ) g2.draw( this.segArray.get(ii).circle); for( int ii = 0 ; ii < 12 ; ii++ ) g2.fill( this.segArray.get(ii).circle); } public void runIt() { for( int ii = 0 ; ii < 120 ; ii++ ) { int jj = ii % 12; this.segArray.get(jj+0).turnOn(Color.blue); this.segArray.get(jj+11).turnOff(); repaint(); } } } private void createAndShowGUI() { JFrame frame1; Container pane1; JPanel panelTGC; final JButton buttonTGCtrigger; final WaitIndicator waitIndicatorTGCtrigger; final JButton buttonCancel; buttonTGCtrigger = new JButton("click me"); waitIndicatorTGCtrigger = new WaitIndicator(); waitIndicatorTGCtrigger.setPreferredSize( new Dimension(200,200)); waitIndicatorTGCtrigger.setBackground(Color.GREEN); buttonCancel = new JButton("Cancel"); buttonTGCtrigger.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e) { waitIndicatorTGCtrigger.runIt(); } }); buttonCancel.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e) { System.exit(0); } }); //Create and set up the window. frame1 = new JFrame( "TinyTest"); frame1.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); // Exit when the window is closed. frame1.setBounds(200,200,900,500); // in pixels pane1 = frame1.getContentPane(); pane1.setLayout( new BoxLayout(pane1, BoxLayout.Y_AXIS)); panelTGC = new JPanel(); panelTGC.setLayout( new FlowLayout()); panelTGC.add( buttonTGCtrigger); panelTGC.add( waitIndicatorTGCtrigger); panelTGC.add( buttonCancel); //now add panels to the pane pane1.add( panelTGC); //Display the window. // frame1.pack(); frame1.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater( new Runnable() { public void run() { WaitIndicatorTest theApp; theApp = new WaitIndicatorTest(); theApp.createAndShowGUI(); } }); } }
VIEWS ON THIS POST

133

Posted on:

Monday 1st October 2012
View Replies!

My Frame is not repainting itself after SWING conversion

Guys, PLEASE HELP!!! Hope you can help me out... been sitting with this problem for a few days now I'm a java rookie. I'm trying to convert this 3D AWT calculator to Swing. So far i managed to change all the AWT components to Swing components. But the problem i have is that everytime i start the application i get a gray screen .The moment i slide my mouse over the gray screen, the buttons start appearing one by one.. what am i doing wrong \t.. the code i'm talking about is attatached to this message. i would really appreciate some help with this. The calculator has 9 classes in it's package.. =============================================== CLASS 1 =============================================== import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.*; //import java.awt.Graphics; import javax.swing.JPanel; public class AwtCalc extends JPanel { //Labels for the number panel of the calculator private String[] numPanelText = { " 1 ", " 2 ", " 3 ", " 4 ", " 5 ", " 6 ", " 7 ", " 8 ", " 9 ", Operator.CLEAR , " 0 ", Operator.DOT }; //Labels for the operator panel of the calculator private String[] operPanelText = { Operator.ADD, Operator.SUBTRACT, Operator.LOGARITHM,Operator.MemoryClear, Operator.MULTIPLY, Operator.DIVIDE, Operator.SINUS,Operator.MemoryRead, Operator.POW, Operator.SQRT, Operator.COSINUS, Operator.MemoryStore, Operator.NEGATE, Operator.EQUALS ,Operator.TANGUS,Operator.MemoryAdd, Operator.MemorySubt,Operator.MemorySpot }; //--------------------------------------------- /** private String[] operPanelText2 = {Operator.LOGARITHM,Operator.MemoryClear, Operator.SINUS,Operator.MemoryRead, Operator.COSINUS, Operator.MemoryStore,Operator.TANGUS,Operator.MemoryAdd }; private Panel mtoetsButtons; */ //-------------------------------------------------- private JPanel numButtonPanel; //used to hold the number buttons private JPanel operButtonPanel; //used to hold the operator buttons private Panel3D displayPanel; //used for the calculator's display private ButtonHandler handler; //action listener for the buttons private CalcDisplay display; //displays the output private Font buttonfont; public AwtCalc() { //Initialize buttonfont = new Font( "Courier", Font.PLAIN, 13 ); setLayout( new BorderLayout() ); setBackground( new Color( 212, 208, 200 ) ); Panel3D mainPanel = new Panel3D( Border3D.EXCLUDE_TOP_BORDER ); numButtonPanel = new JPanel( new GridLayout(5,3, 1, 1) ); operButtonPanel = new JPanel( new GridLayout(5, 5, 1, 1) ); displayPanel = new Panel3D( Border3D.EXCLUDE_BOTTOM_BORDER ); display = new CalcDisplay( 280,26); handler = new ButtonHandler( display ); displayPanel.add( display ); mainPanel.add( createNumberPanel() ); mainPanel.add( createOperPanel() ); add( displayPanel, BorderLayout.NORTH ); add( mainPanel, BorderLayout.CENTER ); mainPanel.setVisible(true); } /* * Method: createNumberPanel * Description: contructs and returns the calculator's number panel */ private JPanel createNumberPanel() { if ( display != null ) { ButtonComponent btn = null; for ( int i = 0; i < numPanelText.length; i++ ) { btn = new ButtonComponent( numPanelText[i] ); btn.addActionListener( handler ); btn.setFont( buttonfont ); numButtonPanel.add( btn ); } } return numButtonPanel; } /** * Method: createOperPanel * Description: contructs and returns the calculator's number panel **/ private JPanel createOperPanel() { ButtonComponent btn = null; for ( int i = 0; i < operPanelText.length; i++ ) { btn = new ButtonComponent( operPanelText[i] ); btn.setFont( buttonfont ); btn.addActionListener( handler ); operButtonPanel.add( btn ); } return operButtonPanel; } }
VIEWS ON THIS POST

219

Posted on:

Wednesday 17th October 2012
View Replies!

Haw to display painting in Panel

Hi i start to experiment with painting and a wonder where is the problem in this code import javax.swing.*; import java.awt.*; class World { World() { JPanel panel = new JPanel(); JFrame frame = new JFrame(); frame.add(panel); frame.setSize(200,200); frame.setVisible(true); } public void paint (Graphics g) { g.drawString(" World!", 50, 25); } public static void main(String args[]) { new World(); } }
VIEWS ON THIS POST

158

Posted on:

Wednesday 17th October 2012
View Replies!

painting a custom JComponent on a JLayeredPane

EDIT: this is an edited version of the original post since that was probably a bit too much at once... i'll try to keep it a bit simpler now to hopefully get an answer... dear javaranch community, i have found this place a valueable source of information then and when and finally signed up to discuss an issue i'm not really sure about. i have the OpenJDK Runtime Environment (build 1.6.0_0-b11) installed, my OS is Ubuntu-Linux. the scenario is as follows: i want to display a number of lines and some filled rectangles on a panel. all of these objects can possibly overlap and the z-order (or stacking order) is important. i found that when i draw onto a normal JPanel, its not entirely reliable that the last painted object is also displayed on top so i found JLayeredPane might be useful for what i am trying to achieve. since i wan't full control over where my lines and rectangles appear, i use a null-layout (no layout-manager). it took some time until i found out, that my custom JComponents won't get painted unless i call setSize() with values > 0 before. further, when i set my custom JComponent to lets say a size of 50x50, it seems i can only use draw commands within the area of (0,0) and (50,50), everything outside this area won't get displayed. so unless line 29 on SimpleLine is commented in, no lines are visible and since there is no output on the console, paintComponent() is probably never called. :: can anybody please tell me whats happening here or confirm this behaviour here is a code example, the controlling class: package custJComponentDrawingSimple; import javax.swing.JFrame; import javax.swing.JLayeredPane; import java.awt.Color; public class CJCD { private static JFrame frm; private static JLayeredPane lpnl; protected static int pnlw, pnlh; // the inner dimensions of the panel (without windowborders) public static void main(String[] args) { // main window settings CJCD.frm = new JFrame( "custJComponentDrawingTest" ); CJCD.frm.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); CJCD.frm.setSize( 400, 400 ); CJCD.frm.setResizable(false); CJCD.frm.setLayout(null); CJCD.frm.setVisible( true ); // determine inner size of window CJCD.pnlw = CJCD.frm.getContentPane().getWidth(); CJCD.pnlh = CJCD.frm.getContentPane().getHeight(); // SimpleLines will be stacked in a layered pane CJCD.lpnl = new JLayeredPane(); // set panes size to main windows inner size CJCD.lpnl.setSize( CJCD.pnlw, CJCD.pnlh ); CJCD.lpnl.setOpaque(true); CJCD.lpnl.setBackground(new Color(31, 31, 31)); CJCD.lpnl.setVisible(true); CJCD.frm.add(CJCD.lpnl); // add lpnl to frame // add some test-lines SimpleLine cSL1, cSL2; cSL1 = new SimpleLine(1, 10, 10, 360, 360); CJCD.lpnl.add(cSL1, 1); // this doesn't help cSL1.setVisible(true); cSL1.repaint(); // explicitly request repaint of the component cSL2 = new SimpleLine(2, 80, 300, 380 , 10); CJCD.lpnl.add(cSL2, 2); CJCD.lpnl.repaint(); // explicitly request repaint of the container } }
VIEWS ON THIS POST

192

Posted on:

Wednesday 17th October 2012
View Replies!

JPanel not repainting

I do not use SWING a lot and I need help figuring this out: Inside JFrame I added JSplitFrame which bottom part contains JPanel. Now I want the panel dynamically populated with checkboxes after a button is pressed. Here is the code inside the panel which generates checkboxes: ... private Box bx; public MyPanel (){//this is the panel constructor extending JPanel super(); initialize(); bx=new Box(BoxLayout.Y_AXIS); add(bx); } ... public void populate(int start){ bx.remove() remove(bx); int sz=20; for (int i=0;i
VIEWS ON THIS POST

167

Posted on:

Wednesday 17th October 2012
View Replies!

painting hundreds of Rectangles in JPanel

Hi ranchers! I need some advise on how to make my paintComponent go faster. I'm bulding a InDesign like program. A user can drag rectangles, change border, columns, colors on the rectangle. rectangles have diffrent z-index so you can draw a rectangle over a rectangle. Every time the mouse is moved over the JPanel that acts like a container for the rectangles 4 JSpinners is changed with the x, y , width and height for all selected rectangles. If I have say 50-100 rectangles and drag them around the screen it is very slow. Is there someway of making drawing faster for 50-100 rectangles that is beeing dragged around the screen
VIEWS ON THIS POST

152

Posted on:

Thursday 18th October 2012
View Replies!

JTextArea not painting

I have a JFrame in which i am adding two JTextAreas and a JPanel. In my JPanel i am drawing some graphics using basic Java drawing functions. The first TextArea is to act as an output prompt, and the second acts as the input field where i type commands. the program is a simple text based game. The problem is that the JPanel paints and the graphics inside it show, but both of the textAreas do not paint until i type a command and press enter, or until i highlight text that's already in the compnent. i've already tried calling repaint(), repaintComponent(), and repaintComponents(). none of them seem to work. any help is greatly appreciated.
VIEWS ON THIS POST

151

Posted on:

Thursday 18th October 2012
View Replies!

Problem when repainting rectangles

Hi! I want a user to draw rectangles in a Indesign fashion. Yoy should be able to resize and so on. The problem is that when I drag the mouse real fast the rectangle moves to a position that is not correct If someone could look at this code. If you press the 1 button you can select rectangles and move them. If you press the 2 button you can drag rectangles. Please try and drag them fast and you will see them jump around. I use the technique that if the offset Point. ( The first point on the mouse ) i less than the mouse coordinate in the drag then the x , y of the rectangle becomes the drag mouse coordinate. I think the problem lies here but I don't know why and what I'm doing wrong. Here is my code. It is under process so It is not built with speed in mind. If you have another approach to my problem then please tell me. import javax.swing.*; import java.awt.*; import java.awt.geom.*; import java.awt.event.*; import java.util.*; public class Tester extends JFrame{ public static int ACTION = 1; public static int EDGE_POSITION = -1; public Tester(){ this.getContentPane().setLayout( new BorderLayout() ); this.getContentPane().add( new Rects(), BorderLayout.EAST ); JPanel panel = new JPanel(); panel.setPreferredSize( new Dimension( 150 , 400 ) ); JButton b1 = new JButton( "1" ); JButton b2 = new JButton( "2" ); b1.addActionListener( new ActionListener(){ public void actionPerformed( ActionEvent e ){ ACTION = 1; } } ); b2.addActionListener( new ActionListener(){ public void actionPerformed( ActionEvent e ){ ACTION = 2; } } ); panel.add( b1 ); panel.add( b2 ); this.getContentPane().add( panel, BorderLayout.WEST ); this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); this.setSize( new Dimension(400 , 400 ) ) ; this.setVisible( true ); } class Block{ private int MAX_EDGES = 9; private int EDGE_WIDTH = 6; private int EDGE_HEIGHT = 6; private int EDGE_SPACE = 3; private boolean isSelector = false; private Rectangle rect; private Vector edges; private boolean m_IsActive = false; Block( Rectangle rect ){ this( rect, false ); } Block( Rectangle rect, boolean selector ){ this.rect = rect; this.isSelector = selector; } public boolean isActive(){ return this.m_IsActive; } public void setActive( boolean state ){ if( this.isSelector ){ state = false; } if( state ){ edges = new Vector( MAX_EDGES ); for( int i = 0; i < MAX_EDGES; i++ ){ edges.add( new Rectangle() ); } }else{ if( edges != null ){ edges.clear(); } edges = null; } this.m_IsActive = state; } public Rectangle getRectangle(){ return this.rect; } public boolean isSelector(){ return this.isSelector; } public Vector getEdges(){ return this.edges; } public void updateEdgeBounds(){ if( this.isActive() ){ double height = this.rect.getHeight(); double width = this.rect.getWidth(); double x = this.rect.getX(); double y = this.rect.getY(); for( int i = 0; i < edges.size(); i++ ){ Rectangle edge = ( Rectangle ) edges.elementAt( i ); switch( i ){ case 0: // Upper left edge.setRect( x - EDGE_SPACE, y - EDGE_SPACE, EDGE_WIDTH , EDGE_HEIGHT ); break; case 1: // Upper middle edge.setRect( ( int ) ( x - EDGE_SPACE + ( width / 2 ) ), ( int )( y - EDGE_SPACE ), EDGE_WIDTH , EDGE_HEIGHT ); break; case 2: // Upper right edge.setRect( ( int ) ( x + width - EDGE_SPACE ),( int ) ( y - EDGE_SPACE ), EDGE_WIDTH , EDGE_HEIGHT ); break; case 3: // Middle left edge.setRect( ( int ) ( x - EDGE_SPACE ),( int ) ( y - EDGE_SPACE + height / 2 ), EDGE_WIDTH , EDGE_HEIGHT ); break; case 4: // bottom Left edge.setRect( ( int ) ( x - EDGE_SPACE ),( int ) ( y + height - EDGE_SPACE ), EDGE_WIDTH , EDGE_HEIGHT ); break; case 5: // bottom middle edge.setRect( ( int ) ( x - EDGE_SPACE +( width / 2 ) ),( int ) ( y + height - EDGE_SPACE ), EDGE_WIDTH , EDGE_HEIGHT ); break; case 6: // bottom right edge.setRect( ( int ) ( x + width - EDGE_SPACE ),( int ) ( y + height - EDGE_SPACE ), EDGE_WIDTH , EDGE_HEIGHT ); break; case 7: // Middle right edge.setRect( ( int ) ( x + width - EDGE_SPACE ),( int ) ( y - EDGE_SPACE + height / 2 ), EDGE_WIDTH , EDGE_HEIGHT ); break; case 8: // Middle edge.setRect( ( int ) ( x - 2 + ( width / 2 ) ),( int ) ( y - 2 + ( height / 2 ) ), 4 , 4 ); break; } } } } public void setBlockBounds( Point offset, Point point ){ double height = 0; double width = 0; double x = this.rect.getX(); double y = this.rect.getY(); if( point.getY() < offset.getY() ){ y = point.getY(); height = offset.getY() - point.getY(); }else{ height = point.getY() - offset.getY(); } if( point.getX() < offset.getX() ){ x = point.getX(); width = offset.getX() - point.getX(); }else{ width = point.getX() - offset.getX(); } this.rect.setRect( x , y , width , height ); this.updateEdgeBounds(); } } class Rects extends JPanel implements MouseListener, MouseMotionListener, KeyListener { boolean pressedEvent = false; boolean moveBlockEvent = false; private Block dragRect; private Vector rects; private Point offsetPoint; final float dash1[] = { 2.0f }; final BasicStroke dashed = new BasicStroke(1.0f,BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f); final BasicStroke normal = new BasicStroke(1); Rects() { setPreferredSize( new Dimension( 250 , 400 ) ); setBackground(Color.white); addMouseListener(this); addMouseMotionListener(this); rects = new Vector(); addKeyListener( this ); } public void paintComponent( Graphics g ){ super.paintComponent( g ); Graphics2D g2 = (Graphics2D)g; for( int i = 0; i < rects.size(); i++ ){ g2.setStroke( normal ); g2.setColor( new Color( 79, 153, 255 ) ); Block block = ( Block ) rects.elementAt( i ); if( block.isSelector() ){ g2.setColor( new Color( 0 , 0 , 0 ) ); g2.setStroke( dashed ); } g2.draw( block.getRectangle() ); if( block.isActive() ){ Vector a = block.getEdges(); for( int j = 0; j < a.size(); j++ ){ Rectangle rect = ( Rectangle ) a.elementAt( j ); g2.setColor( new Color( 79, 153, 255 ) ); g2.draw( rect ); if( j != 8 ){ g2.setColor( Color.WHITE ); g2.fillRect(rect.x + 1, rect.y + 1, rect.width - 1, rect.height - 1); }else{ g2.fillRect(rect.x + 1, rect.y + 1, rect.width - 1, rect.height - 1); } } } } g2.dispose(); } public void mousePressed(MouseEvent evt) { System.out.println( "pressed : " + EDGE_POSITION + "\n" ); if( EDGE_POSITION != -1 ){ moveBlockEvent = true; } if( pressedEvent ) return; pressedEvent = true; mouseClickEvent( evt ); } // end mousePressed() public void mouseReleased(MouseEvent evt) { Point p = evt.getPoint(); if( offsetPoint.getX() == p.getX() && offsetPoint.getY() == p.getY() ){ }else{ if( ACTION == 2 ){ Block b = new Block( new Rectangle( offsetPoint ) ); b.setActive( true ); b.setBlockBounds( offsetPoint, p ); rects.add( b ); }else{ if( moveBlockEvent ){ Block block = new Block( new Rectangle( ( int )dragRect.getRectangle().getX(), ( int )dragRect.getRectangle().getY(), ( int )dragRect.getRectangle().getWidth(), ( int )dragRect.getRectangle().getHeight() ) ); block.setActive( true ); block.updateEdgeBounds(); rects.add( block ); }else{ for( int i = 0; i < rects.size(); i++ ){ Block block = ( Block ) rects.elementAt( i ); if( dragRect.getRectangle().intersects( block.getRectangle() ) ){ block.setActive( true ); block.updateEdgeBounds(); }else{ block.setActive( false ); block.updateEdgeBounds(); } } } } } moveBlockEvent = false; pressedEvent = false; EDGE_POSITION = -1; rects.remove( dragRect ); dragRect = null; p = null; offsetPoint = null; repaint(); } public void mouseClickEvent( MouseEvent evt ){ offsetPoint = evt.getPoint(); if( dragRect != null && moveBlockEvent ){ offsetPoint = null; switch( EDGE_POSITION ){ case 0: offsetPoint = new Point( ( int )( dragRect.getRectangle().getX() + dragRect.getRectangle().getWidth() ), ( int ) ( dragRect.getRectangle().getY() + dragRect.getRectangle().getHeight() ) ); break; case 1: offsetPoint = new Point( ( int )( dragRect.getRectangle().getX() ), ( int ) ( dragRect.getRectangle().getY() + dragRect.getRectangle().getHeight() ) ); break; case 2: offsetPoint = new Point( ( int )( dragRect.getRectangle().getX() ), ( int ) ( dragRect.getRectangle().getY() + dragRect.getRectangle().getHeight() ) ); break; case 3: offsetPoint = new Point( ( int )( dragRect.getRectangle().getX() + + dragRect.getRectangle().getWidth() ), ( int ) ( dragRect.getRectangle().getY() ) ); break; case 4: offsetPoint = new Point( ( int )( dragRect.getRectangle().getX() + dragRect.getRectangle().getWidth() ), ( int ) ( dragRect.getRectangle().getY() ) ); break; case 5: offsetPoint = new Point( ( int )( dragRect.getRectangle().getX()), ( int ) ( dragRect.getRectangle().getY() ) ); break; case 6: offsetPoint = new Point( ( int )( dragRect.getRectangle().getX() ), ( int ) ( dragRect.getRectangle().getY() ) ); break; } rects.remove( dragRect ); }else{ switch( ACTION ){ case 1: for( int i = 0; i < rects.size(); i++ ){ Block block = ( Block ) rects.elementAt( i ); if( block.getRectangle().contains( offsetPoint ) ){ block.setActive( true ); block.updateEdgeBounds(); }else{ block.setActive( false ); } } dragRect = new Block( new Rectangle( offsetPoint ), true ); break; case 2: // Inactivate last added Block if( rects.size() > 0 ){ Block block = ( Block ) rects.elementAt( rects.size() - 1 ); block.setActive( false ); } dragRect = new Block( new Rectangle( offsetPoint ) ); break; } } rects.add( dragRect ); } public void mouseDragged(MouseEvent evt) { Point p = evt.getPoint(); System.out.println( offsetPoint.getX() + ":" + offsetPoint.getY() ); if( moveBlockEvent ){ switch( EDGE_POSITION ){ case 1: p = new Point( ( int ) ( dragRect.getRectangle().getX() + dragRect.getRectangle().getWidth() ), ( int ) evt.getY() ); break; case 3: p = new Point( ( int ) ( evt.getX() ), ( int ) ( dragRect.getRectangle().getY() + dragRect.getRectangle().getHeight() ) ); break; case 5: p = new Point( ( int ) ( dragRect.getRectangle().getX() + dragRect.getRectangle().getWidth() ), ( int ) evt.getY() ); break; } } dragRect.setBlockBounds( offsetPoint, p ); repaint(); } // end mouseDragged() public void mouseClicked(MouseEvent evt) { return; } public void mouseEntered(MouseEvent evt) { if( moveBlockEvent ) return; if( ACTION == 2 ){ this.setCursor( Cursor.getPredefinedCursor( Cursor.CROSSHAIR_CURSOR ) ); } if( ACTION == 1 ){ this.setCursor( Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR ) ); } this.requestFocusInWindow(); } public void mouseExited(MouseEvent evt) { } public void mouseMoved(MouseEvent evt) { if( moveBlockEvent ) return; if( ACTION == 1 ){ this.setCursor( Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR ) ); Point point = evt.getPoint(); for( int i = 0; i < rects.size(); i++ ){ Block block = ( Block ) rects.elementAt( i ); if( block.isActive() ){ Vector a = block.getEdges(); for( int j = 0; j < a.size(); j++ ){ Rectangle rect = ( Rectangle ) a.elementAt( j ); if( rect.contains( point ) ){ switch( j ){ case 0: this.setCursor( Cursor.getPredefinedCursor( Cursor.SE_RESIZE_CURSOR ) ); break; case 1: this.setCursor( Cursor.getPredefinedCursor( Cursor.S_RESIZE_CURSOR ) ); break; case 2: this.setCursor( Cursor.getPredefinedCursor( Cursor.SW_RESIZE_CURSOR ) ); break; case 3: this.setCursor( Cursor.getPredefinedCursor( Cursor.E_RESIZE_CURSOR ) ); break; case 4: this.setCursor( Cursor.getPredefinedCursor( Cursor.NE_RESIZE_CURSOR ) ); break; case 5: this.setCursor( Cursor.getPredefinedCursor( Cursor.N_RESIZE_CURSOR ) ); break; case 6: this.setCursor( Cursor.getPredefinedCursor( Cursor.NW_RESIZE_CURSOR ) ); break; case 7: this.setCursor( Cursor.getPredefinedCursor( Cursor.W_RESIZE_CURSOR ) ); break; case 8: this.setCursor( Cursor.getPredefinedCursor( Cursor.MOVE_CURSOR ) ); break; } dragRect = block; EDGE_POSITION = j; return; } } } } } } public void keyTyped( KeyEvent evt ){} public void keyPressed( KeyEvent evt ){ int x = 0; int y = 0; if( evt.getKeyCode() == 39 || evt.getKeyChar() == KeyEvent.VK_KP_RIGHT || evt.getKeyChar() == KeyEvent.KEY_LOCATION_RIGHT ){ x = 1; } if( evt.getKeyCode() == 37 || evt.getKeyChar() == KeyEvent.VK_KP_LEFT || evt.getKeyChar() == KeyEvent.KEY_LOCATION_LEFT ){ x = -1; } if( evt.getKeyCode() == 38 || evt.getKeyChar() == KeyEvent.VK_KP_UP ){ y = -1; } if( evt.getKeyCode() == 40 || evt.getKeyChar() == KeyEvent.VK_KP_DOWN ){ y = 1; } if( x != 0 || y != 0 ){ for( int i = 0; i < rects.size(); i++ ){ Block block = ( Block ) rects.elementAt( i ); if( block.isActive() ){ block.getRectangle().setLocation( ( int )block.getRectangle().getX() + x , ( int )block.getRectangle().getY()+ y ); block.updateEdgeBounds(); } } } repaint(); } public void delete(){ for( int i = 0; i < rects.size(); i++ ){ Block block = ( Block ) rects.elementAt( i ); if( block.isActive() ){ rects.remove( block ); this.delete(); } } } public void keyReleased( KeyEvent evt ){ if( evt.getKeyChar() == KeyEvent.VK_BACK_SPACE ){ this.delete(); repaint(); } } } public static void main( String args[] ){ new Tester(); } }
VIEWS ON THIS POST

160

Posted on:

Thursday 18th October 2012
View Replies!

repainting in shapes other than square

What I want to do is to repaint a square component but only a portion of it say in a circular shape. Something like.... repaint(10,10,new Circle()) ... I think that gets the point across. I do not want to repaint the entire component just some portion of it in a shape other than repaint(0,0,getWidth(),getHeight()) type of deal.
VIEWS ON THIS POST

125

Posted on:

Monday 22nd October 2012
View Replies!

problem painting

I have a JFrame that contains a JPanel (tbox), and a JScrollPane (vPort) which displays the contents of another JPanel (view). The problem is when I draw on 'view' tbox does not repaint and the scrollbars on vPort do not repaint, they show whatever is behind the JFrame. The drawing is done in the JFrame's 'paint' event. I've tried calling the 'repaint()' methods for 'tbox' and 'vPort' at the end of the event and the componets repaint, but then it doesn't show what is drawn in view. When no repaints are called: When 'tbox.repaint()' is called: When 'vPort.repaint()' is called: When both are repainted:
VIEWS ON THIS POST

150

Posted on:

Monday 22nd October 2012
View Replies!

JLabel not repainting automatically

Dear Readers, I have a JFrame with four JPanels in it. In one of the JPanels, I have a JLabel (in a JScrollPane) as the only component in that JPanel that I use for displaying Sprites (little objects). Everything works except for the fact that whenever I minimize this JFrame or maximize it, the Sprites disappear. Only when I move the JScrollPane associated with the JLabel do the Sprites reappear. I know this is a problem with paintComponent() not being called. I tried everything I know but it still dosent work. I tried setting listeners for the JFrame so that when an event occurs I call the method to repaint the Sprites. But it didnt work. Your help would be greatly appreciated. [ March 06, 2007: Message edited by: Shyam Prasad Murarka ]
VIEWS ON THIS POST

135

Posted on:

Monday 22nd October 2012
View Replies!

Laying out components in JPanel(s) and LayoutManager(s)

Hi all, I'm practicing Swing examples with JPanels and LayoutManagers to display the typical windows form. I'm not using any open source class because it's for my SCJD. Problem: Picture this, i have a JFrame with a GridLayout manager of 3 by 3. Each cell contains a JPanel with a GridLayout manager for them also (actually not all of them). When i add components to the cells of the JPanels, they seem to be too far apart and all in the center of the cell, and because some components are bigger in height than other, they seem reall un-aligned and not very professional like. I'm sure there is something to align them in there corresponging cells, but what, and is what i am doing normal
VIEWS ON THIS POST

124

Posted on:

Tuesday 23rd October 2012
View Replies!

Swing bug? scrolling in BLIT_SCROLL_MODE with painting JTextArea components hangs app

no replies\t I am surprised...
VIEWS ON THIS POST

222

Posted on:

Tuesday 23rd October 2012
View Replies!

JDesktopPane/JInternalFrame - question re: closing frames and repainting

I have a JSplitPane that contains a JPanel as one of its subcomponents. This JPanel (BorderLayout) contains a toolbar (another JPanel) and a JDesktopPane. The JDesktopPane contains 0-many JInternalFrames all of which are rather simple (i.e., I don't do anything real fancy). The toolbar, among other things, contains a button that when clicked will close all of the JInternalFrames in the JDesktopPane. If I click on an individual frame's close button (X) in the top-right corner, without having written one line of code to handle this, the JSplitPane.paint(Graphics) method is called. If I click on the Close button in my toolbar, my myToolbarPane.actionPerformed() method is called (see below) and the JSplitPane.paint(Graphics) method is NOT called (using either implementation). public void actionPerformed(ActionEvent e) { // Implementation #1 myDesktopPane.remove(); myDesktopPane.repaint(); // Implementation #2 // JInternalFrame[] elementFrames = myDesktopPane.getFrames(); // for (int i = 0; i < elementFrames.length; i++) { // elementFrames[i].doDefaultCloseAction(); // } } The question I am throwing out to is ultimately why is the JSplitPane.paint(Graphics) method NOT called when the Close button is clicked It just so happens that I need a panel in the other part of the JSplitPane to repaint when a JInternalFrame is closed. This is not happening when I click on the Close button. Also know that I tried having the panel that needs to update listen to/observe when the frames are closed and have confirmed it is being notified and it is calling revalidate() and repaint() but nothing happens because it thinks the height and width of the panel is 0.
VIEWS ON THIS POST

231

Posted on:

Tuesday 23rd October 2012
View Replies!

Repainting a nested JPanel

I have a JPanel that's nested inside of another JPanel. this panel is supposed to do is repeatedly paint an image that I'm updating during a loop. During the loop my program freezes and nothing paints. After my animation loop runs, it then finally calls paint and just for fun paints in some other graphics. Code included, please help public class WheelPanel extends JPanel { static BufferedImage wheelImage;//read in elsewhere static Graphics2D g;//wheelImage.createGraphics(), graphics context of wheelImage int WIDTH = 256, HEIGHT = 400; Wheel wheel = new Wheel(); private JButton spin = new JButton("Spin"); public WheelPanel(){ setLayout(new FlowLayout()); setPreferredSize(new Dimension(WIDTH,HEIGHT)); setMaximumSize(new Dimension(WIDTH,HEIGHT)); setMinimumSize(new Dimension(WIDTH,HEIGHT)); spin.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ int number = spin(); //take action on table } }); add(wheel); add(spin); } public int spin(){ Random random = new Random(); try{ for(double c=600; c>=0; c-=3){ g.rotate(c/180.*Math.PI,wheel.getWidth()/2,wheel.getHeight()/2);//pretty sure this works, hard to tell repaint(); Thread.sleep(50); } }catch(InterruptedException e){} return random.nextInt(37)-1; } public void paintComponent(Graphics g){ } class Wheel extends JPanel{ protected int WIDTH=256, HEIGHT=256; public Wheel(){ setPreferredSize(new Dimension(WIDTH,HEIGHT)); setMaximumSize(new Dimension(WIDTH,HEIGHT)); setMinimumSize(new Dimension(WIDTH,HEIGHT)); repaint(); } public void paintComponent(Graphics g){ g.drawImage(wheelImage,0,0,this);//works, just not being called } } }
VIEWS ON THIS POST

142

Posted on:

Tuesday 23rd October 2012
View Replies!

Reshaping swing components

hi Is it possible to have swing components (buttons, label etc.) in shapes other than a rectangle (i.e circle etc.) If yes, please tell me how to, if no then why not
VIEWS ON THIS POST

146

Posted on:

Tuesday 23rd October 2012
View Replies!

adding components to JPanel

, I want to know how to make visible components added to a JPanel that happens to be inside a JScrollPane after the JFrame has already been created. My class, that extends JFrame, has the jbInit() method you see below. At the very end of the jbInit() method I set up cardPanel to a GridLayout of 10 rows 1 column. This is so that I can display up to 10 distinct components as I add them dynamically using the displayResults() method. As you can imagine, the new HandStats (which extend JPanel) if they are being added to cardPanel, are not being displayed. I've tried using repaint() methods but they don't do anything. How do I accomplish this Also, how do I remove the HandStats objects from cardPanel so that I can display another new set of them Alan ************************************************* ArrayList players = new ArrayList(); JPanel cardPanel = new JPanel(); private void jbInit() throws Exception { this.setSize(new Dimension(600, 300)); this.setTitle("Card Games"); contentPane = (JPanel) this.getContentPane(); ... ... cardPanel.setLayout(new GridLayout(10,1)); scrollpane.getViewport().add(cardPanel); contentPane.add(scrollpane, BorderLayout.CENTER); } private void displayResults() { for(int i = 0; i < players.size(); i++) { HandStats stats = new HandStats("Player" + (i + 1) + "\nScore: " + ((Player)players.get(i)).getHandScore()); Card[] cards = ((Player)players.get(i)).getHand(); for(int j = 0; j < cards.length; j++) stats.addComponent(cards[j]); cardPanel.add(stats); } scrollpane.repaint(); //doesn't do anything this.repaint(); //doesn't do anything either //enableMenus(); }
VIEWS ON THIS POST

126

Posted on:

Tuesday 23rd October 2012
View Replies!