如果我在没有paint()方法的情况下运行我的代码,则UI显示正常,但在执行paint()之后,UI仅在单击/悬停在元素上后才会显示。
我不知道为什么会发生这种情况,我已经读过某些地方我可能没有以正确的方式调用paint()方法或者我的setVisible()不正确但是我不确定
我的主要方法:
public static void main(String[] args) {
frame.createGUI();
if(list != null) {
System.out.println(list.toString());
}else{
System.out.println("Het is niet gelukt om uw stoelen juist in te delen. De zaal zit vol.");
}
}
我的createGUI方法:
public void createGUI() {
JScrollPane scrollPane = new JScrollPane();
setPreferredSize(new Dimension(450, 110));
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(scrollPane);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setTitle("Bioscoop Challenge");
JFrame.setDefaultLookAndFeelDecorated(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = this.getContentPane();
window.setLayout(new FlowLayout());
resetButton = new JButton("Reset");
seatAmountField = new JTextField("Seats total");
nField = new JTextField("Seats wanted");
methodButton = new JButton("Reservate");
errorMessage = new JLabel("Error message field");
resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
list = fillList(seatcount);
frame.validate();
frame.repaint();
}
});
methodButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
list = fillSeats(n, list);
frame.validate();
frame.repaint();
}
});
window.add(resetButton);
window.add(seatAmountField);
window.add(nField);
window.add(methodButton);
window.add(errorMessage);
pack();
validate();
setVisible(true);
}
绘画方法:
public void paint (Graphics g) {
int x = 215;
int y = 200;
int width = 40;
int height = 60;
try {
for (int i = 0; i < list.size(); i++) {
Color color;
Color color2;
if (list.get(i).IsFree()) {
color = red;
color2 = black;
} else {
color = black;
color2 = red;
}
if (list.get(i).booked) {
color = blue;
}
Rectangle r = new Rectangle(x, y, width, height);
g.setColor(color);
g.fillRect(
(int) r.getX(),
(int) r.getY(),
(int) r.getWidth(),
(int) r.getHeight()
);
g.setColor(color2);
g.drawString(list.get(i).seatNumber.toString(), (width + x) - ((width / 2) + (width / 2) / 2), (height + y) - (height / 2));
x = x + 50;
if (x == 1715) {
x = 215;
y = y + 80;
}
}
} catch(Exception e){
errorMessage = new JLabel("ERROR");
}
}
提前感谢,我们将不胜感激。
答案 0 :(得分:1)
为什么我的UI元素在执行paint()后会消失?
public void paint (Graphics g)
{
...
}
paint()方法负责绘制所有子组件,但是您不会调用默认行为。代码应该是:
public void paint (Graphics g)
{
super.paint(g);
...
}
然而,这仍然不是正确的解决方案。
你不应该重写paint()!!!
自定义绘画是通过覆盖JPanel的paintComopnent()
来完成的。然后将面板添加到框架中。现在你不会遇到任何这些问题。
阅读Custom Painting上Swing教程中的部分,了解更多信息和工作示例。