I wrote a java program which uses a JPanel for drawing. My problem
occurs when I need to draw something that is larger than the size of
the panel on which the drawing panel is put. I'd like to enlarge the
drawing panel so that a JScrollPane would be activated - i.e. scroll
bars will appear.
I've used this nesting: JFrame -> JSplitPane -> JScrollPane -> JPanel -> DrawPanel
This whole thing should be combined in a larger program of mine. So
I've created a sample program to represent the problem.
Here I've drawn only two lines, and enforced the drawing panel's size
to be 1000x1000. The solution should enable choosing the size
dynamically, meaning - enable resizing according to the drawing area.
I've creared two *.java files:
//1:
import javax.swing.*;
import java.awt.*;
public class MainWindow {
private final static Dimension formSize = new Dimension(600,400);
private final static Toolkit toolkit = Toolkit.getDefaultToolkit();
private final static Dimension scrnSize = toolkit.getScreenSize();
private final static Point formLoc = new
Point((scrnSize.width-formSize.width)/2,(scrnSize.height-formSize.height)/2);
private JSplitPane vSplit;
private JScrollPane drawScrollPane;
private JPanel drawBasePanel;
MainWindow() {
vSplit = new JSplitPane();
vSplit.setContinuousLayout(false);
vSplit.setEnabled(true);
vSplit.setResizeWeight(1.0);
vSplit.setDividerSize(10);
vSplit.setDividerLocation(170);
vSplit.setOneTouchExpandable(false);
drawScrollPane = new JScrollPane();
vSplit.setRightComponent(drawScrollPane);
drawBasePanel = new JPanel();
drawScrollPane.setViewportView(drawBasePanel);
JFrame frame = new JFrame("Resize Problems");
DrawPanel drawPanel = new DrawPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawBasePanel.setLayout(new GridLayout(1,1));
drawBasePanel.add(drawPanel);
Dimension minimumSize = new Dimension(300, 300);
drawBasePanel.setMinimumSize(minimumSize);
drawPanel.setMinimumSize(minimumSize);
drawBasePanel.setMinimumSize(minimumSize);
frame.getContentPane().add(vSplit);
frame.setSize(formSize);
frame.setLocation(formLoc);
frame.setVisible(true);
}
public static void main(String[] args){
MainWindow mainWindow = new MainWindow();
}
}
//2:
import javax.swing.*;
import java.awt.*;
public class DrawPanel extends JPanel {
public void paint(Graphics graphics) {
this.setSize(1000,1000);
this.setBackground(Color.white);
super.paintComponent(graphics);
Graphics2D g2 = (Graphics2D)graphics;
int width = this.getSize().width;
int height = this.getSize().height;
g2.drawLine(1, 1, width, height);
g2.drawLine(width+50, 1, 1, height+50);
}
} |