如何基于组合框选项显示JLabel。当我运行代码时,所有JLabel都会立即显示出来。
combo1.addActionListener(this);
panel.add(combo1);
panel.add(img1);
panel.add(img2);
panel.add(img3);
frame.add(panel);
img1.setText("<html> Image : <a href=\"\">Image1/</a></html>");
img2.setText("<html> Image : <a href=\"\">Image2/</a></html>");
img3.setText("<html> Image : <a href=\"\">Image3/</a></html>");
img1.setCursor(new Cursor(Cursor.HAND_CURSOR));
img2.setCursor(new Cursor(Cursor.HAND_CURSOR));
img3.setCursor(new Cursor(Cursor.HAND_CURSOR));
我使用mouseListener检查传入goWebsite()函数的标签,然后根据它添加标签的超链接。
private void goWebsite(final JLabel website) {
website.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if(website == img1){
try {
Desktop.getDesktop().browse(new URI("http://2.bp.blogspot.com/_2dxp9ORKKAM/TBZpViy7O1I/AAAAAAAABGY/zitq3ZLA8K4/s1600/red.png"));
} catch (URISyntaxException | IOException ex) {
//It looks like there's a problem
}
}
if(website == img2){
try {
Desktop.getDesktop().browse(new URI("http://www.pratikbagaria.com/wp-content/uploads/2011/04/BlueGreenPink.jpg"));
} catch (URISyntaxException | IOException ex) {
//It looks like there's a problem
}
}
if(website == img3){
try {
Desktop.getDesktop().browse(new URI("http://i.imgur.com/9OPnZNk.png"));
} catch (URISyntaxException | IOException ex) {
//It looks like there's a problem
}
}
if(website == img4){
try {
Desktop.getDesktop().browse(new URI("http://www.solidbackgrounds.com/images/three/2048x2048/2048x2048-fluorescent-orange-fluorescent-pink-fluorescent-yellow-three-color-background.jpg"));
} catch (URISyntaxException | IOException ex) {
//It looks like there's a problem
}
}
actionPerformed检查用户选择的组合框中的哪个选项,然后将正确的img JLabel传递给goWebsite()函数。
@Override
public void actionPerformed(ActionEvent e)
{
String color1 = (String)combo1.getSelectedItem();
// Possibly check if either color is 'null' here
if (color1.equals("red") )
{
goWebsite(img1);
}
if (color1.equals("blue") )
{
goWebsite(img2);
}
if (color1.equals("green") )
{
goWebsite(img3);
}
}
答案 0 :(得分:1)
尝试向ItemListener
添加JComboBox
,在调用itemStateChanged
时,检查ItemEvent#getStateChanged
是否等于ItemEvent.SELECTED
。
检查组合框中选择的内容(或使用ItemEvent#ItemSelected
)并使用您想要的信息更新单个JLabel
或使用{{使当前标签与所选项目相关联1}},但也要确保隐藏其他人
例如......
JLabel#setVisible(true)