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.
Related
It hasn't been long since I started developing Java.
This code was run by Eclipse. When I run this code javaSE-1.8, only mimage appears, and when I remove and run 'paintComponenets(g);',quit button and start button appear, and mimage disappears. I think 'paintComponents' is the problem. How do I solve this problem
public class Mainscreen extends JFrame {
private Image screenImage;
private Graphics screenGraphics;
private Image mImage = new
ImageIcon(Main.class.getResource("../img/unnamed.jpg")).getImage();
private ImageIcon quitEnter = new
ImageIcon(Main.class.getResource("../img/startButtonBasic1.jpg"));
private ImageIcon quitBasic = new
ImageIcon(Main.class.getResource("../img/startButtonEntered1.jpg"));
private ImageIcon startEnter = new
ImageIcon(Main.class.getResource("../img/startButtonBasic.jpg"));
private ImageIcon startBasic = new
ImageIcon(Main.class.getResource("../img/startButtonEntered.jpg"));
private JButton quitButton = new JButton(quitBasic);
private JButton startButton = new JButton(startBasic);
public Mainscreen() {
setTitle("Main");
setSize(900, 900);
setResizable(false);
setLocationRelativeTo(null);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
startButton.setBounds(40 ,200, 400, 100);
startButton.setBorderPainted(false);
startButton.setContentAreaFilled(false);
startButton.setFocusPainted(false);
startButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
startButton.setIcon(startEnter);
startButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
public void mouseExited(MouseEvent e) {
startButton.setIcon(startBasic);
startButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
public void MousePressed(MouseEvent e) {
//select
}
});
add(startButton);
quitButton.setBounds(40, 500, 400, 100);
quitButton.setBorderPainted(false);
quitButton.setContentAreaFilled(false);
quitButton.setFocusPainted(false);
quitButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
quitButton.setIcon(quitEnter);
quitButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
public void mouseExited(MouseEvent e) {
quitButton.setIcon(quitBasic);
quitButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
public void MousePressed(MouseEvent e) {
try {
Thread.sleep(1000);
}
catch(InterruptedException ex){
ex.printStackTrace();
}
System.exit(0);
}
});
add(quitButton);
}
public void paint(Graphics g) {
screenImage = createImage(Main.SCREEN_WIDTH, Main.SCREEN_HEIGHT);
screenGraphics = screenImage.getGraphics();
screenDraw(screenGraphics);
g.drawImage(screenImage, 0, 0, null);
}
public void screenDraw(Graphics g) {
g.drawImage(mImage, 0, 0, null);
paintComponents(g);
this.repaint();
}
}
I was changing the LookAndFeel of a JTable populated of Custom Class extended of JPanel , But I can't to do it.
I edited to simply my code, but still it's long.
public class LAF_TableCustomContainer extends JFrame {
public LAF_TableCustomContainer() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(300, 300);
setVisible(true);
setLocationRelativeTo(null);
}
public static void changeLAF(Container container, String laf) {
try {
UIManager.setLookAndFeel(laf);
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e) {
}
SwingUtilities.updateComponentTreeUI(container);
}
static final JFrame frame = new JFrame();
public JComponent makeUI() {
String[] hdrsObjects = {"PanelSpinnerRadioButton Class Column"};
Object[][] objectMatrix = new Object[3][1];
objectMatrix[0][0] = new PanelSpinnerRadioButtonData(false, 10, 40);
objectMatrix[1][0] = new PanelSpinnerRadioButtonData(true, 20, 40);
objectMatrix[2][0] = new PanelSpinnerRadioButtonData(false, 30, 40);
JTable table = new JTable(new DefaultTableModel(objectMatrix, hdrsObjects));
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
table.setRowHeight(30);
TableColumn tc = table.getColumn("PanelSpinnerRadioButton Class Column");
tc.setCellRenderer(new PSRBTableCellRenderer());
tc.setCellEditor(new PSRBTableCellEditor());
JPanel pH = new JPanel();
pH.setLayout(new BoxLayout(pH, BoxLayout.LINE_AXIS));
JButton bMetal = new JButton("Metal");
bMetal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeLAF(LAF_TableCustomContainer.this, "javax.swing.plaf.metal.MetalLookAndFeel");
changeLAF(table, "javax.swing.plaf.metal.MetalLookAndFeel");
changeLAF(scrollPane, "javax.swing.plaf.metal.MetalLookAndFeel");
changeLAF((JPanel)table.getModel().getValueAt(0, 0), "javax.swing.plaf.metal.MetalLookAndFeel");
}
});
JButton bMotif = new JButton("Motif");
bMotif.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeLAF(LAF_TableCustomContainer.this, "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
changeLAF(table, "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
changeLAF(scrollPane, "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
changeLAF((JPanel)table.getModel().getValueAt(0, 0), "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
}
});
JButton bNimbus = new JButton("Nimbus");
bNimbus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeLAF(LAF_TableCustomContainer.this, "javax.swing.plaf.nimbus.NimbusLookAndFeel");
changeLAF(table, "javax.swing.plaf.nimbus.NimbusLookAndFeel");
changeLAF(scrollPane, "javax.swing.plaf.nimbus.NimbusLookAndFeel");
changeLAF((JPanel)table.getModel().getValueAt(0, 0), "javax.swing.plaf.nimbus.NimbusLookAndFeel");
}
});
pH.add(bMetal);
pH.add(bMotif);
pH.add(bNimbus);
JPanel pV = new JPanel();
pV.setLayout(new BoxLayout(pV, BoxLayout.PAGE_AXIS));
pV.add(pH);
pV.add(scrollPane);
return pV;
}
public static void main(String... args) {
EventQueue.invokeLater(() -> {
LAF_TableCustomContainer f = new LAF_TableCustomContainer();
f.getContentPane().add(f.makeUI());
});
}
}
class PanelSpinnerRadioButtonData {
private boolean opt02 = false;
private Integer from = 0;
private Integer size = 1;
PanelSpinnerRadioButtonData() {
this(false, 5, 10);
}
PanelSpinnerRadioButtonData(boolean opt02, Integer from, Integer size) {
this.opt02 = opt02;
this.from = from;
this.size = size;
}
public boolean getOption() {
return opt02;
}
public Integer getFrom() {
return from;
}
public Integer getSize() {
return size;
}
}
class PanelSpinnerRadioButton extends JPanel {
public final JRadioButton jrbOption01 = new JRadioButton("01");
public final JRadioButton jrbOption02 = new JRadioButton("12");
public final JSpinner jspnValues = new JSpinner(new SpinnerNumberModel(5, 0, 10, 1));
private final JPanel panel = new JPanel();
PanelSpinnerRadioButton() {
this(new PanelSpinnerRadioButtonData(false, 20, 40));
}
PanelSpinnerRadioButton(PanelSpinnerRadioButtonData data) {
super();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
panel.add(jrbOption01);
panel.add(jrbOption02);
panel.add(Box.createRigidArea(new Dimension(5, 0)));
panel.add(new JSeparator(JSeparator.VERTICAL));
panel.add(Box.createRigidArea(new Dimension(5, 0)));
panel.add(jspnValues);
ButtonGroup bg = new ButtonGroup();
bg.add(jrbOption01);
bg.add(jrbOption02);
((SpinnerNumberModel) jspnValues.getModel()).setMaximum(data.getSize());
setData(data);
init();
}
private void init() {
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
setBackground(new Color(0, 0, 0, 0));
add(panel);
}
public void setData(PanelSpinnerRadioButtonData data) {
if (data.getOption()) {
jrbOption02.setSelected(true);
} else {
jrbOption01.setSelected(true);
}
((SpinnerNumberModel) jspnValues.getModel()).setValue(data.getFrom());
}
// Used in PSRBTableCellEditor.getCellEditorValue()
public PanelSpinnerRadioButtonData getData() {
return new PanelSpinnerRadioButtonData(
jrbOption02.isSelected(),
(Integer) ((SpinnerNumberModel) jspnValues.getModel()).getValue(),
(Integer) ((SpinnerNumberModel) jspnValues.getModel()).getMaximum());
}
}
class PSRBTableCellRenderer implements TableCellRenderer {
private final PanelSpinnerRadioButton renderer = new PanelSpinnerRadioButton();
#Override public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof PanelSpinnerRadioButtonData) {
renderer.setData((PanelSpinnerRadioButtonData) value);
}
return renderer;
}
}
class PSRBTableCellEditor extends AbstractCellEditor implements TableCellEditor {
private final PanelSpinnerRadioButton editor = new PanelSpinnerRadioButton();
#Override public Object getCellEditorValue() {
return editor.getData();
}
#Override public Component getTableCellEditorComponent(
JTable table, Object value, boolean isSelected, int row, int column) {
if (value instanceof PanelSpinnerRadioButtonData) {
editor.setData((PanelSpinnerRadioButtonData) value);
}
return editor;
}
}
When I press some button all JFrame changes except the cells of JTable, containing my custom JPanel.
I tried forcing only the first cell...
changeLAF((JPanel)table.getModel().getValueAt(0, 0), "javax.swing.plaf.metal.MetalLookAndFeel");
But I got Exception:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: PanelSpinnerRadioButtonData cannot be cast to javax.swing.JPanel
The limitation of the SwingUtilities#updateComponentTreeUI(...) method is that the cell renderer LookAndFeel can not change
Since PSRBTableCellRenderer does not extends JComponent, it is not subject to LookAndFeel update in the SwingUtilities # updateComponentTreeUI (...) method
// #see javax/swing/SwingUtilities.java
public static void updateComponentTreeUI(Component c) {
updateComponentTreeUI0(c);
c.invalidate();
c.validate();
c.repaint();
}
private static void updateComponentTreeUI0(Component c) {
if (c instanceof JComponent) {
JComponent jc = (JComponent) c;
jc.updateUI();
JPopupMenu jpm =jc.getComponentPopupMenu();
if(jpm != null) {
updateComponentTreeUI(jpm);
}
}
Component[] children = null;
if (c instanceof JMenu) {
children = ((JMenu)c).getMenuComponents();
}
else if (c instanceof Container) {
children = ((Container)c).getComponents();
}
if (children != null) {
for (Component child : children) {
updateComponentTreeUI0(child);
}
}
}
You can avoid this by overriding the JTable#updateUI() method and recreating the cell renderer and editor.
JTable table = new JTable(new DefaultTableModel(objectMatrix, hdrsObjects)) {
#Override public void updateUI() {
super.updateUI();
setRowHeight(30);
TableColumn tc = getColumn("PanelSpinnerRadioButton Class Column");
tc.setCellRenderer(new PSRBTableCellRenderer());
tc.setCellEditor(new PSRBTableCellEditor());
}
};
LAF_TableCustomContainer2.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class LAF_TableCustomContainer2 extends JFrame {
public LAF_TableCustomContainer2() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(300, 300);
setVisible(true);
setLocationRelativeTo(null);
}
public static void changeLAF(Container container, String laf) {
try {
UIManager.setLookAndFeel(laf);
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e) {
}
SwingUtilities.updateComponentTreeUI(container);
}
static final JFrame frame = new JFrame();
public JComponent makeUI() {
JPanel pV = new JPanel();
pV.setLayout(new BoxLayout(pV, BoxLayout.PAGE_AXIS));
String[] hdrsObjects = {"PanelSpinnerRadioButton Class Column"};
Object[][] objectMatrix = new Object[3][1];
objectMatrix[0][0] = new PanelSpinnerRadioButtonData(false, 10, 40);
objectMatrix[1][0] = new PanelSpinnerRadioButtonData(true, 20, 40);
objectMatrix[2][0] = new PanelSpinnerRadioButtonData(false, 30, 40);
JTable table = new JTable(new DefaultTableModel(objectMatrix, hdrsObjects)) {
#Override public void updateUI() {
super.updateUI();
setRowHeight(30);
TableColumn tc = getColumn("PanelSpinnerRadioButton Class Column");
tc.setCellRenderer(new PSRBTableCellRenderer());
tc.setCellEditor(new PSRBTableCellEditor());
}
};
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
// table.setRowHeight(30);
// TableColumn tc = table.getColumn("PanelSpinnerRadioButton Class Column");
// tc.setCellRenderer(new PSRBTableCellRenderer());
// tc.setCellEditor(new PSRBTableCellEditor());
JPanel pH = new JPanel();
pH.setLayout(new BoxLayout(pH, BoxLayout.LINE_AXIS));
JButton bMetal = new JButton("Metal");
bMetal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeLAF(pV, "javax.swing.plaf.metal.MetalLookAndFeel");
}
});
JButton bMotif = new JButton("Motif");
bMotif.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeLAF(pV, "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
}
});
JButton bNimbus = new JButton("Nimbus");
bNimbus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeLAF(pV, "javax.swing.plaf.nimbus.NimbusLookAndFeel");
}
});
pH.add(bMetal);
pH.add(bMotif);
pH.add(bNimbus);
pV.add(pH);
pV.add(scrollPane);
return pV;
}
public static void main(String... args) {
EventQueue.invokeLater(() -> {
LAF_TableCustomContainer2 f = new LAF_TableCustomContainer2();
f.getContentPane().add(f.makeUI());
});
}
}
class PanelSpinnerRadioButtonData {
private boolean opt02 = false;
private Integer from = 0;
private Integer size = 1;
PanelSpinnerRadioButtonData() {
this(false, 5, 10);
}
PanelSpinnerRadioButtonData(boolean opt02, Integer from, Integer size) {
this.opt02 = opt02;
this.from = from;
this.size = size;
}
public boolean getOption() {
return opt02;
}
public Integer getFrom() {
return from;
}
public Integer getSize() {
return size;
}
}
class PanelSpinnerRadioButton extends JPanel {
public final JRadioButton jrbOption01 = new JRadioButton("01");
public final JRadioButton jrbOption02 = new JRadioButton("12");
public final JSpinner jspnValues = new JSpinner(new SpinnerNumberModel(5, 0, 10, 1));
private final JPanel panel = new JPanel();
PanelSpinnerRadioButton() {
this(new PanelSpinnerRadioButtonData(false, 20, 40));
}
PanelSpinnerRadioButton(PanelSpinnerRadioButtonData data) {
super();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
panel.add(jrbOption01);
panel.add(jrbOption02);
panel.add(Box.createRigidArea(new Dimension(5, 0)));
panel.add(new JSeparator(JSeparator.VERTICAL));
panel.add(Box.createRigidArea(new Dimension(5, 0)));
panel.add(jspnValues);
ButtonGroup bg = new ButtonGroup();
bg.add(jrbOption01);
bg.add(jrbOption02);
((SpinnerNumberModel) jspnValues.getModel()).setMaximum(data.getSize());
setData(data);
init();
}
private void init() {
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
setBackground(new Color(0, 0, 0, 0));
add(panel);
}
public void setData(PanelSpinnerRadioButtonData data) {
if (data.getOption()) {
jrbOption02.setSelected(true);
} else {
jrbOption01.setSelected(true);
}
((SpinnerNumberModel) jspnValues.getModel()).setValue(data.getFrom());
}
// Used in PSRBTableCellEditor.getCellEditorValue()
public PanelSpinnerRadioButtonData getData() {
return new PanelSpinnerRadioButtonData(
jrbOption02.isSelected(),
(Integer)((SpinnerNumberModel) jspnValues.getModel()).getValue(),
(Integer)((SpinnerNumberModel) jspnValues.getModel()).getMaximum());
}
}
class PSRBTableCellRenderer implements TableCellRenderer {
private final PanelSpinnerRadioButton renderer = new PanelSpinnerRadioButton();
#Override public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof PanelSpinnerRadioButtonData) {
renderer.setData((PanelSpinnerRadioButtonData) value);
}
return renderer;
}
}
class PSRBTableCellEditor extends AbstractCellEditor implements TableCellEditor {
private final PanelSpinnerRadioButton editor = new PanelSpinnerRadioButton();
#Override public Object getCellEditorValue() {
return editor.getData();
}
#Override public Component getTableCellEditorComponent(
JTable table, Object value, boolean isSelected, int row, int column) {
if (value instanceof PanelSpinnerRadioButtonData) {
editor.setData((PanelSpinnerRadioButtonData) value);
}
return editor;
}
}
I was trying to set up something with the JMenu where you can switch between "pages" (JPanels) but I ran into an issue where one would not disappear after trying a few methods online. What is the error I am making?
code:
public class Window {
public static boolean NewTerrainCamPos = false;
public static String textVal;
public static String textVal2;
public static String resiveTex;
public static String resiveTex2;
public static final int Width = 1000;
public static final int Height = 720;
public static final int FPS_CAP = 120;
private static long lastFrameTime;
private static float delta;
public void createDisplay(){
ContextAttribs attribs = new ContextAttribs(3,2).withForwardCompatible(true).withProfileCore(true);
try {
Canvas openglSurface = new Canvas();
JFrame frame = new JFrame();
JPanel game = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
//..............Menu Bar...............
JMenuBar menuBar = new JMenuBar();
JMenu terrain = new JMenu("Terrain");
JMenu Home = new JMenu("Home");
menuBar.add(Home);
menuBar.add(terrain);
JMenuItem newTerrain = new JMenuItem("add Terrain");
JMenuItem editTerrain = new JMenuItem("Edit Terrain");
JMenuItem editTexture = new JMenuItem("Edit Texture");
terrain.add(newTerrain);
terrain.add(editTerrain);
terrain.add(editTexture);
frame.setJMenuBar(menuBar);
//......................................................
newTerrain.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
NewTerrainCamPos = true;
JFrame frame2 = new JFrame();
frame2.setVisible(true);
frame2.setSize(300, 300);
//...............................
GridLayout experimentLayout = new GridLayout(3,2);
frame2.setLayout(experimentLayout);
//.....................................
JLabel xCord = new JLabel("XCoords: ");
JLabel zCord = new JLabel("ZCoords: ");
JTextField text = new JTextField();
JTextField text2 = new JTextField();
resiveTex2 = text2.getText();
text.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent de) {
resiveTex = text.getText();
}
#Override
public void removeUpdate(DocumentEvent de) {
resiveTex = text.getText();
}
#Override
public void changedUpdate(DocumentEvent de) {
//plain text components don't fire these events
}
});
text2.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent de) {
resiveTex2 = text2.getText();
}
#Override
public void removeUpdate(DocumentEvent de) {
resiveTex2 = text2.getText();
}
#Override
public void changedUpdate(DocumentEvent de) {
//plain text components don't fire these events
}
});
JButton createTerrain = new JButton("CreateTerrain");
createTerrain.addActionListener(new ActionListener(){
TIDF terrainFileID;
public void actionPerformed(ActionEvent a){
NewTerrainCamPos = false;
textVal = text.getText();
textVal2 = text2.getText();
TIDF load = new TIDF();
load.terrainIDFile();
}
});
frame2.add(xCord);
frame2.add(text);
frame2.add(zCord);
frame2.add(text2);
frame2.add(createTerrain);
}
});
editTerrain.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JFrame frame3 = new JFrame();
frame3.setVisible(true);
frame3.setSize(300, 300);
//......................................
GridLayout experimentLayout = new GridLayout(3,2);
frame3.setLayout(experimentLayout);
//......................................
JButton select = new JButton("Select");
String terrainLocList[] =
{
"Item 1",
"Item 2",
"Item 3",
"Item 4"
};
JList list = new JList(terrainLocList);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setVisibleRowCount(-1);
frame3.add(list);
frame3.add(select);
}
});
editTexture.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
frame.remove(MainPage());
frame.add(TextureEditor());
frame.revalidate();
}
});
//.........................................
frame.add(MainPage());
frame.add(game);
frame.setSize(1200, 1200);
frame.setVisible(true);
game.add(openglSurface);
game.setBounds(0, 266, 1000, 720);
openglSurface.setSize(1000, 720);
Display.setParent(openglSurface);
Display.setDisplayMode(new DisplayMode(Width, Height));
Display.create(new PixelFormat(), attribs);
frame.setTitle("Game editor 0.3");
} catch (LWJGLException e) {
e.printStackTrace();
}
GL11.glViewport(0, 0, Width, Height);
lastFrameTime = getCurrentTime();
}
public Component MainPage(){
JPanel Main = new JPanel();
Main.setBounds(400, 0, 500, 200);
Label Welcome = new Label("Welcome to: Game Editor Version 0.3");
Welcome.setFont(new Font("Monotype Corsiva",10,22));
Main.add(Welcome);
return Main;
}
public Component TextureEditor(){
JPanel TextureLayoutLook = new JPanel();
TextureLayoutLook.setBounds(60, 0, 200, 200);
Label editorVersion = new Label("Terrain Texture Editor: 0.1");
TextureLayoutLook.add(editorVersion);
return TextureLayoutLook;
}
public static boolean Returnboolean(){
return NewTerrainCamPos;
}
public static String getTex1() {
return textVal;
}
public static String getTex2(){
return textVal2;
}
public static String getTexupdate(){
return resiveTex;
}
public static String getTexupdate2(){
return resiveTex2;
}
public static void updateDisplay(){
Display.sync(FPS_CAP);
Display.update();
long currentFrameTime = getCurrentTime();
delta = (currentFrameTime - lastFrameTime)/1000f;
lastFrameTime = currentFrameTime;
}
public static float getFrameTimeSeconds(){
return delta;
}
public static void closeDisplay(){
Display.destroy();
}
private static long getCurrentTime(){
return Sys.getTime()*1000/Sys.getTimerResolution();
}
}
frame.add(MainPage());
This line builds a brand new "main page" JPanel, and adds it the the JFrame.
frame.remove(MainPage());
This line of code creates a brand new "main page" JPanel, which has never been added to the JFrame, and attempts to remove it.
This new panel can't be removed, because it was never added. You need to retain a reference to the original panel, and remove that.
JPanel main_page = MainPage();
frame.add(main_page);
//...
frame.remove(main_page);
Note: This main_page could be re-added at a future time without needing to recreate it. Just call frame.add(main_page); again. But really, you want to use the card layout manager.
So I am doing a Hang man game in Java for my Final Project in my Computer Science class. I have done the template for the Hang man (i.e. buttons and added the words needed). But I don't know how to draw the Hangman itself and how to randomly add the words (meaning so they will start guessing the words) to the program. What I am asking is how do I draw the Hangman if a letter was guessed wrong(or right, to write in the textfield). For the letters I have done JButtons because I think it would be easier, and added action listeners. I know the code is very long, but don't pay attention to the template, method Start is where I have my words and hints. Thank you in advance. Don't mind that I do not have a main method, I have a driver class that extends this class. (It was one of the requirements)
Solved!
package hangman;
import javax.swing.*;
import java.util.Random;
import java.util.Scanner;
import java.awt.event.*;
import java.awt.*;
public class Hangman extends JFrame
{
JPanel panel = new JPanel();
JButton restart = new JButton("Restart");
JButton a = new JButton("A"), b = new JButton("B"), c = new JButton("C"), d = new JButton("D"), ee = new JButton("E"), f = new JButton("F"),
g = new JButton("G"), h = new JButton("H"), i = new JButton("I"), j = new JButton("J"), k = new JButton("K"), l = new JButton("L"),
m = new JButton("M"), n = new JButton("N"), o = new JButton("O"), p = new JButton("P"), q = new JButton("Q"), r = new JButton("R"),
s = new JButton("S"), t = new JButton("T"), u = new JButton("U"), v = new JButton("V"), w = new JButton("W"), x = new JButton("X"),
y = new JButton("Y"), z = new JButton("Z");
JButton exit = new JButton("Exit");
JButton hint = new JButton("Hint");
JLabel title = new JLabel("Welcome to Hang Man! ");
JLabel hintWord = new JLabel("Click the Button to show a hint!");
Font font = new Font("Comic Sans MS", Font.ITALIC, 24);
JTextField theWord = new JTextField();
Font font1 = new Font("Comic Sans MS", Font.BOLD, 34);
public Hangman()
{
//Panel adding
panel.add(restart);
panel.add(theWord);
panel.add(hint);
panel.add(exit);
panel.add(title);
panel.add(hintWord);
panel.add(a);
panel.add(b);
panel.add(c);
panel.add(d);
panel.add(ee);
panel.add(f);
panel.add(g);
panel.add(h);
panel.add(j);
panel.add(k);
panel.add(l);
panel.add(m);
panel.add(n);
panel.add(o);
panel.add(p);
panel.add(q);
panel.add(r);
panel.add(s);
panel.add(t);
panel.add(u);
panel.add(v);
panel.add(w);
panel.add(x);
panel.add(y);
panel.add(z);
add(panel);
title.setFont(font);
// JFrame properties
setSize(1024, 700);
setTitle("Hangman");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
this.setLayout(null);
panel.setLayout(null);
//Adding to the panel
panel.add(restart);
panel.add(theWord);
panel.add(hint);
panel.add(exit);
panel.add(title);
panel.add(hintWord);
panel.add(a);
panel.add(b);
panel.add(c);
panel.add(d);
panel.add(ee);
panel.add(f);
panel.add(g);
panel.add(h);
panel.add(j);
panel.add(k);
panel.add(l);
panel.add(m);
panel.add(n);
panel.add(o);
panel.add(p);
panel.add(q);
panel.add(r);
panel.add(s);
panel.add(t);
panel.add(u);
panel.add(v);
panel.add(w);
panel.add(x);
panel.add(y);
panel.add(z);
add(panel);
// Positioning
restart.setLocation(25,25);
theWord.setLocation(100, 530);
theWord.setEnabled(false);
theWord.setSize(800, 100);
theWord.setHorizontalAlignment(theWord.CENTER);
theWord.setFont(font1);
theWord.setForeground(Color.RED);
hint.setLocation(600, 150);
exit.setLocation(900, 25);
title.setLocation(350, 25);
a.setLocation(600, 250);
b.setLocation(650, 250);
c.setLocation(700, 250);
d.setLocation(750, 250);
ee.setLocation(800, 250);
f.setLocation(850, 250);
g.setLocation(900, 250);
h.setLocation(950, 250);
j.setLocation(600, 280);
k.setLocation(650, 280);
l.setLocation(700, 280);
m.setLocation(750, 280);
n.setLocation(800, 280);
o.setLocation(850, 280);
p.setLocation(900, 280);
q.setLocation(950, 280);
r.setLocation(600, 310);
s.setLocation(650, 310);
t.setLocation(700, 310);
u.setLocation(750, 310);
v.setLocation(800, 310);
w.setLocation(850, 310);
x.setLocation(900, 310);
y.setLocation(950, 310);
z.setLocation(750, 340);
hintWord.setLocation(670, 150);
// Action Listeners
restart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
restartActionPerformed(e);
}
});
hint.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
hintActionPerformed(e);
}
});
exit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
exitActionPerformed(e);
}
});
a.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
aActionPerformed(e);
}
});
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
bActionPerformed(e);
}
});
c.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
cActionPerformed(e);
}
});
d.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dActionPerformed(e);
}
});
ee.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
eeActionPerformed(e);
}
});
f.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
fActionPerformed(e);
}
});
g.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
gActionPerformed(e);
}
});
h.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
hActionPerformed(e);
}
});
j.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
jActionPerformed(e);
}
});
k.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
kActionPerformed(e);
}
});
l.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
lActionPerformed(e);
}
});
m.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
mActionPerformed(e);
}
});
n.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
nActionPerformed(e);
}
});
o.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
oActionPerformed(e);
}
});
p.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
pActionPerformed(e);
}
});
q.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
qActionPerformed(e);
}
});
r.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
rActionPerformed(e);
}
});
s.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
sActionPerformed(e);
}
});
t.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
tActionPerformed(e);
}
});
u.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
uActionPerformed(e);
}
});
v.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
vActionPerformed(e);
}
});
w.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
wActionPerformed(e);
}
});
x.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
xActionPerformed(e);
}
});
y.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
yActionPerformed(e);
}
});
z.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
zActionPerformed(e);
}
});
}
public void Start()
{
String words[] = new String[26];
String hints[] = new String[26];
// Words along with hints
words[0] = "president";
hints[0] = "Leader.";
words[1] = "exclamation";
hints[1] = "Shout out.";
words[2] = "statement";
hints[2] = "To say.";
words[3] = "television";
hints[3] = "You watch it.";
words[4] = "physics";
hints[4] = "Form of Science.";
words[5] = "algebra";
hints[5] = "Form of math.";
words[6] = "geometry";
hints[5] = "Form of math.";
words[7] = "difficult";
hints[7] = "Hard.";
words[8] = "extreme";
hints[8] = "Intense.";
words[9] = "procedure";
hints[9] = "Steps.";
words[10] = "ship";
hints[10] = "Big Boat.";
words[11] = "soldier";
hints[11] = "Army.";
words[12] = "lunch";
hints[12] = "Meal.";
words[13] = "hockey";
hints[13] = "Sports.";
words[14] = "tennis";
hints[14] = "Sports.";
words[15] = "soccer";
hints[15] = "Sports.";
words[16] = "football";
hints[16] = "Sports.";
words[17] = "basketball";
hints[17] = "Sports.";
words[18] = "bias";
hints[18] = "One sided.";
words[19] = "magazine";
hints[19] = "Form of book.";
words[20] = "computer";
hints[20] = "Microsoft.";
words[21] = "internet";
hints[21] = "World Wide Web.";
words[22] = "allegedly";
hints[22] = "Supposedly.";
words[23] = "system";
hints[23] = "Network.";
words[24] = "unison";
hints[24] = "As one.";
words[25] = "excited";
hints[25] = "Upbeat.";
}
// Action Listeners
public void restartActionPerformed(ActionEvent e)
{
a.setEnabled(true);
b.setEnabled(true);
c.setEnabled(true);
d.setEnabled(true);
ee.setEnabled(true);
f.setEnabled(true);
g.setEnabled(true);
h.setEnabled(true);
j.setEnabled(true);
k.setEnabled(true);
l.setEnabled(true);
m.setEnabled(true);
n.setEnabled(true);
o.setEnabled(true);
p.setEnabled(true);
q.setEnabled(true);
r.setEnabled(true);
s.setEnabled(true);
t.setEnabled(true);
u.setEnabled(true);
v.setEnabled(true);
w.setEnabled(true);
x.setEnabled(true);
y.setEnabled(true);
z.setEnabled(true);
hintWord.setText("Click the Button to show a hint!");
}
public void exitActionPerformed(ActionEvent e)
{
System.exit(0);
}
public void hintActionPerformed(ActionEvent e)
{
hintWord.setText("");
}
public void aActionPerformed(ActionEvent e)
{
a.setEnabled(false);
}
public void bActionPerformed(ActionEvent e)
{
b.setEnabled(false);
}
public void cActionPerformed(ActionEvent e)
{
c.setEnabled(false);
}
public void dActionPerformed(ActionEvent e)
{
d.setEnabled(false);
}
public void eeActionPerformed(ActionEvent e)
{
ee.setEnabled(false);
}
public void fActionPerformed(ActionEvent e)
{
f.setEnabled(false);
}
public void gActionPerformed(ActionEvent e)
{
g.setEnabled(false);
}
public void hActionPerformed(ActionEvent e)
{
h.setEnabled(false);
}
public void jActionPerformed(ActionEvent e)
{
j.setEnabled(false);
}
public void kActionPerformed(ActionEvent e)
{
k.setEnabled(false);
}
public void lActionPerformed(ActionEvent e)
{
l.setEnabled(false);
}
public void mActionPerformed(ActionEvent e)
{
m.setEnabled(false);
}
public void nActionPerformed(ActionEvent e)
{
n.setEnabled(false);
}
public void oActionPerformed(ActionEvent e)
{
o.setEnabled(false);
}
public void pActionPerformed(ActionEvent e)
{
p.setEnabled(false);
}
public void qActionPerformed(ActionEvent e)
{
q.setEnabled(false);
}
public void rActionPerformed(ActionEvent e)
{
r.setEnabled(false);
}
public void sActionPerformed(ActionEvent e)
{
s.setEnabled(false);
}
public void tActionPerformed(ActionEvent e)
{
t.setEnabled(false);
}
public void uActionPerformed(ActionEvent e)
{
u.setEnabled(false);
}
public void vActionPerformed(ActionEvent e)
{
v.setEnabled(false);
}
public void wActionPerformed(ActionEvent e)
{
w.setEnabled(false);
}
public void xActionPerformed(ActionEvent e)
{
x.setEnabled(false);
}
public void yActionPerformed(ActionEvent e)
{
y.setEnabled(false);
}
public void zActionPerformed(ActionEvent e)
{
z.setEnabled(false);
}
}
To draw the lines you could use drawline in the Graphics class.
g.drawLine(int x1, int y1, int x2, int y2);
Docs:
Draws a line, using the current color, between the points (x1, y1) and (x2, y2).
Write down the coordinates to a int array and loop thought that array for all cords.
int[] line1 = new int[]{x1,y1,x2,y2};
int[] line2 = new int[]{x3,y3,x4,y4};
If you wonder how to draw the head you can use drawPolygon
int[] head = new int[]{x,y};
final int headSize = 50; //width and height in px
g.drawPolygon(head[0], head[1], headSize, headSize);
Hope it helped.
Regards -Max
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I want to add, move and set properties (font and rotation) of components at runtime.
In other words, I need to add a button, a label, drag them using mouse and set a component's properties at runtime. Is there any example Java swing for or similar to this?
This is my code :
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.io.File;
import java.sql.SQLException;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
public class prova extends JFrame implements MouseMotionListener,MouseListener{
//*************** INIZIALIZZAZIONE VARIABILI ***************************
Checkbox CB=new Checkbox("Label",true);
Button BP=new Button("BUTTON_1");
Button B=new Button("OK");
JComboBox combo1=new JComboBox();
JMenuBar menuBar;
int app=0;
static int anglePeso=0;
static int angleTara=0;
ImageIcon ic;
Border border = LineBorder.createBlackLineBorder();
static int pesoX=184;
static int pesoY=91;
static boolean taraVisible=false;
static boolean pesoVisible=false;
static boolean logo1Visible=false;
static boolean BarCodeVisible=false;
static String font="";
static String rot="";
Label societa=new Label ("Società");
Label importo=new Label ("Importo");
Label nome=new Label("Nome Prodotto");
static int logo1X=250;
static int logo1Y=90;
static Component C;
static int label1X=183;
static int label1Y=91;
static int taraX=100;
//TextField TF=new TextField(10);
static Panel P=new Panel();
//List TA=new List();
boolean b1=false;
int c1=0;int c2=0;
static JLabel logo2=new JLabel("Logo2");
static int aa=0;
static int importoX=0;
static int importoY=0;
public static boolean isBarCodeVisible() {
return BarCodeVisible;
}
public static void setBarCodeVisible(boolean BarCodeVisible) {
prova.BarCodeVisible = BarCodeVisible;
}
public static Component getC() {
return C;
}
public static void setC(Component C) {
prova.C = C;
}
public static int getAnglePeso() {
return anglePeso;
}
public static void setAnglePeso(int anglePeso) {
prova.anglePeso = anglePeso;
}
static ImageIcon immLogo1;
public JLabel getBarcode() {
return barcode;
}
public void setBarcode(JLabel barcode) {
this.barcode = barcode;
}
public static ImageIcon getImmLogo1() {
return immLogo1;
}
public static void setImmLogo1(ImageIcon immLogo1) {
prova.immLogo1 = immLogo1;
}
public static void setFont(String font) {
prova.font = font;
}
public static String getRot() {
return rot;
}
public static void setRot(String rot) {
prova.rot = rot;
}
public static boolean isPesoVisible() {
return pesoVisible;
}
public static void setPesoVisible(boolean pesoVisible) {
prova.pesoVisible = pesoVisible;
}
public static boolean isTaraVisible() {
return taraVisible;
}
public static void setTaraVisible(boolean taraVisible) {
prova.taraVisible = taraVisible;
}
static JLabel label1=new JLabel("Peso"){
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
AffineTransform aT = g2.getTransform();
Shape oldshape = g2.getClip();
double x = getWidth()/2.0;
double y = getHeight()/2.0;
aT.rotate(Math.toRadians(anglePeso), x, y);
// g2.transform(aT);
g2.setTransform(aT);
g2.setClip(oldshape);
super.paintComponent(g);
}
};
Label data=new Label("Data");
static JLabel tara=new JLabel("Tara"){
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
AffineTransform aT = g2.getTransform();
Shape oldshape = g2.getClip();
double x = getWidth()/2.0;
double y = getHeight()/2.0;
aT.rotate(Math.toRadians(angleTara), x, y);
// g2.transform(aT);
g2.setTransform(aT);
g2.setClip(oldshape);
super.paintComponent(g);
}
};
static JLabel logo1=new JLabel("Logo1");
public static JLabel getTara() {
return tara;
}
public static void setTara(JLabel tara) {
prova.tara = tara;
}
static JLabel barcode=new JLabel ("Bar Code");/*{
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
AffineTransform aT = g2.getTransform();
Shape oldshape = g2.getClip();
double x = getWidth()/2.0;
double y = getHeight()/2.0;
aT.rotate(Math.toRadians(angle), x, y);
// g2.transform(aT);
g2.setTransform(aT);
g2.setClip(oldshape);
super.paintComponent(g);
}
};
*/
public static JLabel getLogo1() {
return logo1;
}
public static void setLogo1(JLabel logo1) {
prova.logo1 = logo1;
}
public static boolean isLogo1Visible() {
return logo1Visible;
}
public static void setLogo1Visible(boolean logo1Visible) {
prova.logo1Visible = logo1Visible;
}
public static int getLogo1X() {
return logo1X;
}
public static void setLogo1X(int logo1X) {
prova.logo1X = logo1X;
}
public static int getLogo1Y() {
return logo1Y;
}
public static void setLogo1Y(int logo1Y) {
prova.logo1Y = logo1Y;
}
public static int getTaraX() {
return taraX;
}
public static void setTaraX(int taraX) {
prova.taraX = taraX;
}
public static int getTaraY() {
return taraY;
}
public static void setTaraY(int taraY) {
prova.taraY = taraY;
}
static int taraY=90;
public int getLabel1X() {
return label1X;
}
public void setLabel1X(int label1X) {
this.label1X = label1X;
}
public int getLabel1Y() {
return label1Y;
}
public void setLabel1Y(int label1Y) {
this.label1Y = label1Y;
}
public prova(){
}
public prova(String titlu)
{
super(titlu);
}
void init(int b,int h, String [] par) throws ClassNotFoundException, SQLException
{
setLayout(null);
System.out.println("****************COORINATE PESO: "+label1X+" "+label1Y);
menuBar = new JMenuBar();
JMenuBar menubar = new JMenuBar();
JMenu filemenu = new JMenu("File");
filemenu.add(new JSeparator());
JMenu editmenu = new JMenu("Edit");
editmenu.add(new JSeparator());
JMenuItem fileItem1 = new JMenuItem("New");
JMenuItem fileItem2 = new JMenuItem("Open");
JMenuItem fileItem3 = new JMenuItem("Close");
fileItem3.add(new JSeparator());
JMenuItem fileItem4 = new JMenuItem("Save");
JMenuItem editItem1 = new JMenuItem("Cut");
JMenuItem editItem2 = new JMenuItem("Copy");
editItem2.add(new JSeparator());
JMenuItem editItem3 = new JMenuItem("Paste");
JMenuItem editItem4 = new JMenuItem("Insert");
filemenu.add(fileItem1);
filemenu.add(fileItem2);
filemenu.add(fileItem3);
filemenu.add(fileItem4);
editmenu.add(editItem1);
editmenu.add(editItem2);
editmenu.add(editItem3);
editmenu.add(editItem4);
menubar.add(filemenu);
menubar.add(editmenu);
setJMenuBar(menubar);
//setSize(400,400);
//setVisible(true);
fileItem4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Cliccato Save ");
punti();
setVisible(false);
}
});
InserimentoDB is=new InserimentoDB();
Image im=is.getImage("select immagine from etichette where id= 75");
ic=new ImageIcon(im);
P.setBackground(Color.red);
String[] mm=new String [4];
mm[0]="0";
mm[1]="90";
mm[2]="180";
mm[3]="270";
combo1.setModel(new DefaultComboBoxModel(mm) {});
combo1.addMouseMotionListener(this);
combo1.addMouseListener(this);
combo1.setLocation(200,100);combo1.setSize(80,40);
//add(combo1);
System.out.println("LabelX: "+label1X);
System.out.println("LabelY: "+label1Y);
// label1.getParent().repaint();
/*
l.addMouseMotionListener(this);
l.addMouseListener(this);
l1.addMouseMotionListener(this);
l1.addMouseListener(this);
l2.addMouseMotionListener(this);
l2.addMouseListener(this);
l3.addMouseMotionListener(this);
l3.addMouseListener(this);
*/
for (int i=0; i<par.length; i++){
System.out.println("Parametri ricevuti "+par[i]);
}
//TA.addMouseMotionListener(this);
//TA.addMouseListener(this);
B.addMouseMotionListener(this);
B.addMouseListener(this);
P.addMouseMotionListener(this);
P.addMouseListener(this);
CB.addMouseMotionListener(this);
CB.addMouseListener(this);
if (par[6].equalsIgnoreCase("logo1")){
if(logo1Visible){
System.out.println("*******LOGO1: "+immLogo1);
// logo1.setIcon(immLogo1);
logo1.addMouseMotionListener(this);
logo1.addMouseListener(this);
// System.out.println("Imm Logo1: "+immLogo1.getDescription());
logo1.setIcon(ic);
logo1.setLocation(logo1X,logo1Y);
//label1.setLocation(pesoX,pesoY);
logo1.setSize(384,160);
add(logo1);
}
}
if (par[0].equalsIgnoreCase("peso")){
if(pesoVisible){
// label1.setBorder(border);
label1.addMouseMotionListener(this);
label1.addMouseListener(this);
label1.setBorder(BorderFactory.createEtchedBorder());
//label1.setFont(font);
label1.setLocation(label1X,label1Y);
//label1.setLocation(pesoX,pesoY);
label1.setSize(100,20);
// label1.setIcon(immLogo1);
add(getContent());
//add(getCombo());
label1.setName("peso");
add(label1);
repaint();
}
}
if (par[1].equalsIgnoreCase("tara")){
if(taraVisible){
tara.addMouseMotionListener(this);
tara.addMouseListener(this);
//tara.setLocation(49,130);
tara.setBorder(BorderFactory.createEtchedBorder());
tara.setLocation(taraX,taraY);
tara.setSize(100,20);
tara.setName("tara");
add(tara);
repaint();
}
}
if (par[2].equalsIgnoreCase("importo")){
importo.addMouseMotionListener(this);
importo.addMouseListener(this);
importo.setLocation(44,91);importo.setSize(100,20);
importo.setName("IMPORTO");
add(importo);
}
if (par[3].equalsIgnoreCase("bar code")){
if(BarCodeVisible){
barcode.addMouseMotionListener(this);
barcode.addMouseListener(this);
ImageIcon icon = new ImageIcon("/home/max/Downloads/ce.jpg");
barcode.setIcon(icon);
barcode.setLocation(81,223);barcode.setSize(284,177);
add(barcode);
}
}
if (par[4].equalsIgnoreCase("data")){
data.addMouseMotionListener(this);
data.addMouseListener(this);
// data.setLocation(184,177);
data.setSize(100,20);
data.setName("data");
add(data);
}
if (par[5].equalsIgnoreCase("nome prodotto")){
nome.addMouseMotionListener(this);
nome.addMouseListener(this);
nome.setLocation(43,186);nome.setSize(100,20);
add(nome);
}
ImageIcon icon1 = new ImageIcon("/home/max/Downloads/ce.jpg");
logo2.setIcon(icon1);
logo2.setLocation(100, 50);
add(logo2);
//add(B);***********************
B.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
System.out.println("Cliccato");
punti();
setVisible(false);
}
});
/*data.addMouseMotionListener(this);
data.addMouseListener(this);
societa.addMouseMotionListener(this);
societa.addMouseListener(this);
barcode.addMouseMotionListener(this);
barcode.addMouseListener(this);
TA.setLocation(50,50);
TA.setSize(100,100);TA.add("List");
CB.setLocation(120,370);CB.setSize(100,20);
data.setLocation(184,177);data.setSize(100,20);
societa.setLocation(112,41);societa.setSize(100,20);
barcode.setLocation(44,178);barcode.setSize(100,20);*/
B.setLocation(100,150);B.setSize(80,40);
P.setLayout(new BorderLayout());
P.setLocation(100,200);P.setSize(150,150);
P.setBackground(Color.yellow);
P.add(BP,BorderLayout.NORTH);
//P.add(TF,BorderLayout.SOUTH);
//add(TA);add(B);add(P);add(CB);
//add(l);add(l1);add(l2);add(l3);add(label);
//add(label);
//add(data);add(societa);add(tara);add(barcode);
setLocation(500,500);
setSize(b*10,h*10);
setVisible(true);
//show();
}
//mouseDragged
public void mouseDragged(MouseEvent e)
{
Component C=e.getComponent();
if(b1==false){b1=true;Point p=new
Point(e.getPoint());c1=p.x;c2=p.y;}
Point z=new Point(e.getPoint());
Point q=new Point(C.getLocation());
C.setBounds(q.x+(z.x-c1),q.y+(z.y-c2),C.getSize().
width,C.getSize().height);
repaint();
}
//mouseReleased
public void mouseReleased(MouseEvent e)
{
b1=false;
System.out.println("Mouse Rilascaito");
Component C=e.getComponent();
System.out.println("*******++++++++++**********+++++++++Coordinate"+ C);
System.out.println("NOme: "+C.getName());
if(C.getName().equalsIgnoreCase("importo")){
importo.setLocation(C.getX(), C.getY());
importoX=C.getX();
importoY=C.getY();
}
if(C.getName().equalsIgnoreCase("data")){
data.setLocation(C.getX(), C.getY());
}
if(C.getName().equalsIgnoreCase("peso")){
label1X=C.getX();
label1Y=C.getY();
}
C.getX();
C.getY();
//Attenzione qui sotto da controllare!!!!!!!
//pesoX=e.getX();
//pesoY=e.getY();
repaint();
}
//mouseEntered
public void mouseEntered(MouseEvent e)
{
Cursor c1=new Cursor(Cursor.HAND_CURSOR);
setCursor(c1);
}
//mouseExited
public void mouseExited(MouseEvent e)
{
Cursor c2=new Cursor(Cursor.DEFAULT_CURSOR);
setCursor(c2);
}
//mouseClicked
public void mouseClicked(MouseEvent e)
{
if (e.getClickCount() == 2) {
Component C=e.getComponent();
System.out.println("*****************+NOme componente: "+C.getName());
System.out.println("Coordinate: "+C.getLocation());
System.out.println("XXX: "+C.getX());
System.out.println("YYY: "+C.getY());
// Configurazione cc=new Configurazione();
// cc.setComponente(C.getName());
// cc.main();
Configurazione cf=new Configurazione();
// cf.setC(C);
cf.main();
//RotLabel rot=new RotLabel();
//rot.main();
System.out.println("\n\nRotazione: "+rot);
System.out.println("Font: "+font);
System.out.println("\n\n");
System.out.println("+++++++++++++++++++++++++++++++Clicccato 2 volte");
/* JFrame frame=new JFrame("Configurazione");
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocation(200, 300);
JLabel titolo=new JLabel("Configurazione "+C.getName());
JLabel rotazione=new JLabel("Rotazione");
String [] val=new String [4];
val[0]="0";
val[1]="90";
val[2]="180";
val[3]="270";
JComboBox scelta=new JComboBox(val);
frame.add(titolo);
frame.add(rotazione);
frame.add(scelta);
//3. Create components and put them in the frame.
//...create emptyLabel...
//frame.getContentPane().add(new JLabel("Configurazione"), BorderLayout.CENTER);
//4. Size the frame.
frame.pack();
//5. Show it.
frame.setVisible(true);*/
}
Component C=e.getComponent();
C.getParent().repaint();
repaint();
System.out.println("Coordinate"+ C);
}
//mouseMoved
public void mouseMoved(MouseEvent e)
{
Component C=((Component)e.getSource());
java.util.Random r=new java.util.Random();
java.util.Random g=new java.util.Random();
java.util.Random b=new java.util.Random();
int cr=r.nextInt(255);int cg=g.nextInt(255);
int cb=b.nextInt(255);
Color col=new Color(cr,cg,cb);
//C.setBackground(col);
}
//mousePressed
public void mousePressed(MouseEvent e){}
public class mouse_events{}
public static void punti(){
Inizio in=new Inizio();
System.out.println("\n\n****************Controllo visibilità: ");
System.out.println("Peso: "+pesoVisible);
System.out.println("Tara: "+taraVisible);
System.out.println("Logo1: "+logo1Visible);
System.out.println("***********************************\n\n");
if(logo1Visible){
System.out.println("Parametri Logo1 "+logo1.getLocation());
System.out.println("Parametri X Logo1 "+logo1.getX());
in.setLogo1X(logo1.getX());
//System.out.println("Scrivo app: "+app);
System.out.println("Parametri Y Logo1 "+logo1.getY());
in.setLogo1Y(logo1.getY());
}
if(pesoVisible){
System.out.println("Parametri Label "+label1.getLocation());
System.out.println("Parametri X Label "+label1.getX());
in.setLabelX(label1.getX());
//System.out.println("Scrivo app: "+app);
System.out.println("Parametri Y Label "+label1.getY());
in.setLabelY(label1.getY());
}
if(taraVisible){
System.out.println("Parametri tara "+tara.getLocation());
System.out.println("Parametri X Tara "+tara.getX());
in.setTaraX(tara.getX());
//System.out.println("Scrivo app: "+app);
System.out.println("Parametri Y Tara "+tara.getY());
in.setTaraY(tara.getY());
}
System.out.println("Parametri Bar Code "+barcode.getLocation());
System.out.println("Parametri X Bar code "+barcode.getX()/10);
in.setBarX(barcode.getX()/10);
//System.out.println("Scrivo app: "+app);
System.out.println("Parametri Y Bar Code "+barcode.getY()/10);
in.setBarY(barcode.getY()/10);
// System.out.println("Parametri nome "+nome.getLocation());
// System.out.println("Parametri X nome "+nome.getX()/10);
// in.setNomeX(nome.getX()/10);
//System.out.println("Scrivo app: "+app);
// System.out.println("Parametri Y nome "+nome.getY()/10);
// in.setNomeY(nome.getY()/10);
// System.out.println("Parametri importo "+importo.getLocation());
// System.out.println("Parametri X importo "+importo.getX()/10);
// in.setImportoX(importo.getX()/10);
//System.out.println("Scrivo app: "+app);
// System.out.println("Parametri Y importo "+importo.getY()/10);
// in.setImportoY(importo.getY()/10);
// System.out.println("Parametri data "+data.getLocation());
// System.out.println("Parametri X data"+data.getX()/10);
// in.setDataX(data.getX()/10);
//aa=data.getX();
//System.out.println("Scrivo app: "+app);
// System.out.println("Parametri Y data "+data.getY()/10);
// in.setDataY(data.getY()/10);
}
public void visibile(boolean vis){
P.setVisible(vis);
/*
WindowEvent close = new WindowEvent(FRAME, WindowEvent.WINDOW_CLOSING);
FRAME.dispatchEvent(close);
*/
}
/*
private JComboBox getCombo(){
//final JSlider slider = new JSlider(-180, 180, angle);
String[] val=new String [4];
val[0]="0";
val[1]="90";
val[2]="180";
val[3]="270";
//final JComboBox combo1=new JComboBox(val);
combo1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// angle = Integer.parseInt(combo1.getSelectedItem().toString());//.getValue();
label1.getParent().repaint();
}
});
return combo1;
}*/
private JPanel getContent() {
label1.setFont(new Font("Monospaced", Font.PLAIN, 24));
label1.setBorder(BorderFactory.createEtchedBorder());
JPanel panel = new JPanel(new GridBagLayout());
panel.add(label1, new GridBagConstraints());
return panel;
}
/*
public static void main(String[] args)
{
prova t=new prova("MOUSE EVENT");
t.init();
}*/
public static void refresh(){
//P.getParent().repaint();
P.repaint();
//add(label1);
//repaint();
}
}
Thanks.
Years ago I wrote a framework for this. Maybe it can serve you as a start (the library is Open Source):
Tutorial: http://softsmithy.sourceforge.net/lib/current/docs/tutorial/swing/customizer/index.html
Javadoc: http://softsmithy.sourceforge.net/lib/current/docs/api/softsmithy-lib-core/index.html
Homepage: http://softsmithy.sourceforge.net/
Maven:
<dependency>
<groupId>org.softsmithy.lib</groupId>
<artifactId>softsmithy-lib-core</artifactId>
<version>0.2</version>
</dependency>
More info: http://puces-blog.blogspot.ch/2012/07/news-from-software-smithy-version-02.html
Other solutions:
You could consider the NetBeans Platform and try to reuse either its Matisse component or the Visual Graph library.