任何人都可以帮我解决这个问题。我有一个String
数组,我想在不使用jtable的情况下在表中绘图:
String inventory[][] = {{"Chairs","Tables"},{"Bed","Sofas"}}
我使用嵌套的for
循环和drawLine
来生成此网格,但我无法将String
放在表格中。任何人都可以帮助我吗?
它不是我的程序,但这是关闭的例子,我有互联网形式。我的程序有点类似于此。
import java.awt.* ;
import java.awt.event.* ;
import javax.swing.* ;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import java.awt.*;
import java.awt.event.*;
public class testtable extends JFrame {
private static final int DRAWING_SIZE = 600;
private static final int SUBDIVISIONS = 2;
private static final int SUBDIVISION_SIZE = DRAWING_SIZE / SUBDIVISIONS;
public testtable() {
setSize(800, 800);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridx = 0;
gbc.gridy = 0;
JLabel drawingBoard = new JLabel("Drawing Board");
gbc.anchor = GridBagConstraints.SOUTH;
drawingBoard.setFont(new Font("Serif", Font.BOLD, 28));
add(drawingBoard, gbc);
JPanel panel = new JPanel() {
@Override public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(Color.GRAY);
for (int i = 1; i < SUBDIVISIONS; i++) {
int x = i * SUBDIVISION_SIZE;
g2.drawLine(x, 0, x, getSize().height);
}
for (int i = 1; i < SUBDIVISIONS; i++) {
int y = i * SUBDIVISION_SIZE;
g2.drawLine(0, y, getSize().width, y);
}
}
};
panel.setPreferredSize(new Dimension(DRAWING_SIZE, DRAWING_SIZE));
panel.setBackground(Color.WHITE);
panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
gbc.gridy++;
gbc.anchor = GridBagConstraints.CENTER;
add(panel, gbc);
JButton saveDrawing = new JButton("SAVE DRAWING");
gbc.gridy++;
gbc.anchor = GridBagConstraints.NORTH;
add(saveDrawing, gbc);
}
public static void main(String[] args) {
(new testtable()).setVisible(true);
}
}
答案 0 :(得分:0)
有点不清楚,但我想你已经覆盖了某些现有UI类的paint
或paintComponent
,并使用Graphics.drawLine
方法绘制表格。
如果这是正确的,那么你可以制作类似的嵌套循环并在里面调用Graphics.drawString
来渲染字符串。考虑字符串是按基线锚定的,而不是左上角的。
UPD。在编辑之前发布,所以答案的第一部分现在看起来很奇怪。