好的,所以我有这个任务告诉我用一个可以绘制形状的按钮制作一个绘图程序,就像计算机上的“画家”绘图程序一样。问题是即使我遵循我在互联网上找到的类似java程序的代码,我甚至无法使白板出现。 所以这是我的代码:
主要课程:
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class Main
{
private static final Toolkit TOOLKIT;
static
{
TOOLKIT = Toolkit.getDefaultToolkit();
}
private Main()
{
}
public static void main(final String[] argv)
{
final ShapeFrame frame;
frame = new ShapeFrame();
position(frame);
frame.init();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static void position(final JFrame frame)
{
final Dimension size;
size = calculateScreenArea(0.80f,
0.80f);
frame.setSize(size);
frame.setLocation(centreOnScreen(size));
}
/**
* the amount of center on screen
* @param size space size.
* @return the complete calculated space.
*/
public static Point centreOnScreen(final Dimension size)
{
final Dimension screenSize;
if(size == null)
{
throw new IllegalArgumentException("Size cannot be null");
}
screenSize = TOOLKIT.getScreenSize();
return (new Point((screenSize.width - size.width) / 2,
(screenSize.height - size.height) / 2));
}
/**
* method that calculating screen area.
* @param widthPercent width percentage.
* @param heightPercent height percentage.
* @return dimension the dimension.
*/
public static Dimension calculateScreenArea(final float widthPercent,
final float heightPercent)
{
final Dimension screenSize;
final Dimension area;
final int width;
final int height;
final int size;
if((widthPercent <= 0.0f) || (widthPercent > 100.0f))
{
throw new IllegalArgumentException("widthPercent cannot be " +
"<= 0 or > 100 - got: " +
widthPercent);
}
if((heightPercent <= 0.0f) || (heightPercent > 100.0f))
{
throw new IllegalArgumentException("heightPercent cannot be " +
"<= 0 or > 100 - got: " +
heightPercent);
}
screenSize = TOOLKIT.getScreenSize();
width = (int)(screenSize.width * widthPercent);
height = (int)(screenSize.height * heightPercent);
size = Math.min(width,
height);
area = new Dimension(size,
size);
return (area);
}
}
我的JFrame类:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* This class creates the painting program's toolbar, buttons and stuffs.
* @author Fu Han
* @version 1.0
*/
public class ShapeFrame extends JFrame implements ActionListener {
private DrawPad drawPad;
/**
* the constant string 'save'.
*/
static final private String SAVE = "Save";
/**
* the constant string 'save as'.
*/
static final private String SAVE_AS = "Save As";
/**
* the constant string 'new'.
*/
static final private String NEW = "New";
/**
* the constant string 'color'.
*/
static final private String color = "Color";
/**
* string oval for easy access for buttons.
*/
static String oval = new String("oval");
/**
* string line for easy access for buttons.
*/
static String line = new String("line");
/**
* string circle for easy access for buttons.
*/
static String circle = new String("circle");
/**
* string rectangle for easy access for buttons.
*/
static String rectangle = new String("rectangle");
/**
* string square for easy access for buttons.
*/
static String square = new String("square");
/**
* ShapeFrame constructor.
*/
public ShapeFrame(){
super();
}
/**
* method that add buttons.
* @param toolBar Jtoolbar.
* @param btn Jbuttons.
*/
protected void addButtons(JToolBar toolBar, JButton btn) {
toolBar.add(btn);
}
/**
* method that add radio buttons.
* @param toolBar Jtoolbar.
* @param btn JRadioButton.
*/
protected void addRadioButtons(JToolBar toolBar, JRadioButton btn) {
toolBar.add(btn);
}
/**
* method that creates button.
* @param btnNam button name.
* @param actionCommand calling from string constant.
* @param toolTipText the message that will appear if cursor was hover over.
* @param altText alternative text.
* @return button Jbutton.
*/
protected JButton btnmaker(String btnNam, String actionCommand, String toolTipText, String altText) {
//Create and initialize the button.
JButton button = new JButton(btnNam);
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
return button;
}
/**
* action performed when clicked button.
* @param e mouse click.
*/
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(this, "you have clicked the button");
}
/**
* editlistener for menu bar.
* @author Fu Han
*
*/
private class EditListener implements ActionListener {
/**
* action performed when clicking menu button.
* @param e mouse click.
*/
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
}
/**
* radio listener for the radio buttons.
* @author
*
*/
private class RadioListener implements ActionListener{
/**
* action performed when click the button.
* @param e mouse click.
*/
public void actionPerformed(ActionEvent e) {
String factoryName = null;
System.out.print("ActionEvent received: ");
if (e.getActionCommand() == oval) {
System.out.println(oval + " pressed.");
drawPad.setCurrentShape(oval);
}else if(e.getActionCommand() == rectangle){
System.out.println(rectangle + " pressed.");
drawPad.setCurrentShape(rectangle);
}else if(e.getActionCommand() == square){
System.out.println(square + " pressed.");
drawPad.setCurrentShape(square);
}else{
System.out.println(line + " pressed.");}
drawPad.setCurrentShape(line);
}
/**
* method for when changes happened after clicking.
* @param e mouse click.
*/
public void itemStateChanged(ItemEvent e) {
}
}
/**
* method for when changes of states that happened after clicking.
* @param e mouse click.
*/
public void stateChanged(ChangeEvent e) {
}
/**
* method for selecting color.
*/
private void selectColor(){
Color newColor = JColorChooser.showDialog(
ShapeFrame.this,
"Choose New Background Color",
Color.RED);
}
/**
* GUI initialization.
*/
public void init(){
Container content = getContentPane();
//Creates a new container
content.setLayout(new BorderLayout());
//sets the layout
final DrawPad drawPad = new DrawPad();
//creates a new padDraw, which is pretty much the paint program
content.add(drawPad, BorderLayout.CENTER);
JMenuBar menubar = new JMenuBar();
EditListener l = new EditListener();
JMenu filem = new JMenu("File");
JMenuItem mi;
mi = filem.add(new JMenuItem("New", 'n'));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.CTRL_MASK));
mi.addActionListener(l);
mi = filem.add(new JMenuItem("Open", 'o'));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, Event.CTRL_MASK));
mi.addActionListener(l);
mi = filem.add(new JMenuItem("Save", 's'));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, Event.CTRL_MASK));
mi.addActionListener(l);
mi = filem.add(new JMenuItem("Save As", 'a'));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, Event.CTRL_MASK));
mi.addActionListener(l);
mi = filem.add(new JMenuItem("Exit", 'e'));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, Event.CTRL_MASK));
mi.addActionListener(l);
JMenu shapem = new JMenu("Shape");
JMenuItem smi;
smi = shapem.add(new JMenuItem("Line", 'l'));
smi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Event.CTRL_MASK));
smi.addActionListener(l);
smi = shapem.add(new JMenuItem("Circle", 'c'));
smi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK));
smi.addActionListener(l);
smi = shapem.add(new JMenuItem("Rectangle", 'r'));
smi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, Event.CTRL_MASK));
smi.addActionListener(l);
smi = shapem.add(new JMenuItem("Square", 'q'));
smi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.CTRL_MASK));
smi.addActionListener(l);
smi = shapem.add(new JMenuItem("Shape Picker", 'p'));
smi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, Event.CTRL_MASK));
smi.addActionListener(l);
menubar.add(filem);
menubar.add(shapem);
menubar.add(Box.createHorizontalGlue());
setJMenuBar(menubar);
//Create the toolbar.
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
JButton saveBtn = btnmaker("Save",SAVE, "save your paint", "Save");
JButton saveAsBtn = btnmaker("Save As",SAVE_AS, "save your paint to?","Save As");
JButton NewBtn = btnmaker("New",NEW,"new paint","New");
JButton colorbtn = btnmaker("Color",color,"choose color","Color");
colorbtn.setToolTipText("Click this button to select colors.");
colorbtn.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg) {
selectColor();
}
});
RadioListener myListener = new RadioListener();
JRadioButton ovalShape = new JRadioButton(oval);
ovalShape.addActionListener(myListener);
ovalShape.setMnemonic(KeyEvent.VK_A);
ovalShape.setActionCommand(oval);
ovalShape.setSelected(true);
add(ovalShape);
JRadioButton rectangleShape = new JRadioButton(rectangle);
rectangleShape.addActionListener(myListener);
rectangleShape.setMnemonic(KeyEvent.VK_A);
rectangleShape.setActionCommand(rectangle);
rectangleShape.setSelected(true);
add(rectangleShape);
JRadioButton squareShape = new JRadioButton(square);
squareShape.addActionListener(myListener);
squareShape.setMnemonic(KeyEvent.VK_A);
squareShape.setActionCommand(square);
squareShape.setSelected(true);
add(squareShape);
JRadioButton lineShape = new JRadioButton(line);
lineShape.addActionListener(myListener);
lineShape.setMnemonic(KeyEvent.VK_B);
lineShape.setActionCommand(line);
add(lineShape);
ButtonGroup group = new ButtonGroup();
group.add(ovalShape);
group.add(lineShape);
group.add(rectangleShape);
group.add(squareShape);
JToolBar toolBar = new JToolBar("File");
JToolBar toolBar2 = new JToolBar("Shape",JToolBar.VERTICAL);
JToolBar toolbar3 = new JToolBar("colors",JToolBar.VERTICAL);
addButtons(toolBar,saveBtn);
addButtons(toolBar,saveAsBtn);
addButtons(toolBar,NewBtn);
addRadioButtons(toolBar2,ovalShape);
addRadioButtons(toolBar2,lineShape);
addRadioButtons(toolBar2,rectangleShape);
addRadioButtons(toolBar2,squareShape);
addButtons(toolbar3,colorbtn);
panel.add(toolBar);
panel2.add(toolBar2);
panel2.add(toolbar3);
content.add(panel, BorderLayout.NORTH);
content.add(panel2, BorderLayout.WEST);
}
}
DrawPad类:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JComponent;
public class DrawPad extends JComponent{
Image image;
//this is gonna be your image that you draw on
Graphics2D graphics2D;
Shape shape;
//this is what we'll be using to draw on
int currentX, currentY, oldX, oldY;
//these are gonna hold our mouse coordinates
String currentShape;
public String getCurrentShape() {
return currentShape;
}
public void setCurrentShape(String currentShape) {
this.currentShape = currentShape;
}
//Now for the constructors
public DrawPad(){
setDoubleBuffered(false);
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
if(currentShape != null){
if(currentShape == "rectangle"){
shape = new Rectangle();
}else if(currentShape == "oval"){
shape = new Oval();
}else if(currentShape == "line"){
shape = new Line();
}else{
shape = new Square();
}
shape.setPoint1(e.getPoint());
shape.setColor(Color.black);
}
}
});
//if the mouse is pressed it sets the oldX & oldY
//coordinates as the mouses x & y coordinates
addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
shape.setPoint2(e.getPoint());
}
});
}
public void paintComponent(Graphics g){
//shape.Draw(g);
if(image == null){
image = createImage(getSize().width, getSize().height);
graphics2D = (Graphics2D)image.getGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
clear();
}
g.drawImage(image, 0, 0, null);
}
//this is the painting bit
//if it has nothing on it then
//it creates an image the size of the window
//sets the value of Graphics as the image
//sets the rendering
//runs the clear() method
//then it draws the image
public void clear(){
graphics2D.setPaint(Color.white);
graphics2D.fillRect(0, 0, getSize().width, getSize().height);
graphics2D.setPaint(Color.black);
repaint();
}
}
这是我期待的画家计划:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JComponent;
class PadDraw extends JComponent{
Image image;
//this is gonna be your image that you draw on
Graphics2D graphics2D;
//this is what we'll be using to draw on
int currentX, currentY, oldX, oldY;
//these are gonna hold our mouse coordinates
//Now for the constructors
public PadDraw(){
setDoubleBuffered(false);
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
oldX = e.getX();
oldY = e.getY();
}
});
//if the mouse is pressed it sets the oldX & oldY
//coordinates as the mouses x & y coordinates
addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
currentX = e.getX();
currentY = e.getY();
if(graphics2D != null)
graphics2D.drawLine(oldX, oldY, currentX, currentY);
repaint();
oldX = currentX;
oldY = currentY;
}
});
//while the mouse is dragged it sets currentX & currentY as the mouses x and y
//then it draws a line at the coordinates
//it repaints it and sets oldX and oldY as currentX and currentY
}
public void paintComponent(Graphics g){
if(image == null){
image = createImage(getSize().width, getSize().height);
graphics2D = (Graphics2D)image.getGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
clear();
}
g.drawImage(image, 0, 0, null);
}
//this is the painting bit
//if it has nothing on it then
//it creates an image the size of the window
//sets the value of Graphics as the image
//sets the rendering
//runs the clear() method
//then it draws the image
public void clear(){
graphics2D.setPaint(Color.white);
graphics2D.fillRect(0, 0, getSize().width, getSize().height);
graphics2D.setPaint(Color.black);
repaint();
}
//this is the clear
//it sets the colors as white
//then it fills the window with white
//thin it sets the color back to black
public void red(){
graphics2D.setPaint(Color.red);
repaint();
}
//this is the red paint
public void black(){
graphics2D.setPaint(Color.black);
repaint();
}
//black paint
public void magenta(){
graphics2D.setPaint(Color.magenta);
repaint();
}
//magenta paint
public void blue(){
graphics2D.setPaint(Color.blue);
repaint();
}
//blue paint
public void green(){
graphics2D.setPaint(Color.green);
repaint();
}
//green paint
}
绘图程序的主要方法:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class paint{
public static void main(String[] args){
Icon iconB = new ImageIcon("blue.gif");
//the blue image icon
Icon iconM = new ImageIcon("magenta.gif");
//magenta image icon
Icon iconR = new ImageIcon("red.gif");
//red image icon
Icon iconBl = new ImageIcon("black.gif");
//black image icon
Icon iconG = new ImageIcon("green.gif");
//finally the green image icon
//These will be the images for our colors.
JFrame frame = new JFrame("Paint It");
//Creates a frame with a title of "Paint it"
Container content = frame.getContentPane();
//Creates a new container
content.setLayout(new BorderLayout());
//sets the layout
final PadDraw drawPad = new PadDraw();
//creates a new padDraw, which is pretty much the paint program
content.add(drawPad, BorderLayout.CENTER);
//sets the padDraw in the center
JPanel panel = new JPanel();
//creates a JPanel
panel.setPreferredSize(new Dimension(32, 68));
panel.setMinimumSize(new Dimension(32, 68));
panel.setMaximumSize(new Dimension(32, 68));
//This sets the size of the panel
JButton clearButton = new JButton("Clear");
//creates the clear button and sets the text as "Clear"
clearButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
drawPad.clear();
}
});
//this is the clear button, which clears the screen. This pretty
//much attaches an action listener to the button and when the
//button is pressed it calls the clear() method
JButton redButton = new JButton(iconR);
//creates the red button and sets the icon we created for red
redButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
drawPad.red();
}
});
//when pressed it will call the red() method. So on and so on =]
JButton blackButton = new JButton(iconBl);
//same thing except this is the black button
blackButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
drawPad.black();
}
});
JButton magentaButton = new JButton(iconM);
//magenta button
magentaButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
drawPad.magenta();
}
});
JButton blueButton = new JButton(iconB);
//blue button
blueButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
drawPad.blue();
}
});
JButton greenButton = new JButton(iconG);
//green button
greenButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
drawPad.green();
}
});
blackButton.setPreferredSize(new Dimension(16, 16));
magentaButton.setPreferredSize(new Dimension(16, 16));
redButton.setPreferredSize(new Dimension(16, 16));
blueButton.setPreferredSize(new Dimension(16, 16));
greenButton.setPreferredSize(new Dimension(16,16));
//sets the sizes of the buttons
panel.add(greenButton);
panel.add(blueButton);
panel.add(magentaButton);
panel.add(blackButton);
panel.add(redButton);
panel.add(clearButton);
//adds the buttons to the panel
content.add(panel, BorderLayout.WEST);
//sets the panel to the left
frame.setSize(500, 500);
//sets the size of the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//makes it so you can close
frame.setVisible(true);
//makes it so you can see it
}
}
答案 0 :(得分:0)
维护对Graphics
上下文的引用并在绘制周期之外进行绘制。永远不要保留对您自己未创建的Graphics
上下文的引用。永远不要在Graphics
方法调用之外绘制到组件的paintComponent
上下文。绘画具有破坏性,任何绘制在绘画周期之外的Graphics
上下文的内容都将丢失
打破油漆链。除非你有充分的理由不这样做,否则你应该在执行任何自定义绘画之前调用super.paintComponent
。此外paintComponent
永远不需要公开,任何人都不应该称之为......
currentShape == "line"
不是String
比较的工作原理。请改用"line".equals(currentShape)
...
setDoubleBuffered(false);
...这只是意味着你需要做更多工作...绘制到传递给Graphics
的{{1}}上下文,当它传递给paintComponent方法时......
小心你要添加什么......
paintComponent
Container content = getContentPane();
content.setLayout(new BorderLayout());
final DrawPad drawPad = new DrawPad();
content.add(drawPad, BorderLayout.CENTER);
//...
//Create the toolbar.
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
//...
// What do you think this is been added to?
add(ovalShape);
//...
// What do you think this is been added to?
add(rectangleShape);
//...
// What do you think this is been added to?
add(squareShape);
//...
// What do you think this is been added to?
add(lineShape);
//...
panel.add(toolBar);
panel2.add(toolBar2);
panel2.add(toolbar3);
content.add(panel, BorderLayout.NORTH);
content.add(panel2, BorderLayout.WEST);
只会显示添加到其中任意五个可用广告位中的最后一项...在这种情况下,BorderLayout
...
原型问题的小元素,了解工作如何孤立,然后弄清楚如何将它们插入一大组功能......