我正在使用JPanels
和JFrames
进行项目,我将创建一个名为“欢迎使用目标”的面板以及位于邮件下方的目标徽标。我有的类是Main,TargetLogoPanel和TargetLogoUI。
我尝试搞乱Netbeans 7.1中实现的设计功能,但是找不到以这种方式绘制椭圆的方法,所以这是我添加的代码:
@Override
protected void paintComponent(Graphics g) {
g.setColor(Color.red);
g.fillOval(((targetPanel.getWidth()) / 2) - 100,
((targetPanel.getHeight()) / 2) - 100, 200, 200);
g.setColor(Color.WHITE);
g.fillOval(((targetPanel.getWidth()) / 2) - 65,
((targetPanel.getHeight()) / 2) - 65, 130, 130);
g.setColor(Color.red);
g.fillOval(((targetPanel.getWidth()) / 2) - 30,
((targetPanel.getHeight()) / 2) - 30, 60, 60);
}
徽标宽度为200像素,在调整框架大小时保持居中。但是,正如我添加的内容一样,程序运行时不会绘制圆圈。在我的主要方法中,我放了new TargetLogoUI().setVisible(true);
我到底错在了什么?
答案 0 :(得分:1)
您提供的代码段存在许多问题。
super.paintComponent
,这是确保正确绘制组件所必需的。paint
的工作,这是布局管理器的工作。这些只是我们从您的代码段中看到的内容,可能还有其他问题。
public class Target {
public static void main(String[] args) {
new Target();
}
public Target() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
int radius = Math.min(width, height);
g.setColor(Color.red);
g.fillOval(
(int)((radius / 2) - (radius * 0.5)),
(int)((radius / 2) - (radius * 0.5)),
(int)radius,
(int)radius);
g.setColor(Color.WHITE);
g.fillOval(
(int)((radius / 2) - (radius * 0.325)),
(int)((radius / 2) - (radius * 0.325)),
(int)(radius * 0.65),
(int)(radius * 0.65));
g.setColor(Color.red);
g.fillOval(
(int)((radius / 2) - (radius * 0.15)),
(int)((radius / 2) - (radius * 0.15)),
(int)(radius * 0.3),
(int)(radius * 0.3));
}
}
}
答案 1 :(得分:0)
我在google上搜索了一个靶心,然后遇到了this example。我在下面提供了修改后的JPanel
。
我设置rings = 3
并在paintComponent()
class Bullseye extends JPanel {
static final int SIZE = 300; // initial window size
int rings = 3; // Number of rings to draw in bullseye
public Bullseye() {
this.setBackground(Color.white);
this.setPreferredSize(new Dimension(SIZE, SIZE));
}
public void setRings(int r) {
rings = r;
this.repaint(); // new value of rings - better repaint
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// x,y coordinate of top left corner for drawing circles
int x = SIZE / 2;
int y = SIZE / 2;
for (int i = rings; i > 0; i--) {
if (i % 2 == 0)
g.setColor(Color.white);
else
g.setColor(Color.red);
int radius = i * 100 / rings; // compute radius of this ring
g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
}
}