我试图在用户界面中绘制一个圆角矩形作为组件的背景。为此,我调用了fillRoundRect()
方法。但是,我找不到一种方法来获取组件的位置。我尝试使用getX()
和getY()
,getLocation()
,getBounds()
和getLocationOnScreen()
。在覆盖的paintComponent()
方法中调用这些方法时,所有这些方法都会将矩形放置在错误的位置。
主类:
JScrollPane projectListPane;
JPanel projectEntriesPane;
public static void main(String[] args) {
JFrame frame = new JFrame("Being Productive");
frame.setSize(300,300);
frame.setContentPane(new TestClass());
frame.pack();
frame.setVisible(true);
}
public TestClass() {
setLayout(new BorderLayout());
initProjectPane();
projectListPane = new JScrollPane(projectEntriesPane);
add(projectListPane);
}
private void initProjectPane() {
projectEntriesPane = new JPanel();
projectEntriesPane.setLayout(new BoxLayout(projectEntriesPane,BoxLayout.Y_AXIS));
for(int i = 0; i < 4; i++)
{
JLabel label = new JLabel();
JRounded round = new JRounded(label);
label.setText("test");
projectEntriesPane.add(round);
}
projectEntriesPane.repaint();//just seeing if this would do anything. It didn't
}
自定义组件类:
public class JRounded extends JPanel{
public JRounded(Component contained) {
setLayout(new BorderLayout());
add(contained, BorderLayout.CENTER);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(Color.RED);
g2.setStroke(new BasicStroke(2.0f));
Point position = **position method**;
g2.fillRoundRect(position.x, position.y, getWidth(), getHeight(), 15, 15);
}
}