简体   繁体   中英

Java Swing one-row scrollable container?

I'm writing an app, that needs some kind of one-row JList to store formula objects. I first tried with just buttons as objects with text on them, but it was not good. Then I made one-row JList but all it's cells have the same width, and it looks like this

在此处输入图像描述

(a scrollable area). So "<" will have the same width as others and it looks bad. Is there a way to force list cells to use their real width? Or there is any cool container that just can store objects(just text) with scrolling over them?

With buttons it looks like

在此处输入图像描述

How about you use the JTable which you can configure it to have a single row?

Example Code:

import javax.swing.JFrame; 
import javax.swing.JScrollPane; 
import javax.swing.JTable; 
  
public class JTableTest { 
    JFrame f; 
    JTable j; 
  
    JTableTest() 
    { 
     
        f = new JFrame(); 
  
        f.setTitle("JTable Example"); 
  
        String[][] data = { 
            { "F=ma", "e=mc^2", "a^2=b^2+c^2" }
        }; 
  
        String[] columnNames = { "Newton", "Einstein", "Pythagoras" }; 
  
 
        j = new JTable(data, columnNames); 
        j.setBounds(30, 40, 200, 300); //Position x,y & Size of JTable height,width
  
        JScrollPane sp = new JScrollPane(j); 
        f.add(sp); 
  
        f.setSize(500, 200); 

        f.setVisible(true); 
    } 
  
    public static void main(String[] args) 
    { 
        new JTableTest(); 
    } 
}

By default, the width of JTable cells are fixed. You can change them, however, using:

j.getColumnModel().getColumn(0).setPreferredWidth(5); //Set Width=5 for first column

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM