将画布添加到面板中不会显示该画布吗? [英] Adding a canvas to a panel doesn't show the canvas?
问题描述
首先:对不起,如果以前有人问过这个问题,但是我似乎在任何地方都找不到答案,所以我们去:
First of all: sorry, if this question was asked before, but I cannot seem to find an answer anywhere, so here we go:
我试图在将画布元素添加到面板中时在其周围带有标题边框的情况下显示画布元素.这是我的代码.
I am trying to get a canvas element to show while it being added to a panel with a titled border around the panel. Here is my code.
public class TestClass extends JFrame{
private TestClass() {
GuiCanvas canvas = new GuiCanvas();
setTitle("TestClass");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(1300, 800);
Border menuBorder = BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.LIGHT_GRAY), "Overview");
JPanel controlpanel = new JPanel();
JPanel panelCanvas = new JPanel();
panelCanvas.setBorder(menuBorder);
panelCanvas.add(canvas);
controlpanel.setLayout(new GridLayout(3, 1));
controlpanel.add(panelCanvas);
add(controlpanel);
setLocationRelativeTo(null);
setVisible(true);
System.out.println(canvas.getBounds());
}
private class GuiCanvas extends Canvas {
GuiCanvas() {
setBackground(Color.LIGHT_GRAY);
}
@Override
public void paint(Graphics g) {
g.drawLine(20, 20, 20, 200);
}
}
public static void main(String[] args) {
new TestClass();
}
}
当上面的代码应该显示我在GuiCanvas-Class中绘制的定义的线时,上面的代码将导致带有标题边框的空白面板.我在这里想念什么吗?甚至可以向面板添加画布元素吗?感谢您的提前帮助:)
The above code results in an empty panel with a titled border when it should show the defined line I draw in the GuiCanvas-Class. Am I missing something here? Is it even possible to add a canvas-element to a panel? Thanks for your help in advance :)
推荐答案
确实可以将Canvas
对象添加到JPanel
.
It is indeed possible to add a Canvas
object to a JPanel
.
您的问题在于您的Canvas
没有定义的大小.
您需要的是以下两行
Your problem lies in the fact that your Canvas
has no defined size.
What you need are the two following lines
canvas.setPreferredSize(new Dimension(1300,300));
/*
*
*/
this.pack();
这会将画布放置在panelCanvas
边框内,在浅灰色背景上显示黑色垂直线.
This will place your canvas inside the panelCanvas
border, displaying a black vertical line on a light gray background.
这篇关于将画布添加到面板中不会显示该画布吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!