我正在开发一个程序,其功能类似于Paint。看起来像这样:program
当我打开JComboBox(用于选择画笔大小)时发生错误。它似乎抹去了下面的所有内容。 JComboBox opened。关闭JComboBox之后,它看起来像这样:JComboBox closed
关于可能导致这种情况的任何想法以及如何补救?
代码:
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.awt.event.*;
public class Paint extends JFrame implements ActionListener {
private JPanel topBar;
private JComboBox<String> brushSizes;
private DrawArea drawArea;
public Paint() throws IOException {
setTitle("Paint");
setSize(500,500);
setLayout(new BorderLayout());
drawArea = new DrawArea();
topBar = new JPanel(new FlowLayout());
String[] sizes = {"1", "2", "3", "5", "8", "10", "25", "50", "100"};
brushSizes = new JComboBox<String>(sizes);
brushSizes.setSelectedIndex(0);
brushSizes.setActionCommand("BrushSize");
brushSizes.addActionListener(this);
topBar.add(brushSizes);
add(topBar, BorderLayout.NORTH);
add(drawArea, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("BrushSize")) {
drawArea.setBrushStroke(Integer.parseInt((String)brushSizes.getSelectedItem()));
}
}
public static void main(String[] args) throws IOException {
Paint paint = new Paint();
}
}
更多代码:
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class DrawArea extends JComponent implements MouseMotionListener, MouseListener {
private Color currentColor;
private boolean dragging;
private int toX;
private int toY;
private int brushSize;
private Graphics drawer;
public DrawArea() {
currentColor = Color.BLACK;
dragging = false;
addMouseListener(this);
addMouseMotionListener(this);
toX = -1;
toY = -1;
brushSize = 1;
repaint();
}
public void setBrushStroke(int size) {
brushSize = size;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0,0,1000,1000);
g.setColor(currentColor);
}
public void mousePressed(MouseEvent event) {
dragging = true;
toX = event.getX();
toY = event.getY();
drawer = getGraphics();
drawer.setColor(currentColor);
}
public void mouseReleased(MouseEvent event) {
dragging = false;
drawer.dispose();
drawer = null;
}
public void mouseDragged(MouseEvent event) {
if (dragging) {
int x = event.getX();
int y = event.getY();
Graphics2D drawerTo = (Graphics2D) drawer;
drawerTo.setStroke(new BasicStroke(brushSize));
drawerTo.drawLine(toX, toY, x, y);
toX = x;
toY = y;
}
}
public void mouseClicked(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
public void mouseMoved(MouseEvent event) {}
}
答案 0 :(得分:0)
有两种常见的方法来进行自定义绘画。请查看Custom Painting Approaches,以获取每种方法的示例:
DrawOnImage
示例展示了如何使用BufferedImage
的{{1}}对象绘制到Graphics
。
BufferedImage
示例演示了如何使用传递到组件的DrawOnComponent
方法的Graphics
对象。
您使用的方法取决于您的确切要求。