I am trying to make a border appear when a user hovers their mouse over something, but when I use the paint Method. It says
Syntax Error on Token "(" ; expected and
Syntax Error on Token ")" ; expected
My code is:
JLabel lblAllOrNothing = new JLabel("All Or Nothing (4 BP)");
lblAllOrNothing.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent arg0) {
public void paint(Graphics g) { //Error is this line
g.drawRect(0, 72, 256, 72);
}
}
});
I just don't where else I can put a semi-colen. I am new to GUI programming, so I hope I did not make too bad of a mistake. Thanks!
You cannot nest two method in java:
public void mouseEntered(MouseEvent arg0) {
public void paint(Graphics g) { //Method inside a method is not allowed
you can't to call paint() from AWT/Swing Listener
this methods is automatically called by override this method for Container
override paintComponent for JPanel instead of paint()
You have a syntax problem.
JLabel lblAllOrNothing = new JLabel("All Or Nothing (4 BP)");
lblAllOrNothing.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent arg0) {
// You can't define a method inside a method!!
}
});
By the way to make custom painting in Swing you should override paintComponent instead of paint. Read more Painting in AWT and Swing
You can't nest a paint method in your mouseEntered method; perhaps you just want
JLabel lblAllOrNothing = new JLabel("All Or Nothing (4 BP)");
lblAllOrNothing.addMouseListener(new java.awt.event.MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
// public void paint(Graphics g) {
// g.drawRect(0, 72, 256, 72); }
java.awt.Component c = e.getComponent();
c.getGraphics().drawRect(0, 72, 256, 72);
}
});
you cant put a method into another one in java make the draw method out the listener
what you should do is just call the draw method in the listener method:
this
new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent arg0) {
// You can't define a method inside a method!!
}
};
is an anonymous class.
now when you use it as an statement it will be used as };, and return an object, while when you use it as pass the object as a parameter the will use it as
fun(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent arg0) {
// You can't define a method inside a method!!
}
});
You can't have a method inside of a method in Java.
Instead, do this
JLabel lblAllOrNothing = new JLabel("All Or Nothing (4 BP)");
lblAllOrNothing.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent arg0) {
//call the paint method here
}
//Move this method here
public void paint(Graphics g) { //Error is this line
g.drawRect(0, 72, 256, 72);
}
});
Note that this will not actually work functionally, but it illustrates why you're getting a syntax error
Related
I'm trying to draw circles with random colors and random diameters on mousePressed event but I'm having some issues when I tried to organize my code a little bit "separate my code into classes".
Controller class
public class Controller implements MouseListener {
private HashSet<Circle> circleSet = new HashSet<>();
private int r,g,b,d;
#Override
public void mousePressed(MouseEvent e) {
r = new Random().nextInt(256);
g = new Random().nextInt(256);
b = new Random().nextInt(256);
d = 10+new Random().nextInt(100);
circleSet.add(new Circle(e.getX()-d/2,e.getY()-d/2,d,d,new
Color(r,g,b),0,0));
}
public HashSet<Circle> getCircleSet() {
return circleSet;
}
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
}
View class
public class View extends JPanel{
Controller controller;
HashSet<Circle> circleHashSet;
public View() {
repaint();
controller = new Controller();
circleHashSet = controller.getCircleSet();
this.addMouseListener(controller);
listen();
System.out.println(circleHashSet.size());
}
public void listen() {
new javax.swing.Timer(100, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
circleHashSet = controller.getCircleSet();
System.out.println(circleHashSet.size());
}
});
}
#Override
public void paintComponents(Graphics g) {
super.paintComponents(g);
for (Circle circle:this.circleHashSet) {
paintCircle(g,circle);
}
System.out.println(circleHashSet);
}
public void paintCircle(Graphics graphics, Circle circle) {
graphics.setColor(circle.color);
graphics.fillOval(circle.x,circle.getY(),circle.a,circle.b);
}
circleHashSet still empty even though I did:
//circleHashSet = controller.getCircleSet();
Circles are added into circleSet after pressing the mouse but I can't get them into the View class.
First of all, the problem is that you are calling the paintComponents(Graphics g) method instead of the paintComponent(Graphics g) method.
If you are done changing this, you should create a separate Circle POJO class for the circles, because the only avaliable Circle avaliable in the basic Java API is from the JavaFX package.
After setting the constructor for the circle class, you can add to the HashSet more easily. Like so: circleSet.add(new Circle(e.getX() - d / 2, e.getY() - d / 2, d, new Color(r, g, b)));
Another problem is that the Timer object you created is never used for anything. First, you should make a Timer object and after initializing it, call the start() method on it to start the checking of the circles.
put this line of code
circleHashSet = controller.getCircleSet();
within paintComponents() method. The reason is that you only get the value of HashSet when you start the program while the hashset is empty at this time. You should renew the value of circleHashSet after painting one with mouse.
How do I override a paintComponent method with response to a state change?
Error message: void is an invalid type for the variable paintComponent
public class MyContainer extends Container {
public void paintComponent(Graphics m){
m.drawArc(100,100,100,100,100,100);
m.setColor(Color.green);
m.fillArc(100,100,100,100,100,100);
}
public static void main(String[] args){
Container y = new Container();
JFrame x = new JFrame();
JPanel gg = new JPanel();
x.add(y);
x.setTitle(" Shape Changer");
x.setBounds(100,50,500,300);
x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
x.getContentPane().add(new ContentPanel());
x.getContentPane().add(new ContnetPanel());
x.setContentPane(new ContnetPanel());
x.setVisible(true);
}
static class ContentPanel extends JPanel{
private Graphics g;
private JPanel ss;
public void paint(Graphics g){
g.drawArc(100,100,100,100,100,100);
g.fillRect(100, 100,100,100);
}
public ContentPanel(){
}
}
static class ContnetPanel extends JPanel implements ActionListener, ChangeListener{
JComboBox comboerbox;
class appres {
public void paint(Graphics h){
h.drawRect(100,100,100,100);
h.setColor(Color.red);
h.fillRect(100,100,100,100);
}
}
public ContnetPanel(){
comboerbox = new JComboBox();
comboerbox.addItem("Red Square");
comboerbox.addItem("Blue Square");
comboerbox.addItem("Green Square");
comboerbox.setSelectedIndex(1);
add(comboerbox);
setLayout(new GridLayout(2,1));
}
#Override
protected void paintComponent(Graphics h){
super.paintComponent(h);
h.drawArc(100,100,100,100,100,100);
h.setColor(Color.blue);
h.fillArc(100,100,100,100,100,100);
repaint();
}
int yy = 0;
public void actionPerformed(ActionEvent evt){
switch(comboerbox.getSelectedIndex()){
case 0:yy=0;
case 1: yy=1;
case 2: yy=2;
}
}
//evt.getSource()==comboerbox
public void stateChanged(ChangeEvent evt){
if(evt.getSource()==comboerbox){
#Override
protected void paintComponent(Graphics h){
super.paintComponent(h);
h.drawArc(100,100,100,100,100,100);
h.setColor(Color.blue);
h.fillArc(100,100,100,100,100,100);
repaint();
}
}
else
{
System.out.println("DONE");
}
}
}
}
Of course, the paintComponent method isn't a variable. How would I override paintComponent here? Or is a better way to change the shape with response to state change? That would be great too!
Thanks in advance, love you guys!
In your last question: How do I make the superclass go beyond just the content pane? you were given a link to the Swing tutorial for some Swing basics.
Well there is also a section on Custom Painting for you to read. You can then download the example and play with it to understand how painting works.
Basically the Container class doesn't have a paintComponent() method so you should not be trying to do custom painting in that class.
If you want to change a painting property, then you need to add a method to your class to change the state of the property and then invoke repaint() on itself.
So from the tutorial example in Step 3 you can see how the moveSquare(...) method changes the state of the class and then invokes repaint().
Note you should never invoke repaint() in the paintComponent() method since this will cause the painting to be continually rescheduled.
I have designed a panel that includes some buttons with it. Buttons are attached with an ActionListener. When ever i click on that buttons this ActionListener detects 4 events for this single click. Whereas it should detect only one. Does anybody know what exactly the reason is?
public class Buttons extends JPanel
{
private JButton undo=new JButton("Undo");
private JButton replay=new JButton("Replay");
public void paint(Graphics g)
{
super.paint(g);
super.setSize(new Dimension(560,30));
super.add(replay);
super.add(undo);
undo.setBorder(new LineBorder(Color.WHITE,3));
replay.setBorder(new LineBorder(Color.WHITE,3));
undo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
Controler.pieces.undo();
Controler.reDraw();
}
});
replay.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Dastiii");
}
});
}
}
and these events are being used here
public void undo()
{
System.out.print(Controler.allMoves.size());
if(Controler.allMoves.size()<=1)
{
init_board();
return;
}
Piece temp[][]=Controler.allMoves.get(Controler.allMoves.size()-2);
for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
{
board[i][j].set_name(temp[i][j].get_name());
board[i][j].set_oneWay(temp[i][j].get_oneWay());
}
}
Controler.allMoves.remove(Controler.allMoves.size()-2);
}
Your registering you ActionListeners within the paint method!!
Let's not even worry about the fact that it's un-recommended to override paint
Never change or modify the state of the component or any of it's child components within in any paint method, these will be called multiple times during the execution of your application. For example, it's not unusual for a paint method to be called 2-4 times just when the main window is made visible...
public void paint(Graphics g)
{
super.paint(g);
/** All this should be done within the constructor
// If you are using a layout manager, this is pointless, if your not
// then that's another problem
super.setSize(new Dimension(560,30));
super.add(replay);
super.add(undo);
undo.setBorder(new LineBorder(Color.WHITE,3));
replay.setBorder(new LineBorder(Color.WHITE,3));
undo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
Controler.pieces.undo();
Controler.reDraw();
}
});
replay.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Dastiii");
}
});
**/
}
Take a look at:
Performing Custom Painting
Painting in AWT and Swing
For more details about how and what painting is in Swing
to execute flow chart Symbols.
But JFrame paint method is not working for this method.
package floating;
import designs.*; //mydesings for executing flow chart Symbols
import java.awt.*;
import javax.swing.*;
public class Test extends JFrame
{
boolean START,PASS; //for using
int SPEED=1;
JSlider jSlider1 = new javax.swing.JSlider();
JSeparator js=new JSeparator();
JToggleButton jToggleButton1 = new javax.swing.JToggleButton("START");
JToggleButton jToggleButton2 = new javax.swing.JToggleButton("PASS");
Test(String a)
{
JFrame jf=new JFrame(a);
Dimension dim=Toolkit.getDefaultToolkit().getScreenSize();
jf.setSize(dim.width,dim.height-30);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jToggleButton1.setLocation((dim.width/2)+30,25);
jToggleButton1.setSize(100,30);
jToggleButton1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jToggleButton1ItemStateChanged(evt);
}
});
jToggleButton2.setLocation((dim.width/2)+50+100,25);
jToggleButton2.setSize(100,30);
jToggleButton2.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jToggleButton2ItemStateChanged(evt);
}
});
js.setOrientation(SwingConstants.VERTICAL);
js.setForeground(Color.red);
js.setLocation(dim.width/2,0);
js.setPreferredSize(dim);
js.setSize(10,dim.height);
jf.add(js);
jSlider1.setLocation(dim.width-300,20);
jSlider1.setSize(250,50);
jSlider1.setToolTipText("Set to Seconds");
jSlider1.setMinimum(1);jSlider1.setMaximum(5);jSlider1.setMajorTickSpacing(1);
jSlider1.setMinorTickSpacing(1);jSlider1.setValue(1);
jSlider1.setPaintLabels(true);
jSlider1.setPaintTicks(true);
jSlider1.setPaintTrack(true);
jSlider1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jSlider1MouseClicked(evt);
}
});
jf.add(jSlider1);
jf.add(jToggleButton1);
jf.add(jToggleButton2);
jf.setLayout(null);
jf.setVisible(true);
}
public void jToggleButton1ItemStateChanged(java.awt.event.ItemEvent evt)
{
if(jToggleButton1.getActionCommand()=="START")
{
System.out.printf(jToggleButton1.getText());
jToggleButton1.setText("STOP");
this.START=true;
System.out.println(this.START);
}
else
{
System.out.printf(jToggleButton1.getText());
jToggleButton1.setText("START");
this.START=false;
System.out.println(this.START);
}
}
public void jToggleButton2ItemStateChanged(java.awt.event.ItemEvent evt)
{
if( jToggleButton2.getActionCommand()=="PASS")
{
System.out.printf(jToggleButton2.getText());
jToggleButton2.setText("RESUME");
this.PASS=true;
System.out.println(" "+this.PASS);
}
else
{
System.out.printf(jToggleButton2.getText());
jToggleButton2.setText("PASS");
this.PASS=false;
System.out.println( " " +this.PASS);
}
}
private void jSlider1MouseClicked(java.awt.event.MouseEvent evt)
{
this.SPEED=jSlider1.getValue();
System.out.println(SPEED);
}
#Override
public void paint(Graphics g) //testing paint method
{
super.paint(g);
g.drawLine(10, 20, 50, 70);
repaint();
}
public static void main(String args[])
{
Test a=new Test("Test");
}
}
Test class extends JFrame. So if you want to have overridden paint method to work, you have to create an object of Test class. And make it setVisible(true)
In stead, you are creating another JFrame object in Test's constructor. Don't create it. The object of Test itself is a JFrame. Add all components to Test object in stead of JFrame object (jF).
Hope this helps.
Don't invoke repaint() from a painting method. This will cause an infinite loop.
Custom painting is done by overriding the paintComponent() method of a JPanel (or JComponent) and then you add the panel to the frame. Read the section from the Swing tutorial on Custom Painting for more information and examples. Start with the example from the tutorial and make changes so your class is better designed.
Don't use "==" for string comparisons. Use the equals(...) method.
Also, in the future, post a proper SSCCE when you ask a question. Your question is about painting so most of the code you posted is unrelated to the question.
I want to use canvas inside mousePressed. How can I do that?
public DragManager(Canvas canvas)
{
canvas.addMouseListener(new MouseAdapter() {
#Override public void mousePressed(MouseEvent e)
{
canvas.something(); // does not work.
}
});
}
As many of the guys over here already said you have to make function parameter final.
public DragManager(final Canvas canvas)
{
canvas.addMouseListener(new MouseAdapter() {
#Override public void mousePressed(MouseEvent e)
{
canvas.something();
}
});
}
That means that this variable cannot point to any other object. E.g. you cannot do this inside function:
canvas = SomeOtherCanvas
If you create an object using a local class definition, that object can keep "living" after local variables have been discarded from the stack (after DragManager constructor completion). It has to have a copy of the local values. If you make this parameter final (so it's guaranteed that reference inside constructor wouldn't point to some other place) it's really easy to have a copy: just copy a reference. If there was no such rule you (well, not you personally, but Java language) would need to constantly sync those values and that would be much more complex and slow solution.
Make the parameter final:
public DragManager(final Canvas canvas)
you Cannot refer to non final variable inside an inner class defined. mark your canvas as final.
public void DragManager(final Canvas canvas)
{
canvas.addMouseListener(new MouseAdapter() {
#Override public void mousePressed(MouseEvent e)
{
System.out.println(canvas);;// does not work.
}
});
public DragManager(final Canvas canvas)
{
canvas.addMouseListener(new MouseAdapter() {
#Override public void mousePressed(MouseEvent e)
{
canvas.something(); // does work.
}
});
}
since you can modify canvas variable, you should define it as final(constant reference).
without using final keyword. you can add Init method that return this and add private variable.
pass canvas by Call Init method.
public DragManager(Canvas canvas)
{
canvas.addMouseListener(new MouseAdapter() {
Canvas _canvas;
#Override public void mousePressed(MouseEvent e)
{
_canvas.something(); // does not work.
}
public MouseAdapter Init(Canvas canvas){
_canvas = canvas;
return this;
}
}.Init(canvas));
}