I have wrote a program that simulates memory alloca开发者_高级运维tion with first fit and best fit algorithms .
Now I want to associate my program with a drawing of set of boxes representing available memory segments
Before Allocation
After Allocation
So it just redraws but resizes one box and colors it ... What is the easiest way to do so ? I have a set of boxes with different sizes that will be drawn dynamically according to input when the user does some action one of the boxes will be resized and recolored and so on.
I think this is best approached using graphics.
- Instantiate a
BufferedImage
of a size to fit all boxes. - Get a
Graphics
instance by calling either ofgetGraphics()
orcreateGraphics()
. - For each memory block:
- Call
Graphics.setColor(Color)
according to allocation status, then.. Graphics.fillRect(int,int,int,int)
orfillPolygon(Polygon)
to draw the memory block.
- Call
- If needed, use an
AffineTransform
to scale the sizes. This would require aGraphics2D
object to draw on.
Use JPanel add JLabels like 0verbose but the layout to go with in my opinion is BoxLayout or GridBagLayout.
With FlowLayout you would have to make sure the size of the container is of a proper width to place one component under another, as by default it places components in a row.
From Java tutorial about FlowLayout "The FlowLayout class puts components in a row, sized at their preferred size. If the horizontal space in the container is too small to put all the components in one row, the FlowLayout class uses multiple rows."
Use a JPanel as container with vertical FlowLayout BoxLayout, and add to it a JLabel for each memory block.
If the memory blocks can be rendered all the same size, a JComponent
(or even easier a JProgressBar
) could be used to represent each memory block. Those could then be put into a GridLayout
or BoxLayout
to organize the placement. E.G.
MemoryAllocation.java
import java.awt.*;
import javax.swing.*;
import java.util.Random;
class MemoryAllocation {
public static JProgressBar getMemoryBlock(int full) {
JProgressBar progressBar = new JProgressBar(
SwingConstants.VERTICAL, 0, 100);
progressBar.setValue(full);
progressBar.setPreferredSize(new Dimension(30,20));
return progressBar;
}
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JPanel memoryView = new JPanel(new GridLayout(0,10,1,1));
Random random = new Random();
for (int ii=0; ii<200; ii++) {
int amount = 100;
if (random.nextInt(5)==4) {
amount = 100-random.nextInt(75);
}
memoryView.add( getMemoryBlock(amount) );
}
JOptionPane.showMessageDialog(null, memoryView);
}
});
}
}
精彩评论