【发布时间】:2015-08-22 09:07:18
【问题描述】:
我正在做一个项目,我工作的总体思路是在一个独立的项目中完成它的每个部分,然后在完成后通过库将其添加到主项目中。
我的问题是 - 我所做的一部分是在面板上进行绘画。 当我添加一个将其连接到主项目的图层窗格时,实际上并没有发生绘图。
这是我的项目示例代码:
在代码示例 1 中有 JLayeredPane,其中包含我的面板以执行绘图。
在代码示例 2 中有一个按钮。它的 actionPerformed 是将 JLayeredPane 添加到面板中。但是问题是添加了JLayeredPane后没有出现绘图。
代码示例 1:
public class GraphGui extends javax.swing.JFrame {
/**
* Creates new form GraphGui
*/
adjacencyMatrix m = new adjacencyMatrix();
Dfs df = new Dfs();
int[] x = new int[df.MAX_VERTS];
int[] y = new int[df.MAX_VERTS];
public Graphics2D d;
public Graphics2D doo;
int i = 0;
public GraphGui() {
setlookAndFeel();
initComponents();
setLocationRelativeTo(null);
DFS.setVisible(true);
adjMatrics.setVisible(false);
//display is the panel that draw over
d = (Graphics2D) display.getGraphics();
doo = (Graphics2D) jPanel2.getGraphics();
}
//crating an initialization of components are done automatically
public void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
df.dfs();
doo.setFont(new Font("TimesRoman", Font.BOLD, 19));
doo.drawString("visits: " + df.out, 5, 20);
df.out = "";
}
public void AddE1ActionPerformed(java.awt.event.ActionEvent evt) {
String j = start1.getText();
int k = Integer.parseInt(j) - 1;
String c = end1.getText();
int v = Integer.parseInt(c) - 1;
df.addEdge(k, v);
d.setFont(new Font("TimesRoman", Font.BOLD, 17));
d.drawLine(x[k] + 30, y[k] + 20, x[v], y[v] + 19);
}
public void AddV1ActionPerformed(java.awt.event.ActionEvent evt) {
String f = ver1.getText();
String toUpperCase = f.toUpperCase();
char r = toUpperCase.charAt(0);
df.addVertex(r);
int radius = 30;
int R = (int) (Math.random() * 256);
int G = (int) (Math.random() * 256);
int B = (int) (Math.random() * 256);
x[i] = R % 320;
y[i] = B % 167;
d.setColor(new Color(R, G, B));
d.setFont(new Font("TimesRoman", Font.BOLD, 15));
d.drawOval(x[i], y[i], radius, radius);
d.fillOval(x[i], y[i], radius, radius);
d.setColor(Color.BLACK);
d.drawString(r + "", x[i] + 10, y[i] + 20);
d.drawOval(0, 0, radius, radius);
i++;
}
此链接显示了代码示例 1 应该执行的操作:
https://pbs.twimg.com/media/CG8INXZXAAEqthh.png:large
代码示例 2
{
private void graphBTActionPerformed(java.awt.event.ActionEvent evt) {
GraphGui gr=new GraphGui();
jPanel2.removeAll();
jPanel2.add(gr.DFS);
MainLayer.setVisible(false);
Displaylayer.setVisible(true);
}
}
下面的链接是我添加面板后得到的- 什么都没有。
【问题讨论】:
-
JPanel.getGraphics()不是为任何JComponent获取Graphics对象的方法。绘画相关任务需要在上述JComponent的覆盖paintComponent(...)方法内完成。更多信息请访问performing Custom Painting。一个很simple example -
我以前试过,但对我没有帮助
-
i have tried that's before but it didn't help me- 因为您没有按照教程示例进行操作。下载教程中的最后一个示例以证明它有效。然后对工作示例进行更改以执行您想要的操作,而不是从您自己的不起作用的代码开始。此外,变量名称和方法名称不应以大写字符开头。你也可以从教程中学习。 -
我会再试一次,对于变量名和方法,我之前并不关心,但我会考虑到非常感谢您的帮助
标签: java user-interface panel draw