我用 Java 制作了一個簡單的 GUI。問題是,當我在按鈕和復選按鈕之前向框架添加標簽時,將滑鼠懸停在按鈕上時會出現奇怪的閃爍,并且 GUI 看起來不正確。但是當我在按鈕和復選按鈕后添加標簽時,一切正常。為什么會這樣?
這是我的代碼:
package javaapplication13;
import java.awt.*;
import javax.swing.*;
public class JavaApplication13 {
public static void main(String[] args) {
ButtonFrame bf = new ButtonFrame();
}
}
class ButtonFrame extends JFrame {
public ButtonFrame() {
JButton b1 = new JButton("1. Dugme");
JButton b2 = new JButton("2. Dugme");
JLabel l1 = new JLabel();
JCheckBox c1 = new JCheckBox("Prvo dugme");
JCheckBox c2 = new JCheckBox("Drugo dugme");
Container cp = getContentPane();
setTitle("Dugme");
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
this.add(b1);
this.add(b2);
this.add(c1);
this.add(c2);
this.add(l1);
b1.setBounds(20, 30, 90, 20);
b2.setBounds(20,70,90,20);
l1.setBounds(70,120,90,20);
c1.setBounds(120,30,120,20);
c2.setBounds(120,70,120,20);
l1.setText("");
}
}
uj5u.com熱心網友回復:
當我使用 JDK 17 在我的 Windows 10 計算機上復制和運行代碼時,我沒有看到你聲稱得到的閃爍。但是,當我在添加按鈕和復選框之前更改代碼并將標簽添加到框架時(正如您在問題中所述),我確實看到了“閃爍”。
盡管您已經接受了@Antoniosss 的
在您的代碼中將布局管理器設定為 null 時(正如@Antoniossss 在他的回答中所說),GUI 看起來像下面的螢屏截圖。(同樣,我還設定了 的文本,JLabel以便您可以看到它。)

如您所見,這兩個螢屏截圖實際上是相同的。
為了完整起見,這是您的代碼,經過我的更改,生成了上述螢屏截圖。如您所見,我移動了該行this.add(l1)并添加了該行cp.setLayout(null)。
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ButtonFrame extends JFrame {
public ButtonFrame(){
JButton b1 = new JButton("1. Dugme");
JButton b2 = new JButton("2. Dugme");
JLabel l1 = new JLabel();
JCheckBox c1 = new JCheckBox("Prvo dugme");
JCheckBox c2 = new JCheckBox("Drugo dugme");
Container cp = getContentPane();
cp.setLayout(null); // Added this line.
setTitle("Dugme");
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
this.add(l1);
this.add(b1);
this.add(b2);
this.add(c1);
this.add(c2);
// this.add(l1);
b1.setBounds(20, 30, 90, 20);
b2.setBounds(20,70,90,20);
l1.setBounds(70,120,90,20);
c1.setBounds(120,30,120,20);
c2.setBounds(120,70,120,20);
l1.setText("label");
}
public static void main(String[] args) {
ButtonFrame bf = new ButtonFrame();
}
}
uj5u.com熱心網友回復:
這是因為LayoutManager您無論如何都不想使用默認值,因為您對組件使用了嚴格的界限。洗掉布局管理器
setLayout(null);
它會按預期作業
public ButtonFrame(){
setLayout(null); //this will do the trick
JButton b1 = new JButton("1. Dugme");
...rest of your code
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/334605.html
