我在Java JPanel上从(0,0)
到坐标(JComponent.getWidth(), JComponent.getHeight())
水平和垂直长度将保持不变取决于常数NUM_STAIRS
初始绘图将是水平线。我猜这将使用while和if语句(可能是嵌套的),但我不知道如何生成这个算法。
我的想法:
版本1:
当y轴满足
要求时,首先绘制JComponent.getWidth()/NUM_STAIRS
长度的水平线
(y=n x JComponent.getHeight()/NUM_STAIRS, where 0< n<=NUM_STAIRS)
。
记住绘制线的端点坐标,绘制JComponent.getHeight()/NUM_STAIRS
的垂直线
在长度上,然后在终点的相同长度的x坐标处绘制下一条水平线
y = 1 x JComponent.getHeight()/NUM_STAIRS.
重复此操作,直到y = JComponent.getHeight()。
第2版:
做2个循环,分别绘制水平线和垂直线,想法将与版本1类似。但我对如何将这个想法写入某些代码感到困惑。
有人可以帮帮我吗?感谢。
答案 0 :(得分:2)
可能有很多方法可以实现这一目标...这个解决方案存在一个四舍五入的问题,但这个概念会让你感动......
基本思路,如你所说,每一步的宽度和高度都是可用空间的百分比。
每个步骤从步长宽度/高度与当前步长的乘数开始。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class StairWayToHeven {
public static void main(String[] args) {
new StairWayToHeven();
}
public StairWayToHeven() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private int numSteps = 4;
public TestPane() {
setBorder(new EmptyBorder(4, 4, 4, 4));
setLayout(new BorderLayout());
final JSlider slider = new JSlider(2, 20);
slider.setOpaque(false);
slider.setValue(4);
add(slider, BorderLayout.SOUTH);
slider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
numSteps = slider.getValue();
repaint();
}
});
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Insets insets = getInsets();
int width = getWidth() - (insets.left + insets.right);
int height = getHeight() - (insets.top + insets.bottom);
int stepWidth = Math.round((float)width / (float)numSteps);
int stepHeight = Math.round((float)height / (float)numSteps);
g.setColor(Color.BLACK);
for (int step = 0; step < numSteps; step++) {
int fromX = insets.left + (stepWidth * step);
int fromY = insets.top + (stepHeight * step);
int toX = insets.left + (stepWidth * (step + 1));
int toY = insets.top + (stepHeight * (step + 1));
g.drawLine(fromX, fromY, toX, fromY);
g.drawLine(toX, fromY, toX, toY);
}
}
}
}