我可以使用PaintListener事件在画布上成功绘制。一旦我绘制了矩阵。我需要创建一个按钮,单击该按钮将删除Matrix的随机行和列。问题是我在按钮选择监听器上无法获得图形GC的句柄。那么,我如何得到这个句柄。请检查以下代码:
package com.matrix.example;
import java.util.Random;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
* This class demonstrates drawing lines
*/
public class MatrixVisualizer {
private Matrix denseMatrix;
private Matrix sparseMatrix;
Display display;
static double[][] myMatrix = new double[][] { { 1, 9, 8, 3, 7, 0 },
{ 0, 2, 0, 1, 2, 4 }, { 2, 0, 1, 3, 8, 0 }, { 1, 9, 8, 2, 1, 0 },
{ 2, 0, 1, 4, 5, 6 } };
public void run() {
display = new Display();
Shell shell = new Shell(display);
shell.setText("Matrix Visualizor");
shell.setSize(800, 600);
createContents(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
/**
* Creates the main window's contents
*
* @param shell
* the main window
*/
private void createContents(Shell shell) {
shell.setLayout(new FillLayout());
final Canvas denseCanvas = new Canvas(shell, SWT.NONE);
denseCanvas.setLocation(400, 400);
Button hideButton = new Button(denseCanvas, SWT.PUSH);
hideButton.setBounds(250, 10, 100, 40);
hideButton.setText("Hide");
denseCanvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
renderMatrix(denseMatrix, e.gc);
}
});
hideButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Random rand = new Random();
int randCol = rand.nextInt(5) + 1;
int randRow = rand.nextInt(5) + 1;
denseMatrix = new DecoratorMatrix(myMatrix,true);
denseMatrix.setColumnNumber(randCol);
denseMatrix.setRowNumber(randRow);
denseCanvas.redraw();
}
});
}
private void renderMatrix(Matrix activeMatrix, GC c)
{
activeMatrix = new DenseMatrix(myMatrix);
Painter painter = new Painter();
painter.setGraphics(c);
activeMatrix.paintMatrix(painter);
}
/**
* The application entry point
*
* @param args
* the command line arguments
*/
public static void main(String[] args) {
new MatrixVisualizer().run();
}
}
答案 0 :(得分:1)
GC仅在绘图事件期间由SWT的内部提供给paintlistener。只需更改您想要的任何数据结构,并在用户单击按钮时调用denseCanvas.redraw()。
而不是: 画家画家=新画家(); painter.setGraphics(); denseMatrix.paintMatrix(画家); 使用 activeMatrix = denseMatrix; //数据已修改 denseCanvas.redraw();
让你的油漆听众变得简单:
denseCanvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
renderMatrix(activeMatrix, e.gc);
}
});
画布上的redraw()将触发您的绘图侦听器,它应该调用一个新函数renderMatrix,它执行SWT GUI调用以绘制矩阵。
paintlistener通常不应该使用每个油漆来创建对象。它也可能是处理或杀死GC的坏主意,因为它是由SWT提供的。