我的代码无法将自定义 JComponent 对象的边框设置为 new EmptyBorder(50, 50, 50, 50)
。这是我的监视器上的样子(如您所见,它显然适用于 JButton,但不适用于自定义 JComponent):
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class Sandbox
{
public static void main(String[] args)
{
// Instantiate components needed.
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
WideComponent wc = new WideComponent();
JButton button = new JButton("Test");
// Add borders
EmptyBorder empty1 = new EmptyBorder(50, 50, 50, 50);
wc.setBorder(empty1);
EmptyBorder empty2 = new EmptyBorder(50, 50, 50, 50);
button.setBorder(empty2);
// Add stuff to panel
panel.add(wc);
panel.add(button);
// Add panel to frame, show frame
frame.add(panel);
frame.setVisible(true);
frame.pack();
}
}
class WideComponent extends JComponent
{
final int WIDTH = 500;
final int HEIGHT = 150;
// drawing method
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(0, 0, WIDTH, HEIGHT);
}
// JComponent sizing methods
public Dimension getPreferredSize()
{
return new Dimension(WIDTH, HEIGHT);
}
public Dimension getMaximumSize() { return getPreferredSize(); }
public Dimension getMinimumSize() { return getPreferredSize(); }
}
最佳答案
您的边框工作正常——但只是空边框被涂成蓝色,因为您正在绘制整个组件,而边框是该组件的一部分。例如:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class Sandbox {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
WideComponent wc = new WideComponent();
JButton button = new JButton("Test");
wc.setBorder(createBorder());
button.setBorder(createBorder());
panel.add(wc);
panel.add(button);
frame.add(panel);
frame.setVisible(true);
frame.pack();
}
private static Border createBorder() {
Border innerBorder = BorderFactory.createLineBorder(Color.red);
int eb = 50;
Border outerBorder = BorderFactory.createEmptyBorder(eb, eb, eb, eb);
Border comboBorder = BorderFactory.createCompoundBorder(outerBorder,
innerBorder);
return comboBorder;
}
}
class WideComponent extends JComponent {
final int WIDTH = 500;
final int HEIGHT = 150;
public WideComponent() {
setOpaque(true);
}
// drawing method
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(0, 0, WIDTH, HEIGHT);
}
// JComponent sizing methods
public Dimension getPreferredSize() {
return new Dimension(WIDTH, HEIGHT);
}
public Dimension getMaximumSize() {
return getPreferredSize();
}
public Dimension getMinimumSize() {
return getPreferredSize();
}
}
如果您希望 WideComponent 周围有一个空白边框,请将其嵌套在 JPanel 中,并将边框提供给嵌套的 JPanel。例如,上面的代码可以通过添加以下内容来更改:
JPanel nestingJPanel = new JPanel();
nestingJPanel.add(new WideComponent());
nestingJPanel.setBorder(createBorder());
panel.add(wc);
panel.add(button);
panel.add(nestingJPanel);
关于java - 为什么我不能将 EmptyBorder 添加到自定义 JComponent?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29875352/