英文:
How to use setOpaque(true/false) in an if statement
问题
import java.awt.Color;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.*;
public class TestOpaque {
public static void main (String args[])
{
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Label with blue background");
label.setBackground(Color.BLUE);
label.setOpaque(false);
frame.add(label, BorderLayout.WEST);
JButton button = new JButton("Button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if (label.isOpaque() == false) {
label.setOpaque(true);
label.revalidate();
}
}
});
frame.add(button, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
}
}
英文:
My JLabel won't change to a blue background. The JLabel is already set to the blue background but it is not opaque until you press the button. Why is it still not opaque?
Does setOpaque work for if statements?
import java.awt.Color;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.*;
public class TestOpaque {
public static void main (String args[])
{
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Label with blue background");
label.setBackground(Color.BLUE);
label.setOpaque(false);
frame.add(label, BorderLayout.WEST);
JButton button = new JButton("Button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if (label.isOpaque() == false) {
label.setOpaque(true);
label.revalidate();
}
}
});
frame.add(button, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
}
}
答案1
得分: 1
if语句运行良好,但最好使用 if (!label.isOpaque()) {
您需要通过 repaint()
重新绘制GUI组件以显示背景:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!label.isOpaque()) {
label.setOpaque(true);
label.revalidate();
label.repaint();
}
}
});
英文:
The if statement works fine, although better to use if (!label.isOpaque()) {
You need to redraw the GUI component via repaint()
for the background to show:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!label.isOpaque()) {
label.setOpaque(true);
label.revalidate();
label.repaint();
}
}
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论