【问题标题】:Setting JScrollPane visible/invisible via JCheckBox not working通过 JCheckBox 设置 JScrollPane 可见/不可见不起作用
【发布时间】:2012-07-26 10:32:54
【问题描述】:

有一个名为“one”的 JCheckBox 和另一个名为“two”的 JCheckBox。还有一个名为“sp”的 JScrollPane。其中有一个 JTextArea。复选框的目的是隐藏和显示程序的某些部分。我简化了程序,在这里我繁琐地解释了应该发生的事情,以确保您理解程序。

这是应该发生的:

最初只有 一个 可见且未选中。如果选择一个两个应设置可见。 Whenever two is selected, sp should be set visible.取消选中复选框时,相应的组件将设置为不可见。然而,当一个被取消选中时,sp 也被设置为不可见。 (one 控制 twosp)。

问题:

选择一个时,两个可见。 But when two is selected, sp is not visible (it should be).当一个未选中而 two 被选中时,two 是不可见的(这应该会发生)。 But when one is selected, two is visible and all of a sudden sp is now visible.此后,程序按预期运行。

不过,这适用于其他 JComponent(代替 JScrollPane)。

可能出了什么问题?

package tests;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Checkboxscrollpane extends JPanel {

    private JCheckBox one, two;
    private JScrollPane sp;

    private Checkboxscrollpane() {
        Listener listener = new Listener();

        one = new JCheckBox();
        one.addActionListener(listener);
        add(one);

        two = new JCheckBox();
        two.addActionListener(listener);
        add(two);

        sp = new JScrollPane(new JTextArea("hello"));
        add(sp);

        one.setVisible(true);
        two.setVisible(false);
        sp.setVisible(false);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        one.setLocation(50, 50);
        two.setLocation(70, 70);
        sp.setLocation(90, 90);
    }

    private class Listener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == one) {
                two.setVisible(one.isSelected());
            }
            sp.setVisible(one.isSelected() && two.isSelected());
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(300, 200);
        frame.add(new Checkboxscrollpane());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

【问题讨论】:

    标签: java swing jscrollpane visibility jcheckbox


    【解决方案1】:

    您应该重新验证Checkboxscrollpane 面板。

    但您不应该在每个绘制事件上设置组件的位置:

    setLayout(null);
    
        one.setSize(100, 20);
        two.setSize(100, 20);
        sp.setSize(100, 20);
        one.setLocation(50, 50);
        two.setLocation(70, 70);
        sp.setLocation(90, 90);
    

    并删除public void paintComponent(Graphics g) { 方法。

    【讨论】:

    • 我这样做是因为我希望我的组件位于某些位置。做你说的使用默认面板布局来定位组件,这是我不想要的。
    • 是的,我忘了添加行:setLayout(null)
    猜你喜欢
    • 1970-01-01
    • 2012-05-01
    • 2012-12-17
    • 2015-04-08
    • 2016-01-09
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    相关资源
    最近更新 更多