您好我正在编程游戏,我认为圆形按钮看起来不错但我很好奇如何将所述按钮的大小更改为更大的尺寸?这是我的代码
public JavaApplication3(String label) {
super(label);
Dimension size = getPreferredSize();
size.width = size.height = Math.max(size.width,size.height);
setPreferredSize(size);
setContentAreaFilled(false);
}
protected void paintComponent(Graphics g) {
if (getModel().isArmed()) {
g.setColor(Color.RED);
} else {
g.setColor(Color.yellow);
}
g.fillOval(0, 0, getSize().width-1,getSize().height-1);
super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
g.setColor(getForeground());
g.drawOval(0, 0, getSize().width-1, getSize().height-1);
}
Shape shape;
public boolean contains(int x, int y) {
if (shape == null ||
!shape.getBounds().equals(getBounds())) {
shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
}
return shape.contains(x, y);
}
希望有人可以提供帮助:)
答案 0 :(得分:0)
每次点击按钮都会改变按钮的大小。
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("klick");
setSize(new Dimension(newSizeWidth, newSizeHeight));
}
});
}
只需拨打
即可 setSize(new Dimension(newSizeWidth, newSizeHeight));
方法
这是一些有效的代码:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.JButton;
import javax.swing.JFrame;
public class test2 extends JButton {
int width = 100;
int height = 100;
public test2(String label) {
super(label);
setSize(width, height);
setContentAreaFilled(false);
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("klick");
setSize(new Dimension(width--, height--));
}
});
}
protected void paintComponent(Graphics g) {
if (getModel().isArmed()) {
System.out.println(width + " " + height);
g.setColor(Color.RED);
} else {
g.setColor(Color.yellow);
}
g.fillOval(0, 0, getSize().width - 1, getSize().height - 1);
super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
g.setColor(getForeground());
g.drawOval(0, 0, getSize().width - 1, getSize().height - 1);
}
Shape shape;
public boolean contains(int x, int y) {
if (shape == null || !shape.getBounds().equals(getBounds())) {
shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
}
return shape.contains(x, y);
}
static JFrame f;
public static void main(String[] args) {
f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setSize(200, 200);
f.add(new test2("label"));
f.setLayout(new BorderLayout());
f.setVisible(true);
}
}