import java.awt.Color;
import java.awt.Graphics;
import javax.swing.*;
public class NewJFrame extends JFrame {
private Graphics g1;
private JLabel label = new JLabel();
// holds information of all businesses
private Object[][] busInfo = new Object[10][15];
public NewJFrame() {
initComponents();
g1 = jPanel1.getGraphics();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 858, Short.MAX_VALUE));
jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 564, Short.MAX_VALUE));
jButton1.setText("Click Me");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup().addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1).addGap(425, 425, 425))
.addGroup(layout.createSequentialGroup().addGap(48, 48, 48)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(61, Short.MAX_VALUE)));
layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup().addGap(28, 28, 28)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addComponent(jButton1)));
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
printBarChart(2, 1);
System.out.println(getSize());
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(() -> {
new NewJFrame().setVisible(true);
});
}
public void printBarChart(int bestBus, int worstBus) {
busInfo[0][7] = 24325.08;
busInfo[1][7] = 15394.59;
busInfo[2][7] = 186719.84;
int y = jPanel1.getSize().height;
int x = jPanel1.getSize().width;
double balance, maxScale = (double) busInfo[bestBus][7] + 650;
int sameBusDistance, diffBusDistance = 0, scaleNum, maxPoint;
for (int i = 0; i <= 2; ++i) {
if (i == 0) {
diffBusDistance = 0;
} else {
diffBusDistance += 65;
}
// color of best business
if (i == bestBus) {
g1.setColor(Color.YELLOW);
// color of worst business
} else if (i == worstBus) {
g1.setColor(Color.RED);
// color of other businesses (neither best nor worst)
} else {
g1.setColor(Color.BLACK);
}
balance = (double) busInfo[i][7];
sameBusDistance = 25;
scaleNum = y - 100;
maxPoint = scaleNum - (scaleNum * (int) balance / (int) maxScale) + 50;
g1.drawLine(125 + diffBusDistance, y - 50, 125 + diffBusDistance, maxPoint);
g1.drawLine(125 + sameBusDistance + diffBusDistance, y - 50, 125 + sameBusDistance + diffBusDistance,
maxPoint);
g1.drawLine(125 + sameBusDistance + diffBusDistance, maxPoint, 125 + diffBusDistance, maxPoint);
jPanel1.add(label);
jPanel1.setLayout(null);
label.setSize(100, 50);
label.setFont(label.getFont().deriveFont(8f));
label.setLocation(125 + sameBusDistance + diffBusDistance - 30, maxPoint - 50);
label.setText("" + busInfo[i][7]);
}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
为图形类型变量绘制的线在为其制作标签时消失
此代码位于企业数量的for循环中。我会附上问题的图片。第一个栏很好用:
然而,第二个栏从视图中删除第一个栏及其标签:
打印条形图的标签,导致其他酒吧及其标签消失
答案 0 :(得分:1)
同样,我建议您不要使用组件上调用的getGraphics()
。到目前为止,您应该最小化并恢复GUI,以便在最小化和恢复GUI时看到绘图不稳定。我建议您在JPanel的paintComponent中绘制。
但是有一个例外 - 如果你在BufferedImage中绘图,你可以使用从它获得的Graphics对象,然后在JLabel的ImageIcon中显示图像。例如,在下面的代码中,我创建了一个填充空图像的JLabel(给它大小)。然后我按下按钮按下一些条形图数据填充图像,将图像放入ImageIcon,然后通过调用setIcon(...)
来设置带有该图标的JLabel:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import javax.swing.*;
@SuppressWarnings("serial")
public class DrawInImage extends JPanel {
private static final int IMG_W = 900;
private static final int IMG_H = 700;
private static final int GAP = 20;
private BufferedImage img = new BufferedImage(IMG_W, IMG_H, BufferedImage.TYPE_INT_ARGB);
private Icon icon = new ImageIcon(img);
private JLabel label = new JLabel(icon);
private int[] data = { 4, 2, 9, 7, 3, 8, 2, 8 };
public DrawInImage() {
JPanel btnPanel = new JPanel();
btnPanel.add(new JButton(new AbstractAction("Press Me") {
@Override
public void actionPerformed(ActionEvent arg0) {
printBarChart();
}
}));
setLayout(new BorderLayout());
add(label);
add(btnPanel, BorderLayout.PAGE_END);
}
private void printBarChart() {
// create new image
img = new BufferedImage(IMG_W, IMG_H, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics(); // get image's graphics
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 18));
// get sizes of drawing area
int totalWidth = IMG_W - 2 * GAP;
int totalHeight = IMG_H - 2 * GAP;
// number of columns including gaps
int columns = 2 * data.length + 1;
// calc the max data + 1
int maxData = 0;
for (int i : data) {
if (i > maxData) {
maxData = i;
}
}
maxData++; // + 1
for (int i = 0; i < data.length; i++) {
int x1 = GAP + ((2 * i + 1) * totalWidth) / columns;
int x2 = GAP + ((2 * i + 2) * totalWidth) / columns;
int y1 = GAP + (totalHeight * (maxData - data[i])) / maxData;
int y2 = GAP + totalHeight;
float hue = (float) i / (float) data.length;
Color c = Color.getHSBColor(hue, 1f, 1f);
g2.setColor(c);
g2.fillRect(x1, y1, x2 - x1, y2 - y1);
g2.setColor(Color.BLACK);
String text = "Data " + (i + 1);
int strX = x1;
int strY = y1 - GAP / 2;
g2.drawString(text, strX, strY);
}
g2.dispose(); // dispose of graphics objects *we* create
icon = new ImageIcon(img); // create new icon
label.setIcon(icon); // display in label
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Draw In Image");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DrawInImage());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
显示为