我正在尝试创建一个可单击的图像 JButton 并在单击后显示文本,但我似乎无法弄清楚如何使其工作。我对java很陌生,所以很多基本的解释对我很有帮助。这是我目前正在使用的代码。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class States extends JFrame {
private JTabbedPane jtpFigures = new JTabbedPane();
//State Labels
private JButton VTPanel = new JButton();
frame.add(VTPanel);
VTPanel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent);
System.out.println("The State Capital of VT is Montpelier");
}
private JButton NYPanel = new JButton();
private JButton CAPanel = new JButton();
private JButton MEPanel = new JButton();
private JButton NHPanel = new JButton();
private JButton CTPanel = new JButton();
private JButton MAPanel = new JButton();
private JButton FLPanel = new JButton();
private JButton HIPanel = new JButton();
private JButton NDPanel = new JButton();
//Images for each of the states
private ImageIcon[] stateImage = {
new ImageIcon("image/VT.png"),
new ImageIcon("image/NY.png"),
new ImageIcon("image/CA.png"),
new ImageIcon("image/ME.png"),
new ImageIcon("image/NH.png"),
new ImageIcon("image/CT.png"),
new ImageIcon("image/MA.png"),
new ImageIcon("image/FL.png"),
new ImageIcon("image/HI.png"),
new ImageIcon("image/ND.png")};
public States() {
//adds each of the images to the panel
VTPanel.setIcon(stateImage[0]);
NYPanel.setIcon(stateImage[1]);
CAPanel.setIcon(stateImage[2]);
MEPanel.setIcon(stateImage[3]);
NHPanel.setIcon(stateImage[4]);
CTPanel.setIcon(stateImage[5]);
MAPanel.setIcon(stateImage[6]);
FLPanel.setIcon(stateImage[7]);
HIPanel.setIcon(stateImage[8]);
NDPanel.setIcon(stateImage[9]);
//Adds the panels and name
add(jtpFigures, BorderLayout.CENTER);
jtpFigures.add(VTPanel, "Vermont");
jtpFigures.add(NYPanel, "New York");
jtpFigures.add(CAPanel, "California");
jtpFigures.add(MEPanel, "Maine");
jtpFigures.add(NHPanel, "New Hampshire");
jtpFigures.add(CTPanel, "Connecticut");
jtpFigures.add(MAPanel, "Massachusetts");
jtpFigures.add(FLPanel, "Florida");
jtpFigures.add(HIPanel, "Hawaii");
jtpFigures.add(NDPanel, "North Dakota");
//Sets the default index
jtpFigures.setSelectedIndex(3);
}
public static void main(String[] args) {
States frame = new States();
frame.pack();
frame.setTitle("State License Plates");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(560,250);
}
}