在JPanel的边框上设置笔触

时间:2016-05-15 05:02:46

标签: java swing border

我在设置边框的厚度方面遇到了问题。我想要一个带有圆形虚线边框的JPanel。我可以通过覆盖paintComponent来使其四舍五入。但是,当我设置笔划使边框更粗并且虚线时它不起作用。我使用setStroke()方法。我的代码如下

private void loadTopPane() {

    JPanel topSection = new JPanel() {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Dimension arcs = new Dimension(15, 15); // Border corners arcs
                                                    // {width,height},
                                                    // change this to
                                                    // whatever you want
            int width = getWidth();
            int height = getHeight();
            Graphics2D graphics = (Graphics2D) g;
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            float dash1[] = { 10.0f };
            final BasicStroke dashed = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f,
                    dash1, 0.0f);

            // Draws the rounded panel with borders.
            graphics.setColor(getBackground());
            graphics.fillRoundRect(0, 0, width - 1, height - 1, arcs.width, arcs.height);// paint
                                                                                            // background
            graphics.setColor(getForeground());
            graphics.drawRoundRect(0, 0, width - 1, height - 1, arcs.width, arcs.height);// paint
                                                                                            // border
            graphics.setStroke(dashed);

        }
    };

    topSection.setLayout(null);
    topSection.setSize(1150, 175);
    topSection.setBackground(new Color(222, 225, 226));

    topSection.setBounds(25, 13, topSection.getPreferredSize().width, topSection.getPreferredSize().height);

    topSection.add(new JLabel("TESTING"));
    topSection.setBounds(20, 10, 1180, 180);
    frame.add(topSection);

}

因此输出显示JPanel带有圆角边框,但它没有给我一个虚线和更粗的边框。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您是否考虑在绘制边框之前调用setStroke ...

Stroked

float dash1[] = {10.0f};
final BasicStroke dashed = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f,
                                                                                     dash1, 0.0f);
graphics.setStroke(dashed);

// Draws the rounded panel with borders.
graphics.setColor(getBackground());
graphics.fillRoundRect(0, 0, width - 1, height - 1, arcs.width, arcs.height);// paint
// background
graphics.setColor(getForeground());
graphics.drawRoundRect(0, 0, width - 1, height - 1, arcs.width, arcs.height);// paint