I'm new to Stackoverflow and tried to follow the rules as much as possible. I haven't been able to solve this problem for hours. When I start the program it seldom starts strangely:
properly started: correct image:
not properly started: white screen:
If you see an error in the code and help me fix it I would appreciate it. any correction
public class MainClass extends JPanel implements Runnable, MouseListener {
enum MenuState {
xMenu1, xMenu2;
}
private MenuState menuState = MenuState.xMenu1;
JFrame frame;
private Image bgImage, playButtonImage, backButtonImage;
private Rectangle playButton, backButton;
public MainClass() {
frame = new JFrame("TEST");
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.BLACK);
frame.setFocusable(true);
frame.addMouseListener(this);
frame.add(this);
try {
bgImage = ImageIO.read(getClass().getResourceAsStream("/Data/background.png"));
playButtonImage = ImageIO.read(getClass().getResource("/Data/playButton2.png"));
backButtonImage = ImageIO.read(getClass().getResource("/Data/backButton.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
playButton = new Rectangle(900, 400, 214, 78);
backButton = new Rectangle(5, 5, 136, 92);
Thread thread = new Thread(this);
thread.start();
System.out.println("thread started");
}
public static void main(String[] args) {
new MainClass();
}
#Override
public void run() {
while (true) {
System.out.println("run method started");
if (menuState == menuState.xMenu1) {
} else if (menuState == menuState.xMenu2) {
}
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void paint(Graphics g) {
if (menuState == menuState.xMenu1) {
g.drawImage(playButtonImage, playButton.x, playButton.y, this); // THIS IS THE 77th LINE
} else if (menuState == menuState.xMenu2) {
g.drawImage(bgImage, 0, 0, this);
g.drawImage(backButtonImage, backButton.x, backButton.y, this);
}
}
#Override
public void mousePressed(MouseEvent e) {
if (menuState == menuState.xMenu1) {
if (playButton.intersects(e.getX(), e.getY(), 1, 1)) {
menuState = menuState.xMenu2;
}
} else if (menuState == menuState.xMenu2) {
if (backButton.intersects(e.getX(), e.getY(), 1, 1)) {
menuState = menuState.xMenu1;
}
}
}
}
I want to make a paint program.
When the user clicks the text button, then the user click the canvas the user can input the text they want in the clicked location.
What can I use to make that happen?
When i use drawstring, I can put the pre-defined text and user click location
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Font font = new Font("Serif", Font.PLAIN, 40);
g2.setFont(font);
g2.drawString("text", x, y);
How can I change "text" to what the user inputs from keyboard?
My MainPanel Code (For View Mostly)
public class MainPanel extends JPanel implements ActionListener, ChangeListener {
private JButton button1, button2, button3, button4, button5, button6, button7, button8, button9, button10, button11, button12, activeButton;
private ButtonGroup buttonGroup;
private DrawPanel drawPanel;
private boolean insertedDrawPanel;
private JSlider slider;
private JTextField valueField;
private int jSliderMin, jSliderMax, jSliderInit;
private Toolkit toolkit;
private Image cursorImage;
private Point cursorHotSpot;
private Cursor fillCursor, penCursor, eraserCursor, lineCursor, rectCursor, ovalCursor, triangleCursor, starCursor;
private Color color1, color2;
public MainPanel()
{
try {
javax.swing.UIManager.setLookAndFeel( javax.swing.UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
setPreferredSize(new Dimension(1280, 720));
initiateComponent();
buildLayout();
registerListener();
checkDrawPanel();
}
public JPanel getDrawPanel() {
return drawPanel;
}
public void initiateComponent()
{
int width=54;
int height=48;
jSliderMin=1;
jSliderMax=100;
jSliderInit=1;
insertedDrawPanel=false;
BufferedImage buttonIcon;
activeButton= new JButton();
button1 = new JButton();
button1.setPreferredSize(new Dimension(width, height));
button1.setName("");
button2 = new JButton();
button2.setPreferredSize(new Dimension(width, height));
button2.setName("");
button3 = new JButton();
button3.setPreferredSize(new Dimension(width, height));
button4 = new JButton("");
button4.setPreferredSize(new Dimension(width, height));
button5 = new JButton("");
button5.setPreferredSize(new Dimension(width, height));
button6 = new JButton("");
button6.setPreferredSize(new Dimension(width, height));
button7 = new JButton("1");
button7.setPreferredSize(new Dimension(width, height));
button8 = new JButton("2");
button8.setPreferredSize(new Dimension(width, height));
button9 = new JButton("");
button9.setPreferredSize(new Dimension(width, height));
button10 = new JButton("");
button10.setPreferredSize(new Dimension(width, height));
button11 = new JButton("");
button11.setPreferredSize(new Dimension(width, height));
button12 = new JButton("");
button12.setPreferredSize(new Dimension(width, height));
public void buildLayout()
{
this.setLayout(new BorderLayout());
JPanel buttonPanel = new JPanel();
String colSizes = "20px, 54px, 10px, 54px, 20px";
String rowSizes = "20px, 48px, 20px, 48px, 20px, 48px, 20px, 48px, 20px, 200px, 48px, 48px, 20px, 48px";
FormLayout layout = new FormLayout(colSizes, rowSizes);
buttonPanel.setLayout(layout);
CellConstraints cc = new CellConstraints();
buttonPanel.add(button1, cc.xy(2, 2));
buttonPanel.add(button2, cc.xy(4, 2));
buttonPanel.add(button3, cc.xy(2, 4));
buttonPanel.add(button4, cc.xy(4, 4));
buttonPanel.add(button5, cc.xy(2, 6));
buttonPanel.add(button6, cc.xy(4, 6));
buttonPanel.add(button7, cc.xy(2, 8));
buttonPanel.add(button8, cc.xy(4, 8));
buttonPanel.add(slider, cc.xywh(2, 10, 3, 1));
buttonPanel.add(valueField, cc.xyw(2, 11, 3));
buttonPanel.add(button9, cc.xy(2, 12));
buttonPanel.add(button10, cc.xy(4, 12));
buttonPanel.add(button11, cc.xy(2, 14));
buttonPanel.add(button12, cc.xy(4, 14));
this.add(buttonPanel, BorderLayout.WEST);
}
public void registerListener()
{
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
button5.addActionListener(this);
button6.addActionListener(this);
button7.addActionListener(this);
button8.addActionListener(this);
button9.addActionListener(this);
button10.addActionListener(this);
button11.addActionListener(this);
button12.addActionListener(this);
slider.addChangeListener(this);
}
public void addDrawPanel(DrawPanel panel)
{
drawPanel=panel;
JPanel centerPanel = new JPanel();
String colSizes = "20px, pref,20px";
String rowSizes = "20px, pref,20px";
FormLayout layout = new FormLayout(colSizes, rowSizes);
centerPanel.setLayout(layout);
CellConstraints cc = new CellConstraints();
centerPanel.add(drawPanel, cc.xy(2, 2));
this.add(centerPanel, BorderLayout.CENTER);
insertedDrawPanel=true;
checkDrawPanel();
}
public void addOpenedImage(Image img)
{
drawPanel = new DrawPanel();
drawPanel.setPreferredSize(new Dimension(img.getWidth(null),img.getHeight(null)));
drawPanel.setBgImg(img);
JPanel centerPanel = new JPanel();
String colSizes = "20px, pref,20px";
String rowSizes = "20px, pref,20px";
FormLayout layout = new FormLayout(colSizes, rowSizes);
centerPanel.setLayout(layout);
CellConstraints cc = new CellConstraints();
centerPanel.add(drawPanel, cc.xy(2, 2));
this.add(centerPanel, BorderLayout.CENTER);
insertedDrawPanel=true;
checkDrawPanel();
}
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource().equals(button1))
{
activeButton=button1;
this.setCursor(penCursor);
resetButtonChanges();
drawPanel.setPenActive(true);
}
if(ae.getSource().equals(button2))
{
activeButton=button2;
this.setCursor(lineCursor);
resetButtonChanges();
drawPanel.setLineActive(true);
}
if(ae.getSource().equals(button3))
{
activeButton=button3;
this.setCursor(eraserCursor);
resetButtonChanges();
drawPanel.setEraserActive(true);
}
if(ae.getSource().equals(button4))
{
activeButton=button4;
resetButtonChanges();
drawPanel.setTextActive(true);
}
if(ae.getSource().equals(button7))
{
activeButton= button7;
resetButtonChanges();
color1 = JColorChooser.showDialog(null, "Pick your Background Color", color1);
if(color1!=null)
{
drawPanel.setBackground(color1);
}
}
if(ae.getSource().equals(button8))
{
activeButton= button8;
resetButtonChanges();
color2 = JColorChooser.showDialog(null, "Pick your Stroke / Shape Color", color2);
if(color2!=null)
{
drawPanel.setStrokecolor(color2);
}
}
if(ae.getSource().equals(button9))
{
activeButton=button9;
this.setCursor(rectCursor);
resetButtonChanges();
drawPanel.setRectActive(true);
}
if(ae.getSource().equals(button10))
{
activeButton=button10;
this.setCursor(ovalCursor);
resetButtonChanges();
drawPanel.setOvalActive(true);
}
if(ae.getSource().equals(button11))
{
activeButton=button11;
this.setCursor(triangleCursor);
resetButtonChanges();
drawPanel.setTriangleActive(true);
}
if(ae.getSource().equals(button12))
{
activeButton=button12;
this.setCursor(starCursor);
resetButtonChanges();
drawPanel.setStarActive(true);
}
}
public void resetButtonChanges()
{
if(activeButton!=button1)
{
drawPanel.setPenActive(false);
}
if(activeButton!=button2)
{
drawPanel.setLineActive(false);
}
if(activeButton!=button3)
{
drawPanel.setEraserActive(false);
}
if(activeButton!=button4)
{
drawPanel.setTextActive(false);
}
if(activeButton!=button9)
{
drawPanel.setRectActive(false);
}
if(activeButton!=button10)
{
drawPanel.setOvalActive(false);
}
if(activeButton!=button11)
{
drawPanel.setTriangleActive(false);
}
if(activeButton!=button12)
{
drawPanel.setStarActive(false);
}
}
public void checkDrawPanel()
{
if(insertedDrawPanel==false)
{
button1.setEnabled(false);
button2.setEnabled(false);
button3.setEnabled(false);
button4.setEnabled(false);
button5.setEnabled(false);
button6.setEnabled(false);
button7.setEnabled(false);
button8.setEnabled(false);
button9.setEnabled(false);
button10.setEnabled(false);
button11.setEnabled(false);
button12.setEnabled(false);
slider.setEnabled(false);
}
else
{
button1.setEnabled(true);
button2.setEnabled(true);
button3.setEnabled(true);
button4.setEnabled(true);
button5.setEnabled(true);
button6.setEnabled(true);
button7.setEnabled(true);
button8.setEnabled(true);
button9.setEnabled(true);
button10.setEnabled(true);
button11.setEnabled(true);
button12.setEnabled(true);
slider.setEnabled(true);
}
}
#Override
public void stateChanged(ChangeEvent ce) {
if(ce.getSource().equals(slider))
{
drawPanel.setStrokevalue(slider.getValue());
valueField.setText(String.valueOf(slider.getValue()));
}
if(ce.getSource().equals(button7))
{
button7.setBackground(color1);
button7.setForeground(color2);
}
if(ce.getSource().equals(button8))
{
button8.setBackground(color2);
button8.setForeground(color1);
}
}
}
My DrawPanel Code
public class DrawPanel extends JPanel implements ActionListener, FocusListener, DocumentListener, MouseListener, MouseMotionListener{
private boolean penActive ,eraserActive, lineActive, rectActive, ovalActive, triangleActive, starActive, textActive, isDrag, isReleased;
private int x, y , xDrag, yDrag, xRelease, yRelease, strokevalue;
private Color strokecolor ,dragColor;
private Vector<int[]> allShapes;
private int[] dragShape;
private Vector<Color> shapeColor;
private Vector<String> type;
private String dragType;
private JTextField text;
private Image bgImg;
public boolean isPenActive() {
return penActive;
}
public void setPenActive(boolean penActive) {
this.penActive = penActive;
}
public boolean isEraserActive() {
return eraserActive;
}
public void setEraserActive(boolean eraserActive) {
this.eraserActive = eraserActive;
}
public boolean isTriangleActive() {
return triangleActive;
}
public void setTriangleActive(boolean triangleActive) {
this.triangleActive = triangleActive;
}
public boolean isLineActive() {
return lineActive;
}
public void setLineActive(boolean lineActive) {
this.lineActive = lineActive;
}
public int getStrokevalue() {
return strokevalue;
}
public void setStrokevalue(int strokevalue) {
this.strokevalue = strokevalue;
}
public Color getStrokecolor() {
return strokecolor;
}
public void setStrokecolor(Color strokecolor) {
this.strokecolor = strokecolor;
}
public boolean isRectActive() {
return rectActive;
}
public void setRectActive(boolean rectActive) {
this.rectActive = rectActive;
}
public boolean isOvalActive() {
return ovalActive;
}
public void setOvalActive(boolean ovalActive) {
this.ovalActive = ovalActive;
}
public boolean isStarActive() {
return starActive;
}
public void setStarActive(boolean starActive) {
this.starActive = starActive;
}
public boolean isTextActive() {
return textActive;
}
public void setTextActive(boolean textActive) {
this.textActive = textActive;
}
public Image getBgImg() {
return bgImg;
}
public void setBgImg(Image bgImg) {
this.bgImg = bgImg;
}
public DrawPanel()
{
setFocusable(true);
setBackground(Color.white);
initiateComponents();
addMouseMotionListener(this);
addMouseListener(this);
}
public void initiateComponents()
{
allShapes=new Vector<int[]>();
shapeColor=new Vector<Color>();
type=new Vector<String>();
eraserActive = false;
penActive = false;
lineActive = false;
rectActive = false;
ovalActive = false;
triangleActive = false;
starActive = false;
strokevalue=1;
strokecolor=Color.BLACK;
}
#Override
public void mouseClicked(MouseEvent me) {
if (me.getClickCount() == 2)
text.setEditable( true );
}
#Override
public void mousePressed(MouseEvent me) {
x = me.getX();
y = me.getY();
if(me.getClickCount() == 1)
{
this.requestFocusInWindow();
}
if(me.getClickCount() == 2)
{
System.out.println("asd");
text.setLocation(me.getPoint());
this.add(text);
text.requestFocusInWindow();
text.selectAll();
repaint();
}
}
#Override
public void mouseReleased(MouseEvent me) {
isDrag=false;
isReleased=true;
xRelease=me.getX();
yRelease=me.getY();
repaint();
}
#Override
public void mouseEntered(MouseEvent me) {
}
#Override
public void mouseExited(MouseEvent me) {
}
#Override
public void mouseDragged(MouseEvent me) {
isDrag=true;
isReleased=false;
xDrag=me.getX();
yDrag=me.getY();
repaint();
}
#Override
public void mouseMoved(MouseEvent me) {
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if(penActive==true)
{
int[]coordinates=new int[5];
if(isDrag)
{
coordinates[0]=x;
coordinates[1]=y;
coordinates[2]=xDrag;
coordinates[3]=yDrag;
coordinates[4]=strokevalue;
allShapes.add(coordinates);
shapeColor.add(strokecolor);
type.add("Pen");
x=xDrag;
y=yDrag;
}
}
else if(eraserActive==true)
{
int[]coordinates=new int[5];
if(isDrag)
{
coordinates[0]=x;
coordinates[1]=y;
coordinates[2]=xDrag;
coordinates[3]=yDrag;
coordinates[4]=strokevalue;
allShapes.add(coordinates);
shapeColor.add(this.getBackground());
type.add("Eraser");
x=xDrag;
y=yDrag;
}
}
else if(lineActive==true)
{
int[]coordinates=new int[5];
if(isDrag)
{
dragShape=new int[5];
dragShape[0]=x;
dragShape[1]=y;
dragShape[2]=xDrag;
dragShape[3]=yDrag;
dragShape[4]=strokevalue;
dragColor=strokecolor;
dragType="Line";
}
if(isReleased)
{
dragShape=null;
coordinates[0]=x;
coordinates[1]=y;
coordinates[2]=xDrag;
coordinates[3]=yDrag;
coordinates[4]=strokevalue;
allShapes.add(coordinates);
shapeColor.add(strokecolor);
type.add("Line");
}
}
else if(textActive==true)
{
int[]coordinates=new int[3];
if(isReleased)
{
dragShape=null;
coordinates[0]=x;
coordinates[1]=y;
coordinates[2]=strokevalue;
allShapes.add(coordinates);
shapeColor.add(strokecolor);
type.add("Text");
}
}
else if(triangleActive==true)
{
int[]coordinates=new int[4];
if(isDrag)
{
dragShape=new int[4];
dragShape[0]=x;
dragShape[1]=y;
dragShape[2]=-y+yDrag;
dragShape[3]=strokevalue;
dragColor=strokecolor;
dragType="Triangle";
}
if(isReleased)
{
dragShape=null;
coordinates[0]=x;
coordinates[1]=y;
coordinates[2]=-y+yDrag;
coordinates[3]=strokevalue;
allShapes.add(coordinates);
shapeColor.add(strokecolor);
type.add("Triangle");
}
}
else if(starActive==true)
{
int[]coordinates=new int[4];
if(isDrag)
{
dragShape=new int[4];
dragShape[0]=x;
dragShape[1]=y;
dragShape[2]=-y+yDrag;
dragShape[3]=strokevalue;
dragColor=strokecolor;
dragType="Star";
}
if(isReleased)
{
dragShape=null;
coordinates[0]=x;
coordinates[1]=y;
coordinates[2]=-y+yDrag;
coordinates[3]=strokevalue;
allShapes.add(coordinates);
shapeColor.add(strokecolor);
type.add("Star");
}
}
else if(rectActive==true)
{
int[]coordinates=new int[5];
if(isDrag)
{
dragShape=new int[5];
dragShape[0]=x;
dragShape[1]=y;
dragShape[2]=xDrag;
dragShape[3]=yDrag;
dragShape[4]= strokevalue;
dragColor=strokecolor;
dragType="Rectangle";
}
if(isReleased)
{
dragShape=null;
coordinates[0]=x;
coordinates[1]=y;
coordinates[2]=xDrag;
coordinates[3]=yDrag;
coordinates[4]=strokevalue;
allShapes.add(coordinates);
shapeColor.add(strokecolor);
type.add("Rectangle");
}
}
else if(ovalActive==true)
{
int[]coordinates=new int[4];
if(isDrag)
{
dragShape=new int[4];
dragShape[0]=x;
dragShape[1]=y;
dragShape[2]=-y+yDrag;
dragShape[3]=strokevalue;
dragColor=strokecolor;
dragType="Oval";
}
if(isReleased)
{
dragShape=null;
coordinates[0]=x;
coordinates[1]=y;
coordinates[2]=-y+yDrag;
coordinates[3]=strokevalue;
allShapes.add(coordinates);
shapeColor.add(strokecolor);
type.add("Oval");
}
}
if(bgImg!=null)
{
g2.drawImage(bgImg, 0, 0, null);
}
for(int a=0;a<allShapes.size();a++)
{
if(type.get(a).equals("Pen")||type.get(a).equals("Eraser")||type.get(a).equals("Line"))
{
int[]coordinates=allShapes.get(a);
Color color=shapeColor.get(a);
g2.setStroke(new BasicStroke(coordinates[4]));
g2.setPaint(color);
g2.drawLine(coordinates[0], coordinates[1], coordinates[2], coordinates[3]);
}
else if(type.get(a).equals("Text"))
{
text = new JTextField("asd");
Font font = new Font("Serif", Font.PLAIN, 40);
g2.setFont(font);
}
else if(type.get(a).equals("Triangle"))
{
int[]coordinates=allShapes.get(a);
Point2D b= new Point2D.Double(coordinates[0], coordinates[1]);
Triangle triangle = new Triangle(b,coordinates[2]);
g2.setStroke(new BasicStroke(coordinates[3]));
g2.setPaint(dragColor);
g2.draw(triangle);
}
else if(type.get(a).equals("Star"))
{
int[]coordinates=allShapes.get(a);
Point2D b= new Point2D.Double(coordinates[0], coordinates[1]);
Star star = new Star(b,coordinates[2], coordinates[2]);
g2.setStroke(new BasicStroke(coordinates[3]));
g2.setPaint(dragColor);
g2.draw(star);
}
else if(type.get(a).equals("Rectangle"))
{
int[]coordinates=allShapes.get(a);
Point2D b=new Point2D.Double(coordinates[0], coordinates[1]);
Point2D c=new Point2D.Double(coordinates[2], coordinates[3]);
Rectangle rectangle = new Rectangle(b,c);
g2.setStroke(new BasicStroke(coordinates[4]));
g2.setPaint(dragColor);
g2.draw(rectangle);
}
else if(type.get(a).equals("Oval"))
{
int[]coordinates=allShapes.get(a);
Point2D b= new Point2D.Double(coordinates[0], coordinates[1]);
Circle oval = new Circle(b,coordinates[0], coordinates[1], coordinates[2]);
g2.setStroke(new BasicStroke(coordinates[3]));
g2.setPaint(dragColor);
g2.draw(oval);
}
}
if(dragShape!=null)
{
if(dragType.equals("Line"))
{
g2.setStroke(new BasicStroke(dragShape[4]));
g2.setPaint(dragColor);
g2.drawLine(dragShape[0], dragShape[1], dragShape[2], dragShape[3]);
}
else if(dragType.equals("Triangle"))
{
Point2D a= new Point2D.Double(dragShape[0], dragShape[1]);
Triangle triangle = new Triangle(a,dragShape[2]);
g2.setStroke(new BasicStroke(dragShape[3]));
g2.setPaint(dragColor);
g2.draw(triangle);
}
else if(dragType.equals("Star"))
{
Point2D a= new Point2D.Double(dragShape[0], dragShape[1]);
Star star = new Star(a,dragShape[2],dragShape[2]);
g2.setStroke(new BasicStroke(dragShape[3]));
g2.setPaint(dragColor);
g2.draw(star);
}
else if(dragType.equals("Rectangle")){
Point2D b=new Point2D.Double(dragShape[0], dragShape[1]);
Point2D c=new Point2D.Double(dragShape[2], dragShape[3]);
Rectangle rectangle = new Rectangle(b,c);
g2.setStroke(new BasicStroke(dragShape[4]));
g2.setPaint(dragColor);
g2.draw(rectangle);
}
else if(dragType.equals("Oval"))
{
Point2D a= new Point2D.Double(dragShape[0], dragShape[1]);
Circle oval = new Circle(a,dragShape[0],dragShape[1], dragShape[2]);
g2.setStroke(new BasicStroke(dragShape[3]));
g2.setPaint(dragColor);
g2.draw(oval);
}
}
}
#Override
public void focusGained(FocusEvent e) {
}
#Override
public void focusLost(FocusEvent e) {
text.setEditable(false);
}
#Override
public void insertUpdate(DocumentEvent e) {
text.setSize(getPreferredSize());
}
#Override
public void removeUpdate(DocumentEvent e) {
text.setSize(getPreferredSize());
}
#Override
public void changedUpdate(DocumentEvent e) {
}
#Override
public void actionPerformed(ActionEvent e) {
text.setEditable(false);
}
}
Here is an example that uses a JTextField to enter text at the location.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class InvisibleTextField extends JTextField
implements ActionListener, FocusListener, MouseListener, DocumentListener
{
public InvisibleTextField()
{
setOpaque( false );
setColumns( 1 );
// setBorder( null );
setSize( getPreferredSize() );
setColumns( 0 );
addActionListener( this );
addFocusListener( this );
addMouseListener( this );
getDocument().addDocumentListener( this );
}
// Implement ActionListener
public void actionPerformed(ActionEvent e)
{
setEditable( false );
}
// Implement FocusListener
public void focusLost(FocusEvent e)
{
setEditable( false );
}
public void focusGained(FocusEvent e) {}
// Implement MouseListener
public void mouseClicked( MouseEvent e )
{
if (e.getClickCount() == 2)
setEditable( true );
}
public void mouseEntered( MouseEvent e ) {}
public void mouseExited( MouseEvent e ) {}
public void mousePressed( MouseEvent e ) {}
public void mouseReleased( MouseEvent e ) {}
// Implement DocumentListener
public void insertUpdate(DocumentEvent e)
{
updateSize();
}
public void removeUpdate(DocumentEvent e)
{
updateSize();
}
public void changedUpdate(DocumentEvent e) {}
private void updateSize()
{
setSize( getPreferredSize() );
}
public static void main(String[] args)
{
JPanel panel = new JPanel();
panel.setFocusable( true );
panel.setLayout( null );
panel.addMouseListener( new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
JPanel panel = (JPanel)e.getSource();
if (e.getClickCount() == 1)
{
panel.requestFocusInWindow();
}
if (e.getClickCount() == 2)
{
InvisibleTextField tf = new InvisibleTextField();
tf.setLocation(e.getPoint());
panel.add( tf );
tf.requestFocusInWindow();
}
}
});
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add(new JLabel("Double Click to Add Text"), BorderLayout.NORTH);
frame.add(panel);
frame.setSize(650, 300);
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
You can edit the text at any time by double clicking on the text.
I am programming a small paint application, the problem is, when I clic on my Menu and then move the mouse out and clic on the panel to continiue painting, the panel erases everything I painted and changes the background too ... here's my code :
Frame's Code :
public class Ardoise extends JFrame {
private JMenuBar menu = new JMenuBar();
private JToolBar toolbar = new JToolBar();
private JMenu file = new JMenu("Fichier");
private JMenu edit = new JMenu("Edition");
private JMenu about = new JMenu("About");
private JMenu shape = new JMenu("Forme du curseur");
private JMenu color = new JMenu("Couleur du curseur");
private JMenuItem clear = new JMenuItem("Effacer");
private JMenuItem quit = new JMenuItem("Quitter");
private JMenuItem rond = new JMenuItem("Rond");
private JMenuItem carre = new JMenuItem("Carre");
private JMenuItem rouge = new JMenuItem("Rouge");
private JMenuItem bleu = new JMenuItem("Bleu");
private JMenuItem noir = new JMenuItem("Noir");
private JButton rougeButton = new JButton(new ImageIcon("rouge.jpg"));
private JButton bleuButton = new JButton(new ImageIcon("bleu.jpg"));
private JButton noirButton = new JButton(new ImageIcon("noir.jpg"));
private JButton formecarreeButton = new JButton(new ImageIcon("formecarree.png"));
private JButton formerondeButton = new JButton(new ImageIcon("formeronde.png"));
private JPanel container = new JPanel();
private Panneau pan = new Panneau();
private ColorListener cListener = new ColorListener();
public Ardoise(){
this.setTitle("Paint");
this.setSize(700,500);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
initComposants();
this.setVisible(true);
}
private void initComposants(){
file.add(clear);
file.addSeparator();
file.add(quit);
file.setMnemonic('F');
clear.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,KeyEvent.CTRL_DOWN_MASK));
quit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,KeyEvent.CTRL_DOWN_MASK));
shape.add(rond);
shape.add(carre);
color.add(rouge);
color.add(bleu);
color.add(noir);
edit.add(shape);
edit.add(color);
edit.setMnemonic('E');
menu.add(file);
menu.add(edit);
toolbar.add(formecarreeButton);
toolbar.add(formerondeButton);
toolbar.addSeparator();
toolbar.add(noirButton);
toolbar.add(rougeButton);
toolbar.add(bleuButton);
pan.addMouseMotionListener(new PaintListener1());
pan.addMouseListener(new PaintListener2());
clear.addActionListener(new ClearListener());
rougeButton.addActionListener(cListener);
bleuButton.addActionListener(cListener);
noirButton.addActionListener(cListener);
container.setLayout(new BorderLayout());
container.add(toolbar,BorderLayout.NORTH);
container.add(pan,BorderLayout.CENTER);
this.setContentPane(container);
this.setJMenuBar(menu);
}
class PaintListener1 implements MouseMotionListener{
public void mouseDragged(MouseEvent e) {
pan.setx(e.getX());
pan.sety(e.getY());
pan.repaint();
}
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
class PaintListener2 implements MouseListener{
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
pan.setx(e.getX());
pan.sety(e.getY());
pan.repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
class ClearListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
pan.setClean(true);
pan.repaint();
}
}
class ColorListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getSource() == rougeButton)
pan.setColor(Color.red);
if(e.getSource() == bleuButton)
pan.setColor(Color.blue);
if(e.getSource() == noirButton)
pan.setColor(Color.black);
}
}
}
Panel's Code :
public class Panneau extends JPanel{
private int mousex=0,mousey=0;
private boolean clean=true;;
private Color color= Color.black;
public void paintComponent(Graphics g){
g.setColor(color);
draw(g);
if(clean){
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
clean=false;
}
}
private void draw(Graphics g){
g.fillOval(mousex, mousey, 10, 10);
}
public void setx(int x){
this.mousex=x;
}
public void sety(int y){
this.mousey=y;
}
public void setClean(boolean c){
this.clean = c;
}
public void setColor(Color c){
this.color=c;
}
}
the panel erases everything I painted and changes the background too ... here's my code :
You need to keep track of everything that has been painted and then repaint everything again.
See Custom Painting Approaches for the two common ways to do this:
Use a ArrayList to keep track of objects painted
Use a BufferedImage
I'm trying to capture the screen without including my application's window. To do this I first call setVisible(false), then I call the createScreenCapture method, and finally I call setVisible(true). This isn't working however and I'm still getting my applications window in the screen capture. If I add a call to sleep this seems to resolve the issue, but I know this is bad practice. What is the right way to do this?
Code:
setVisible(false);
BufferedImage screen = robot.createScreenCapture(rectScreenSize);
setVisible(true);
Have you tried to use SwingUtilities.invokeLater() and run the capture inside of the runnable passed as an argument? My guess is that the repaint performed to remove your application is performed right after the end of the current event in the AWT-EventQueue and thus invoking the call immediately still captures your window. Invoking the createCapture in a delayed event through invokeLater should fix this.
you have to delay this action by implements Swing Timer, for example
import javax.imageio.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
public class CaptureScreen implements ActionListener {
private JFrame f = new JFrame("Screen Capture");
private JPanel pane = new JPanel();
private JButton capture = new JButton("Capture");
private JDialog d = new JDialog();
private JScrollPane scrollPane = new JScrollPane();
private JLabel l = new JLabel();
private Point location;
private Timer timer1;
public CaptureScreen() {
capture.setActionCommand("CaptureScreen");
capture.setFocusPainted(false);
capture.addActionListener(this);
capture.setPreferredSize(new Dimension(300, 50));
pane.add(capture);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(pane);
f.setLocation(100, 100);
f.pack();
f.setVisible(true);
createPicContainer();
startTimer();
}
private void createPicContainer() {
l.setPreferredSize(new Dimension(700, 500));
scrollPane = new JScrollPane(l,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBackground(Color.white);
scrollPane.getViewport().setBackground(Color.white);
d.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
d.add(scrollPane);
d.pack();
d.setVisible(false);
d.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
f.setVisible(true);
}
public void windowClosed(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
});
}
private void startTimer() {
timer1 = new Timer(1000, new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
capture.doClick();
f.setVisible(false);
}
});
}
});
timer1.setDelay(500);
timer1.setRepeats(false);
timer1.start();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("CaptureScreen")) {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // gets the screen size
Robot r;
BufferedImage bI;
try {
r = new Robot(); // creates robot not sure exactly how it works
Thread.sleep(1000); // waits 1 second before capture
bI = r.createScreenCapture(new Rectangle(dim)); // tells robot to capture the screen
showPic(bI);
saveImage(bI);
} catch (AWTException e1) {
e1.printStackTrace();
} catch (InterruptedException e2) {
e2.printStackTrace();
}
}
}
private void saveImage(BufferedImage bI) {
try {
ImageIO.write(bI, "JPG", new File("screenShot.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
private void showPic(BufferedImage bI) {
ImageIcon pic = new ImageIcon(bI);
l.setIcon(pic);
l.revalidate();
l.repaint();
d.setVisible(false);
//location = f.getLocationOnScreen();
//int x = location.x;
//int y = location.y;
//d.setLocation(x, y + f.getHeight());
d.setLocation(150, 150);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
d.setVisible(true);
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
CaptureScreen cs = new CaptureScreen();
}
});
}
}