【发布时间】:2012-02-11 07:40:09
【问题描述】:
我在将 JPanel(其中包含 paintComponent)添加到 JFrame 时遇到问题。
如果这是我添加到框架中的唯一内容,那么它可以工作。但是一旦我添加一个布局管理器并将其他组件添加到 JFrame,它就不再显示带有绘画的面板!
为了让这个更清楚......
这是有效的代码,JPanel 已成功显示:
绘制标志的面板(实际上我并不是要画你好,这里只是简单的代码)
public class SignPanel2 extends JPanel {
public int hello;
public void paintComponent(Graphics comp) {
Graphics g = (Graphics) comp;
g.setColor(Color.LIGHT_GRAY);
g.fillRect(70, 250, 150, 150);
g.setColor(Color.BLACK);
if (hello > 0)
g.drawString("h",135, 270);
if (hello > 1 )
g.drawString("h e",135, 270);
if (hello > 2)
g.drawString("h e l",135, 270);
if (hello > 3)
g.drawString("h e l l",135, 270);
if (hello > 4)
g.drawString("h e l l o",135, 270);
}
}
我放置面板的框架:
public class SignFrame extends JFrame {
// the constructor method
public SignFrame () {
super("This is the title of the Sign Frame");
setSize(300,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// make a container for the frame
Container content = getContentPane();
// call from the drawing panel
SignPanel2 signpanel = new SignPanel2();
// change class variable of SignPanel
signpanel.hello = 5;
signpanel.repaint();
// add signpanel to container
content.add(signpanel);
setContentPane(content);
setVisible(true);
}
}
主类
public class TheSignMain {
public static void main (String[] args) {
SignFrame signframe = new SignFrame();
}
}
上面的工作非常好,给了我一个框架,里面有想要的图画。
但是,如果我将其他组件添加到框架并添加布局管理器,它将不再显示绘画。即使我使用 repaint()。
我必须包括一个布局管理器,否则它会添加带有绘画的面板,而不是其他组件。
这就是我的框架类现在的样子,这就是我遇到问题的地方。
公共类 SignFrame 扩展 JFrame {
// the constructor method
public SignFrame () {
super("This is the title of the Sign Frame");
setSize(300,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// make a container for the frame
Container content = getContentPane();
// need a layout manager to decide the arrangement of the components on the container
FlowLayout flo = new FlowLayout();
// designate the layout manager to the container
content.setLayout(flo);
// make components
JPanel buttons = new JPanel();
JButton play = new JButton("Play");
JButton pause = new JButton("Pause");
JButton stop = new JButton("Stop");
// add components to a panel
buttons.add(play);
buttons.add(pause);
buttons.add(stop);
// add panel to frame container
content.add(buttons);
// call from the drawing panel
SignPanel2 signpanel = new SignPanel2();
// change class variable of SignPanel
signpanel.hello = 5;
signpanel.repaint();
// add signpanel to container
content.add(signpanel);
setContentPane(content);
setVisible(true);
}
}
我对 Java 完全陌生,因此非常感谢任何帮助。 抱歉所有这些代码,感谢您的帮助!
【问题讨论】:
-
+1,不过,很好的问题。今天帮我学到了一些东西:-)
-
@Gagandeep ...我不确定我对您的回答做了什么。我单击了 JB Nizet 旁边的勾号图标,使其成为接受的答案(即它解决了问题),但随后您的回复消失了。我不认为它会删除任何其他回复。抱歉,我今天才注册,所以我对论坛的运作方式很陌生。
-
不,这是故意的,我自己删除了。既然你想要什么以及 JB Nizet 告诉你的,那就太好了。保持微笑,不用担心:-)
-
您是否遇到过同样的问题?上次没有处理的东西,请注明?
标签: java swing jpanel layout-manager paintcomponent