簡體   English   中英

JButtons中的單詞換行

[英]Word Wrap in JButtons

是否有可能在JButtons中實現文本的自動換行? 我在運行時創建的動態按鈕很少。 我想在按鈕上放置自動換行功能,這樣我就可以在按鈕上看到更好的測試。 有可能嗎?

此示例使用Java的內置CSS呈現功能來執行確定何時執行換行的“繁重工作”。 它使用JLabel ,但相同的原則適用於將呈現HTML的任何組件。

FixedWidthText.java

import javax.swing.*;

class FixedWidthText {

    public static void showLabel(int width, String units) {
        String content1 = "<html>"
                + "<body style='background-color: white; width: ";
        String content2 = "'>"
                + "<h1>Fixed Width</h1>"
                + "<p>Body width fixed at ";
        String content3
                = " using CSS.  "
                + "Java's HTML"
                + " support includes support"
                + " for basic CSS.</p>";
        final String content = content1 + width + units
                + content2 + width + units + content3;
        Runnable r = () -> {
            JLabel label = new JLabel(content);
            JOptionPane.showMessageDialog(null, label);
        };
        SwingUtilities.invokeLater(r);
    }

    public static void main(String[] args) {
        showLabel(160, "px");
        showLabel(200, "px");
        showLabel(50, "%");
    }
}

截屏

160像素

在此輸入圖像描述

200像素

在此輸入圖像描述

50%

在此輸入圖像描述

使用HTML ...

button.setText("<html><center>"+"This is a"+"<br>"+"swing button"+"</center></html>");

最簡單的方法是修改另一個支持自動換行的Component,使其充當Button。 我創建了一個簡單的類來操作JTextArea來充當Button。

 public class MultiLineButton extends JTextArea implements MouseListener    {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Color defaultColor;
    private Color highlight, lightHighlight;
    private BtnState state;
    private List<ActionListener> actionListeners;

    public MultiLineButton(String text, Color defaultColor) {
        this.setEditable(false);
        this.setText(text);
        this.setLineWrap(true);
        this.setWrapStyleWord(true);
        this.addMouseListener(this);
        this.setBorder(new EmptyBorder(5, 10, 5, 10));
        state = BtnState.NORMAL;
        this.defaultColor = defaultColor;
        this.setBackground(defaultColor);
        highlight = new Color(122, 138, 153);
        lightHighlight = new Color(184, 207, 229);
        // clickedColor = new Color(r, g, b);/
        actionListeners = new ArrayList<>();
    }

    @Override
    public Color getSelectionColor() {
        return getBackground();
    }

    @Override
    public void mouseClicked(MouseEvent e) {
    }

    @Override
    public void mousePressed(MouseEvent e) {
        setBackground(lightHighlight);
        state = BtnState.CLICKED;
        repaint();
    }   

    @Override
    public void mouseReleased(MouseEvent e) {
        for (ActionListener l : actionListeners) {
            l.actionPerformed(new ActionEvent(this,     ActionEvent.ACTION_PERFORMED, this.getText()));
        }
        setBackground(defaultColor);
        state = BtnState.NORMAL;
        repaint();
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        state = BtnState.HOVERED;
        repaint();
    }

    @Override
    public void mouseExited(MouseEvent e) {
        setBackground(defaultColor);
        state = BtnState.NORMAL;
        repaint();
    }

    @Override
    public void paintBorder(Graphics g) {
        super.paintBorder(g);
        Graphics g2 = g.create();
        g2.setColor(highlight);
        switch (state) {
        case NORMAL:
            g2.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
            break;
        case HOVERED:
            g2.drawRect(1, 1, getWidth() - 3, getHeight() - 3);
            g2.setColor(lightHighlight);
            g2.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
            g2.drawRect(2, 2, getWidth() - 5, getHeight() - 5);
            break;
        case CLICKED:
            Border b = new BevelBorder(BevelBorder.LOWERED);
            b.paintBorder(this, g2, 0, 0, getWidth(), getHeight());
            break;
        }
        g2.dispose();
    }

    public void addActionListener(ActionListener l) {
        actionListeners.add(l);
    }

    public List<ActionListener> getActionListeners() {
        return actionListeners;
    }
}

BtnState只是一個常量NORMAL,HOVERED,CLICKED的枚舉

大多數代碼只是用於使JTextArea看起來像JButton,它工作得很好。 一個缺點是你失去了通過ButtonModels修改它的能力,但對於大多數應用程序來說這已經足夠了。

@Override
public void paint(Graphics pGraphics)
{
    super.paint(pGraphics);

    Graphics2D g2d = (Graphics2D) pGraphics;
    FontRenderContext frc = g2d.getFontRenderContext();

    String itemName = item.getName();
    AttributedString attributedString = new AttributedString(itemName);
    attributedString.addAttribute(TextAttribute.FONT, getFont());
    AttributedCharacterIterator iterator = attributedString.getIterator();

    LineBreakMeasurer measurer = new LineBreakMeasurer(iterator, frc);
    float wrappingWidth = getSize().width - 15;

    StringBuilder stringBuilder = new StringBuilder("<html><center>");

    int previousIndex = 0;
    while (measurer.getPosition() < itemName.length())
    {
      if (previousIndex != 0) stringBuilder.append("<br>");
      stringBuilder.append(itemName.substring(previousIndex, measurer.getPosition()));
      previousIndex = measurer.getPosition();

      measurer.nextLayout(wrappingWidth);
    }

    if (previousIndex < itemName.length())
    {
      if (previousIndex != 0) stringBuilder.append("<br>");
      stringBuilder.append(itemName.substring(previousIndex));
    }

    stringBuilder.append("</center></html>");
    setText(stringBuilder.toString());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM