2011-08-08 6 views
9

제목 : JLabel을 JFrame에 맞춰야하지만 JLabel의 텍스트가 너무 길어 일부 줄 바꿈을 추가해야합니다. JLabel의 텍스트는 온라인 XML 파일에서 가져온 것이므로 줄 바꿈이 포함되도록 텍스트를 변경하기 만하면됩니다.긴 문자열을 JLabel에 맞추는 법

이 코드는 문자열 내가 문자열 V 일부 바꿈을 추가 할이 경우 XML 파일

Element element = (Element)nodes1.item(i); 
      String vær = getElementValue(element,"body"); 
      String v = vær.replaceAll("<.*>", ""); 
      String forecast = "Vær: " + v; 

에서 데이터를 추출합니다. 문자열 V는 XML 파일에서 구문 분석 된 데이터를 포함합니다. String 예측이 반환되어 JLabel에 대한 텍스트로 설정됩니다.

사전에 감사의 말을 전합니다.

답변

12

대신 JTextArea을 사용하고 포장을 켜는 것이 좋습니다. JLabel에서 그것을 수행하는 유일한 방법은 줄 바꿈을 미리 입력하지 않으면 상황에 맞지 않는 (적어도 쉽지 않은) 줄 바꿈을 넣는 것입니다.

JTextArea은 훨씬 더 유연합니다. 기본적으로 모양이 달라 보이지만 표시 속성 중 일부를 사용하여 JLabel처럼 보이게 만들 수 있습니다.


How to Use Text Areas 튜토리얼에서 가져온 간단한 수정 사용 예 -

public class JTextAreaDemo { 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() {   
       createAndShowGUI(); 
      } 
     }); 
    } 

    private static void createAndShowGUI(){ 
     final JFrame frame = new JFrame("JTextArea Demo"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     final JPanel panel = new JPanel(); 
     JTextArea textArea = new JTextArea(
       "If there is anything the nonconformist hates worse " + 
       "than a conformist, it's another nonconformist who " + 
       "doesn't conform to the prevailing standard of nonconformity.", 
       6, 
       20); 
     textArea.setFont(new Font("Serif", Font.ITALIC, 16)); 
     textArea.setLineWrap(true); 
     textArea.setWrapStyleWord(true); 
     textArea.setOpaque(false); 
     textArea.setEditable(false); 

     panel.add(textArea); 
     frame.add(panel); 
     frame.pack(); 
     frame.setVisible(true); 
    } 
} 

enter image description here

+1

+1, 구성 요소를 불투명하게 만들 수도 있습니다 (예 :'setOpaque (false)'). – mre

+0

간단한 사용 예가 포함되어 있습니다. 이것이 불필요하다고 생각되면 알려주십시오. 다시 돌려 드리겠습니다. :) – mre

+0

하지만 JTextArea의 크기를 조정하여 각 행에 특정 캐릭터를 포함시킬 수는 있습니다. 예를 들어 linebreak 전에 각 행에 30 Charcers? Cus 나는 JPanel이 화면 전체에 있고 pack()이 아니길 바래. –

5

JLabel은 HTML 텍스트를 표시 할 수 있습니다. 즉, <html>your text<html>으로 텍스트를 감싸는 경우 텍스트를 줄 바꿈 할 수 있습니다. 그것은 테스트되지 않았으므로, YMMV.

+1

+1을, 그리고 것은 좋은 튜토리얼입니다 - [방법 스윙 구성 요소에 HTML 사용] (http://download.oracle.com/javase/tutorial/uiswing/components/html.html) – mre

1

동적 텍스트에 맞게 자체의 크기를 조정하여 JLabel의를 알 수 있습니다. 당신이 LayoutManager에의 시도를 사용하지 않는 경우

:

 jLabel.setText ("A somewaht long message I would not want to 
stop"); 
     jLabel.setSize(jLabel.getPreferredSize()); 

당신이 레이아웃 매니저를 사용하는 경우이 코드 조각이 작동합니다 : 여기

 jLabel.setText ("A somewaht long message I would not want to 
stop"); 
     jLabel.validate(); 
관련 문제