我遇到了在将一个包含paintComponent的JPanel添加到JFrame时的问题。
如果这是我添加到框架的唯一组件,则可以正常工作。但是,一旦我添加了布局管理器并向JFrame添加其他组件,它就不再显示具有绘画的面板!
为了更清晰地说明...
以下是代码,只有添加JPanel,成功显示出来:
绘制标记的面板(实际上我并非试图绘制“hello”,这只是为了简化此处的代码)
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()也无效。
我必须包括一个布局管理器,否则它会添加带有绘画的面板,但不包括其他组件。
这是我的框架类现在的样子,也是我遇到问题的地方:
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();
// 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的新手,所以非常感谢您的帮助。 对于所有的代码混乱,感到抱歉并感谢您的帮助!