How to resize graphics

I have a Java applet for drawing an array (only one rectangle one by one).

When the user selects an array of size n , he will draw the rectangles n connected together. When n gets bigger, the graphs get bigger, but since I use JPanel to draw an array and JPanel will not scroll, I have to add that JPanel in JScrollPane , but still it will not scroll. The user can see only part of the entire array.

Can anybody help me?

Here is my code:

 public class ArrayPanel extends JPanel { .... public void paintComponent(Graphics g) { ...draw array here.. // I wish to get the updated size of the graphis here, // then i can reset the preferredSize()....? System.out.println("width=" + getWidth() + " height=" + getHeight()); } } public class ArrayDemo extends JPanel { public ArrayDemo() { super(new BorderLayout()); arrayPanel = new ArrayPanel(); arrayPanel.setPreferredSize(new Dimension(400, 300)); JScrollPane container = new JScrollPane(arrayPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ); container.setPreferredSize(arrayPanel.getPreferredSize()); add(container, BorderLayout.CENTER); ... } } 
+4
source share
1 answer

Do not set the size in paintComponent .

You did not specify this code, but you have some kind of position in the code where you know the size of this array and the size of your rectangles, so set the size of your JPanel there.

Here is an example (using a JFrame , not Applet , but the ideas are the same) that looks like this:

alt text http://img186.imageshack.us/img186/143/so2305419.png

 public class ScrollPanelFrame extends JFrame{ public ScrollPanelFrame() { ArrayPanel panel = new ArrayPanel(20, 20); JScrollPane container = new JScrollPane( panel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ); getContentPane().add(container); } class ArrayPanel extends JPanel { final int RECTANGLE_WIDTH = 100; final int RECTANGLE_HEIGHT = 100; int rectangleCountX; int rectangleCountY; public ArrayPanel(int rectangleCountX, int rectangleCountY) { this.rectangleCountX = rectangleCountX; this.rectangleCountY = rectangleCountY; this.setPreferredSize(new Dimension(RECTANGLE_WIDTH * rectangleCountX, RECTANGLE_HEIGHT * rectangleCountY)); } @Override public void paintComponent(Graphics g) { for(int x = 0 ; x < rectangleCountX ; x++) { for(int y = 0 ; y < rectangleCountY ; y++) { g.setColor(new Color(0, 0, (x+y)*64 % 256)); g.fillRect(x*RECTANGLE_WIDTH, y*RECTANGLE_HEIGHT, RECTANGLE_WIDTH, RECTANGLE_HEIGHT); } } } } public static void main(String[] args) { ScrollPanelFrame frame = new ScrollPanelFrame(); frame.setSize(600, 400); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setVisible(true); } } 
+3
source

Source: https://habr.com/ru/post/1301942/


All Articles