我知道您可以将ImageIcon设置为JLabel对象中的图像。我想知道是否可以使用teh .setTaxt方法(或任何其他方法)稍后通过程序更改JLabel中的图像。 这是我的计划:
import javax.swing.*;
import java.awt.* ;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.border.Border;
public class Teststuff extends JFrame implements ActionListener{
String imgname = new String();
int imgcount = 11;
JButton nxt = new JButton("Next");
JButton prev = new JButton("Previous");
JButton nxt10 = new JButton("Next 10");
JButton prev10 = new JButton("Previous 10");
public Teststuff(){
super("Pic Hider");
setLookAndFeel();
setSize(1300, 800);
BorderLayout lay = new BorderLayout();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
imgname = "teststuff/" + imgcount + ".jpg";
ImageIcon test = new ImageIcon (getClass().getResource(imgname));
Image img = test.getImage() ;
Image newimg = img.getScaledInstance( 850, 600, java.awt.Image.SCALE_SMOOTH ) ;
test = new ImageIcon( newimg );
JPanel buttons = new JPanel();
GridLayout blay = new GridLayout (0,4);
buttons.setLayout(blay);
JLabel tryi = new JLabel(test);
JLabel head = new JLabel("Secret Pic Viewer Program", JLabel.CENTER);
nxt.addActionListener(this);
prev.addActionListener(this);
nxt10.addActionListener(this);
prev10.addActionListener(this);
buttons.add(prev10);
buttons.add(prev);
buttons.add(nxt);
buttons.add(nxt10);
add(head, BorderLayout.NORTH);
add(tryi, BorderLayout.CENTER);
add(buttons, BorderLayout.SOUTH);
}
@Override
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if(source == nxt){
imgcount = imgcount + 1;
imgname = "teststuff/" + imgcount + ".jpg";
}
else if(source == prev){
imgcount = imgcount - 1;
imgname = "teststuff/" + imgcount + ".jpg";
}
else if(source == prev10){
imgcount = imgcount - 10;
imgname = "teststuff/" + imgcount + ".jpg";
}
else if(source == nxt10){
imgcount = imgcount + 10;
imgname = "teststuff/" + imgcount + ".jpg";
}
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
}
}
public static void main(String[] args) {
Teststuff dog = new Teststuff();
}
}
我刚从java开始,只是在试验。我知道这可能不是这样写的,我的变量名很随意...提前谢谢