【问题标题】:Java JComboBox repaint errorJava JComboBox重绘错误
【发布时间】:2014-06-12 14:18:37
【问题描述】:

所以我在我的新程序中使用 JComboBox,但由于某种原因,每次选择某些内容时它都会重新绘制。我不希望它在选择某些内容时重新绘制整个程序,只是指定的框。请参阅下面的代码。 这里的第一部分来自包含面板的类。 首先,这里是 JComboBox 的声明以及它们在选择后编辑的标签:

private JComboBox crewview = new JComboBox(SpaceGame.stuffselector);
private JComboBox resourceview = new JComboBox(SpaceGame.stuffselector1);
private JLabel crewmember, crewmember1, crewmember2;
private JLabel resourcev, resourcev1, resourcev2;

其中的东西选择器是一个由 1 到 10 组成的数字数组

我的paint方法包含这些,因为除非我在这里有这些,否则它不起作用:

    resourceview.setLocation(400,80);
    resourcev.setLocation(455,85);
    resourcev1.setLocation(455,95);
    resourcev2.setLocation(455,105);

    crewview.setLocation(400, 20);
    crewmember.setLocation(455,25);
    crewmember1.setLocation(455,35);
    crewmember2.setLocation(455,45);

这是我的动作监听器:

    private  class crewviewListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
        lifeForm temp = SpaceGame.playership.getCrewat(crewview.getSelectedIndex());
        crewmember.setText("Name: " + temp.getName()); //set the text to the crew member
        crewmember1.setText("Race: " + temp.getRace()); 
        crewmember2.setText("Worth: " + temp.getWorth());
    }
}
private class resourceviewListener implements ActionListener{
    public void actionPerformed(ActionEvent e1){
        Resource temp1 = SpaceGame.playership.getResourceat(resourceview.getSelectedIndex());
        resourcev.setText("Name: " + temp1.getName()); //set the text to the crew member
        resourcev1.setText("Worth: " + temp1.getWorth()); 
        resourcev2.setText("Amount: " + temp1.getAmount());
    }
}

因此,正如您在阅读代码时所说的那样,我试图让它仅在选择框中的内容时更新 JLables,而不是重新绘制所有内容。

【问题讨论】:

  • 请遵守 java 命名约定。类名应以大写字母开头,并且是 CamelCase:CrewViewListener、ResoureViewListener。变量应该以小写开头,并且是camelCase:resourceView,crewMember,...
  • 你说的那个paint方法,到底是哪个组件的paint方法?
  • 哦,paintComponent 与所有这些都属于同一类,它被称为 spacePanel

标签: java jpanel actionlistener paint jcombobox


【解决方案1】:

JLabel 默认是不透明的。这意味着每当您更改标签中的文本时,标签的背景也必须重新绘制。因此包含标签的面板也将被重新绘制。

Swing 通常会确定要重新绘制的面板的剪切区域。也就是说,包含 3 个标签的矩形区域将被重新绘制,而不是整个面板。

如果您需要更多帮助,请发布 SSCCE 来说明问题。

【讨论】:

  • 所以如果我使用字符串,理论上它不会在 JComboBox 周围?
  • 我不明白你的评论。我不建议使用字符串。使用一个 Swing 组件,让它来绘制文本。
猜你喜欢
  • 2010-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多