我使用简单的“计算器”项目作为圆角矩形按钮的示例。整个项目包含一个小类文件。这是:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* Swing layout management tutorial
*
* This program shows how to use the
* GridLayout manager to create a
* calculator skeleton.
*
* @author jan bodnar
* website zetcode.com
* last modified February 2009
*/
public class Calculator extends JFrame {
public Calculator() {
setTitle("Calculator");
initUI();
setSize(320, 290);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public void initUI() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
menubar.add(file);
setJMenuBar(menubar);
String[] labels = {
"Cls", "Bck", "", "Close",
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
JTextField field = new JTextField();
add(field, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new GridLayout(5, 4, 3, 3));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(8, 0, 0, 0));
for (String label: labels) {
if (label.isEmpty()) {
JLabel lbl = new JLabel();
buttonPanel.add(lbl);
} else {
JButton button = new JButton(label);
buttonPanel.add(button);
}
}
add(buttonPanel, BorderLayout.CENTER);
}
public static void main(String[] args) {
new Calculator();
}
}
当它运行时,它产生漂亮的矩形标记按钮,具有平坦的,略微3D的外观。我试图获得如下效果:
FlowLayout flowLayoutManager = new FlowLayout(FlowLayout.RIGHT);
JPanel lowerPanel = new JPanel(flowLayoutManager);
lowerPanel.setBorder(
BorderFactory.createEtchedBorder(
EtchedBorder.RAISED));
lowerPanel.setBackground(Color.ORANGE);
lowerPanel.setPreferredSize(new Dimension(700, 100));
lowerPanel.setMaximumSize(lowerPanel.getPreferredSize());
lowerPanel.setMinimumSize(lowerPanel.getPreferredSize());
/*
* cardReaderButtonPanel holds three card reader control buttons
*/
JPanel cardReaderButtonPanel = new JPanel(new GridLayout(1, 3, 10, 0));
cardReaderButtonPanel.setBorder(BorderFactory.createEmptyBorder(8, 0, 0, 0));
cardReaderButtonPanel.setOpaque(false); // transparent background
String[] labels = {"Load", "Stop", "Start"};
for (String label : labels) {
JButton button = new JButton(label);
cardReaderButtonPanel.add(button);
}
lowerPanel.add(cardReaderButtonPanel);
...但我的按钮看起来像Mac OS X Aqua含片!与计算器示例不同,我将按钮面板添加到一个封闭面板,该面板本身被BorderLayout的中心包围 - 但我不知道这会如何影响按钮的绘制方式。