gpt4 book ai didi

java - JSeparator 虚线样式

转载 作者:行者123 更新时间:2023-12-01 18:23:09 25 4
gpt4 key购买 nike

我在我的 java swing 应用程序中使用 JSeparator。正常执行使分隔线正常;但我需要的是分隔符应该是虚线(就像我们创建虚线边框一样)。我们有什么办法可以做到这一点吗?

谢谢

最佳答案

创建自定义 JSeparator ,您可以重写 BasicSeparatorUIpaint() 方法,讨论here ,并使用虚线 Stroke 绘制线条,如图所示 here .

附录:一种更熟悉的方法会覆盖 paintComponent(),如已接受的 answer 所示。并方便地封装在这个StrokedSeparator中。下面的变体将 drawLine() 替换为 draw()使用 Line2D,它利用了笔划的几何形状。

Separators

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Stroke;
import java.awt.geom.Line2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import static javax.swing.JSeparator.*;

/**
* @see https://stackoverflow.com/a/74657060/230513
*/
public class StrokeSepTest {

private static final int N = 10;

private void display() {
var f = new JFrame("StrokeSepTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
var stroke = new BasicStroke(8.0f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10.0f, new float[]{5.0f}, 0.0f);
var panel = new JPanel(new GridLayout(0, 1)) {
@Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
};
panel.setBackground(Color.white);
for (int i = 0; i < N; i++) {
Color color = Color.getHSBColor((float) i / N, 1, 1);
panel.add(new StrokedSeparator(stroke, HORIZONTAL, color));
}
f.add(panel);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}

// @see https://stackoverflow.com/a/74657060/230513 */
private static class StrokedSeparator extends JSeparator {

private Stroke stroke;

public StrokedSeparator() {
this(new BasicStroke(1F), HORIZONTAL);
}

public StrokedSeparator(int orientation) {
this(new BasicStroke(1F), orientation);
}

public StrokedSeparator(Stroke stroke) {
this(stroke, HORIZONTAL);
}

public StrokedSeparator(Stroke stroke, int orientation) {
super(orientation);
this.stroke = stroke;
}

public StrokedSeparator(Stroke stroke, int orientation, Color color) {
super(orientation);
super.setForeground(color);
this.stroke = stroke;
}

@Override
public void paintComponent(Graphics g) {
var graphics = (Graphics2D) g;
var s = getSize();
graphics.setStroke(stroke);
graphics.setColor(getForeground());
if (getOrientation() == JSeparator.VERTICAL) {
graphics.draw(new Line2D.Double(0, 0, 0, s.height));
} else // HORIZONTAL
{
graphics.draw(new Line2D.Double(0, 0, s.width, 0));
}
}
}

public static void main(String[] args) {
EventQueue.invokeLater(new StrokeSepTest()::display);
}
}

关于java - JSeparator 虚线样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27077372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com