小编典典

为什么JComboBox忽略PrototypeDisplayValue

java

与这两个帖子@iMohammad有关, 在单击JButtonJava时使用JButton增加/减少textArea内的字体大小并在单击JButton
Java时更改字体样式 …,我面临着一个非常有趣的问题,该问题来自于on
作为参数JComboBox传递屏幕setPrototypeDisplayValue``JComboBox's size

请如何JComboBox动态调整大小取决于Font,与我在sscce中尝试过的另一个JComponent正常工作一样

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

public class ComboBoxFontChange extends JFrame {

    private static final long serialVersionUID = 1L;
    private JComboBox cbox = new JComboBox();
    private JTextField tfield = new JTextField("Change");
    private JLabel label = new JLabel("Cash");
    private JButton button = new JButton("++ Font");
    private JTextField text;
    private JPanel panel = new JPanel();

    public ComboBoxFontChange() {
        super("Combo Box Font change");
        text = (JTextField) cbox.getEditor().getEditorComponent();
        cbox.addItem("Change");
        cbox.addItem("Cash");
        cbox.addItem("Font");
        tfield.setColumns(5);
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Font font = cbox.getFont();
                font = font.deriveFont((float) (font.getSize2D() * 1.10));
                cbox.setFont(font);
                // EDIT
                cbox.setPrototypeDisplayValue(cbox.getSelectedItem().toString());
                tfield.setFont(font);
                button.setFont(font);
                label.setFont(font);
                //panel.revalidate();
                //panel.repaint();
                pack();
            }
        });
        //panel.setLayout(new GridLayout(2, 2, 10, 10));
        panel.add(cbox);
        panel.add(label);
        panel.add(tfield);
        panel.add(button);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        add(panel);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ComboBoxFontChange frame = new ComboBoxFontChange();
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}

阅读 329

收藏
2020-09-28

共1个答案

小编典典

我调试了您的SSCCE,并且传递给的setPrototypeDisplayValue值为空字符串。将行更改为

cbox.setPrototypeDisplayValue(cbox.getSelectedItem());

使一切正常工作。删除对的调用setPrototypDisplayValue也会使程序按预期方式运行。

编辑:

另一个问题是,没有为原型显示值触发任何事件,因为您像以前一样将其设置为先前的值,并且仅在值实际更改时才触发事件。如果添加cbox.setPrototypeDisplayValue("");before
cbox.setPrototypeDisplayValue(cbox.getSelectedItem().toString()),则即使在JDK
1.6上,也可以使一切正常运行。我同意,鉴于字体已更改,应该重新计算首选大小,但至少此更改是一种解决方法。

2020-09-28