我正在尝试创建一个可以修改和希望的通用节点,但是我遇到了一些麻烦,因为我在Swing中的技能并不是那么好。
问题1:我似乎无法在同一个JFrame中获得两个Node / Jpanel。
较小的问题2:中风从JPanel边界切断(我是否应该建立一种出血,这样就不会发生?)
任何帮助都有帮助:)
public class SimpleGui {
public SimpleGui() {
JFrame frame = new JFrame();
NodePanel panel = new NodePanel(3, 2);
panel.setLayout(new javax.swing.SpringLayout());
frame.add(panel);
NodePanel panel2 = new NodePanel(3, 2);
panel2.setLayout(new javax.swing.SpringLayout());
frame.add(panel2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setResizable(true);
frame.setVisible(true);
panel.setLocation(50, 50);
panel2.setLocation(150, 150);
}
}
添加到JFrame的通用节点/面板类:
public class NodePanel extends JPanel {
private int x = 0, int y = 0;
private PortPanel inPortPanel;
private PortPanel outPortPanel;
int iH;
int oH;
private int width = 120;
private int height = 30;
Graphics2D g2;
public NodePanel(int input, int output) {
inPortPanel = new PortPanel(input);
this.add(inPortPanel);
outPortPanel = new PortPanel(output);
this.add(outPortPanel);
setPreferredSize(calculateDimension());
}
public void paintComponent(Graphics g) {
g2 = (Graphics2D) g;
g2.setColor(Color.black);
g2.setStroke(new BasicStroke(4));
inPortPanel.setLocation(x, y + (height - iH) / 2);
outPortPanel.setLocation(x + width, y + (height - oH) / 2);
drawNode();
}
private void drawNode() {
g2.drawRoundRect(x, y, width, height, 5, 5);
}
private Dimension calculateDimension() {
iH = inPortPanel.getPreferredSize().height;
int iW = inPortPanel.getPreferredSize().width;
oH = outPortPanel.getPreferredSize().height;
height = iH > oH ? iH + iW : oH + iW;
return new Dimension(width, height);
}
}
作为节点面板
的一部分的端口面板public class PortPanel extends JPanel {
int x = 0;
int y = 0;
int portWidth = 14;
int portHeight = 14;
int count = 0;
int offset = 22;
Graphics2D g2;
public PortPanel(int i) {
this.count = i;
setPreferredSize(calculateDimensions());
}
public void paintComponent(Graphics g) {
g2 = (Graphics2D) g;
g2.setColor(Color.black);
drawPorts();
}
private void drawPorts() {
for (int i = 0; i < count; i++) {
g2.fillOval(x, y + (i * offset), portWidth, portHeight);
}
}
private Dimension calculateDimensions(){
int overallHeight = (offset * (count-1)) + portHeight;
return new Dimension(portWidth,overallHeight);
}
}
答案 0 :(得分:1)
super.paintComponent
方法,以便您的JPanel可以做家务绘画。