简体   繁体   中英

How can I make this custom JButton work?

I've looked through so many threads- and none have helped me. Here is my code:

package myProjects;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.*;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class LukeButton extends JButton{
public static void main(String[] args){
    JFrame frame = new JFrame();
    frame.setTitle("Luke");
    frame.setSize(300, 300);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    LukeButton lb = new LukeButton("Text");
    lb.addActionListener(e->{
        System.out.println("Clicked");
    });

    frame.setVisible(true);
}
public LukeButton(String text){

}
public void paint(Graphics g){
    Graphics2D g2 = (Graphics2D)g;

    Shape rec = new Rectangle2D.Float(10, 10, 60, 80);

    g2.setColor(Color.BLACK);
    g2.setStroke(new BasicStroke(2));
    g2.draw(rec);
    g2.setColor(Color.BLUE);
    g2.fill(rec);
    }
}

And the rectangle that is supposed to be there, isn't. I don't know if this is not allowed when extending JButton, but if it's not, I don't know how to fix it. Does anyone have a solution?

A main problem: You don't add your LukeButton instance to the GUI. Solution: add it via a container's add(lb) method.

public static void main(String[] args) {
    LukeButton lb = new LukeButton("Text");
    JPanel panel = new JPanel();
    panel.add(lb);

    JFrame frame = new JFrame();
    frame.add(panel);

Other problems:

  • You should override the paintComponent method not the paint method
  • Call the super's paintComponent method in the override
  • Override the getPreferredSize of your component.
  • Don't ignore the String being passed into your constructor's parameter. You'll probably want to pass it into the super's constructor.
  • You're likely far better off not using inheritance to do whatever it is you're trying to do, that is, to not extend JButton. If you can give us more detail of your overall problem, we can help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM