我在表单上有一些复选框,我希望它们通过单行连接。有一些简单的方法来做到这一点?由于我正在使用WindowBuilder并且随着表单大小的改变,对象可能会移动,我不能只在屏幕上放置图形。
具体来说,我有4个复选框,表示棒球钻石的基础,菱形图案。我希望连接它们的基本路径是直线。
所以,基本概念是:
这表明JCheckBox
s需要包含在同一个组件/容器中,这样可以简化它。
从那里,你将覆盖组件的paintComponent
方法,计算源和目标组件/复选框的中心位置,并在两者之间画一条线
例如...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JCheckBox[] checkBoxes;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = gbc.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
checkBoxes = new JCheckBox[4];
for (int index = 0; index < 4; index++) {
checkBoxes[index] = new JCheckBox();
checkBoxes[index].setOpaque(false);
checkBoxes[index].setHorizontalAlignment(JCheckBox.CENTER);
}
// Base
gbc.gridx = 1;
gbc.gridy = 2;
add(checkBoxes[0], gbc);
// First
gbc.gridx = 2;
gbc.gridy = 1;
add(checkBoxes[1], gbc);
// Second
gbc.gridx = 1;
gbc.gridy = 0;
add(checkBoxes[2], gbc);
// Third
gbc.gridx = 0;
gbc.gridy = 1;
add(checkBoxes[3], gbc);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected Point center(Rectangle bounds) {
Point point = new Point();
point.x = bounds.x + (bounds.width / 2);
point.y = bounds.y + (bounds.height / 2);
return point;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Point from = center(checkBoxes[0].getBounds());
for (int index = 1; index < checkBoxes.length; index++) {
Rectangle bounds = checkBoxes[index].getBounds();
Point to = center(bounds);
g2d.drawLine(from.x, from.y, to.x, to.y);
from = to;
}
Point to = center(checkBoxes[0].getBounds());
g2d.drawLine(from.x, from.y, to.x, to.y);
g2d.dispose();
}
}
}
警告:由于绘画在Swing中的工作方式,当更新/重新绘制子组件时,父组件可能不会被通知/绘制。因此,您对任何可能影响线条位置的子组件所做的任何更改也需要强制父组件的repaint
。
不,你不能通过Window Builder来做到这一点,你将不得不亲自动手使这项工作正常进行