-1
嗨,即時通訊尋找一種解決方案,使用Java Swing製作自定義按鈕。 我有一個例子應該如何,但它不顯示按鈕文本。有人知道錯誤在哪裏嗎?如何製作一個自定義的JButton類?
這是一個JButton類
package custombutton;
import java.awt.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.border.LineBorder;
public class CustomButton extends JButton implements MouseListener {
Dimension size = new Dimension(206, 30);
boolean hover = false;
boolean click = false;
String text;
public CustomButton(String text) {
setVisible(true);
setFocusable(true);
setContentAreaFilled(false);
setBorderPainted(true);
setBorder(new LineBorder(Color.BLACK, 3));
setButtonText(text);
addMouseListener(this);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(255, 255, 255));
g.fillRect(0, 0, 206, 30);
g.setFont(Font.decode("arial-24"));
FontMetrics metrics = g.getFontMetrics();
int width = metrics.stringWidth(getButtonText());
g.drawString(text, 103 - width/2, 15);
}
@Override
public Dimension getPreferredSize() {
return size;
}
@Override
public Dimension getMaximumSize() {
return size;
}
@Override
public Dimension getMinimumSize() {
return size;
}
public void setButtonText(String text) {
this.text = text;
}
public String getButtonText() {
return text;
}
@Override
public void mouseEntered(MouseEvent e) {
hover = true;
}
@Override
public void mouseExited(MouseEvent e) {
hover = false;
}
@Override
public void mousePressed(MouseEvent e) {
click = true;
}
@Override
public void mouseReleased(MouseEvent e) {
click = false;
}
@Override
public void mouseClicked(MouseEvent e) {}
}
這裏IST主:
package custombutton;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame {
public Main() {
JPanel panel = new JPanel();
setTitle("Custom Button");
setSize(400, 100);
setResizable(false);
panel.setBackground(Color.GRAY);
CustomButton button = new CustomButton("Hallo");
panel.add(button);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
*「我有一個例子應該如何..「* ..在哪裏?謹慎與我們分享這個例子? –