我有一个 JSlider,其值从 1 到 360。对于每个值,我想从数据库中获取图像并将其放入 JLabel。所以我有 360 个案例,其中唯一的区别是用于从数据库中获取相应图像的变量开关(参见下面的代码)。我知道我需要刷新我的代码,因为我的“解决方案”代码非常繁重。
我希望我清楚我想要存档的内容。下面是代码。
degreesSlider = new JSlider(); //my JSlider
degreesSlider.setMajorTickSpacing(10);
degreesSlider.setMaximum(360);
degreesSlider.setMinorTickSpacing(1);
degreesSlider.setOrientation(javax.swing.JSlider.VERTICAL);
degreesSlider.setPaintLabels(true);
degreesSlider.setPaintTicks(true);
degreesSlider.setSnapToTicks(true);
degreesSlider.setValue(0);
degreesSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
int x = degreesSlider.getValue(); //get JSlider value
int row = myJTable.getSelectedRow();
int realIndex = myJTable.convertRowIndexToModel(row);
String clickJTable = (myJTable.getModel().getValueAt(realIndex, 0).toString()); //detect my JTable row click
switch (x) {
case 1:
try {
PreparedStatement pst = conn.prepareStatement("select pol, cros from test where degrees = ? AND id_min=?");
pst.setInt(1, x); //x is the only variable of the all 360 cases
pst.setString(2, clickJTable);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
byte[] imageP = rs.getBytes("pol");
byte[] imageC = rs.getBytes("cros");
pol = new ImageIcon(imagepolars);
cros = new ImageIcon(imagecrossed);
mineralsPolars.setIcon(pol); //put image into JLabel
mineralsCrossed.setIcon(cros); //put image into JLabel
}
rs.close();
pst.close();
} catch (Exception e) {
}
break;
//case 2, 3, 4 ... 360 with the same code and the difference between them is the variable x
}
}
});