我有一个 MyFrame
类,它扩展了 JFrame
。我使用 NET BEANS 中的设计选项向该框架添加了组件(控件,即按钮)。我有一个 MyCanvas
类,它使用重写的 paintComponent()
方法扩展了 JPanel
。我正在尝试将此组件添加到 MyFrame 类中。但是当我添加它并使其可见时, Canvas (JPanel
)不会在JFrame
上显示自己。
(首先,我尝试添加由 Canvas
扩展的 Mycanvas
类。但后来我在这里读了一个线程,尝试将其更改为 JPanel
。我也不起作用。对于 Canvas ,我显然使用油漆而不是 paintcomponent()
)
我的代码在下面
MyCanvas 类
public class MyCanvas extends javax.swing.JPanel{
MyCanvas()
{
super();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D graphics2D=(Graphics2D)g;
graphics2D.drawRect(10, 10, 10, 10);
graphics2D.drawOval(0, 0, 100, 100);
}
}
MyFrame
public class Myframe extends javax.swing.JFrame {
public Myframe() {
initComponents();
@SuppressWarnings("unchecked")
+generatedcode by the designer
private void RectangleActionPerformed(java.awt.event.ActionEvent evt) {
}
private void SquareActionPerformed(java.awt.event.ActionEvent evt) {
}
private void CircleActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Myframe().setVisible(true);
}
});
}
public void run() {
new Myframe().setVisible(true);
}
// Variables declaration - do not modify
private javax.swing.JButton Circle;
private javax.swing.JButton Rectangle;
private javax.swing.JButton Square;
// End of variables declaration
}
我的主程序
public static void main(String[] args) {
MyCanvas c = new MyCanvas();
Myframe f= new Myframe();//Works if used JFrame instead of MyFrame
f.add(c);
f.setVisible(true);
}
基本上我想创建一个 GUI,其中我想要可以触发事件并更改 Canvas 上绘制内容的按钮。我用空的 jframe 尝试过。将 Canvas /面板添加到 JFrame 。有效。我还更改了面板/ Canvas 并刷新了框架。这也很好用。但我无法这样做。
最佳答案
您正在混合创建 JFrame
使用 IDE 并创建 JPanel
您自己,请记住 IDE 将所有组件添加到 JFrame
在initComponents()
这是您希望拥有 Canvas
的理想位置。添加。
要么创建 JFrame
和JPanel
自己完成(不使用 Netbeans GUI Builder)
或
您可以使用 Netbeans 的调色板管理器来添加 Component
到调色板,然后您可以在 GUI 构建器中使用它,就像使用任何其他类一样:
(只需将 Canvas
类从项目树拖动到 GUI 设计器中的 JFrame
即可)
确保您的定制Canvas
功能:
- 覆盖
getPrefferedSize(..)
并返回适合的尺寸
引用:
关于java - Canvas/JPanel 未显示在 JFrame 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13091991/