Вопрос

I am making a small JFrame in which I draw a large triangle. On all the sides of the triangle there has to be a label. I have to position these labels myself, because of the irregular shape of the triangle (yes, there will also be a non-right-angled triangle). (I have specified setResizable(false) on my JFrame, so there is no need for multiple sizes.)

Would there be any way to manually set the location of all my labels, WITH a layout manager?

Program design

Это было полезно?

Решение

You say that you want to draw the labels at irregular places e.g. at corners and at the sides the dhapes. Then I would recommend to use drawString(String s, int x, int y) in the Graphics2D API. So place the labels and draw then when you draw the figure.

See Lesson: Working with Text APIs for more advanced options like e.g. Fonts and Font metrics.

When you want to specify the exact position of labels, is the only case when you shouldn't use an Layout Manager.

Другие советы

If you want to have a canvas in the middle and then labels on any of the 4 sides, you could use a BorderLayout, like so:

JPanel framePanel = new JPanel(new BorderLayout());

JPanel triangleCanvas = ...
framePanel.add(triangleCanvas, BorderLayout.CENTER);

JPanel northLabels = ...
framePanel.add(northLabels, BorderLayout.PAGE_START);

JPanel southLabels = ...
framePanel.add(southLabels, BorderLayout.PAGE_END);

JPanel eastLabels = ...
framePanel.add(eastLabels, BorderLayout.LINE_END);

JPanel westLabels = ...
framePanel.add(westLabels, BorderLayout.LINE_START);

frame.getContentPane().add(framePanel);

The tricky part will be if you want to somehow align where your labels are depending on the currently drawn triangle (or whatever is in the container), but hopefully you don't want to do that.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top