Java-Swing在jtable的单元格中添加多行 [英] Java-Swing adding multiple lines in jtable's cell

查看:193
本文介绍了Java-Swing在jtable的单元格中添加多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一行jtable行中的同一个单元格中插入多个字符串。这是我将数据添加到jtable的方式。

 字符串型号,品牌,序列号; 

String itemdetails = Model + Brand + Serial

model.addRow(new Object [] {itemdetails,amountText.getText()});

问题在于,单行输出,但是我希望输出像这样

 模型//它是来自数据库的字符串
品牌//它是来自数据库的字符串
Serial //它是来自数据库的字符串

我试过这个,但是它只能处理数据

 < html> lineOne< br /> lineTwo< / html>  


解决方案

code>< html> ...< br> ...< / html> 工作得很好...

  import java.awt.Dimension; 
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

public class Test {

public static void main(String [] args){
new Test();

$ b $ public Test(){
EventQueue.invokeLater(new Runnable(){
@Override
public void run(){
尝试{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex){
ex.printStackTrace();
}

JFrame frame = new JFrame(Testing);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {
$ b $ public TestPane(){
DefaultTableModel model = new DefaultTableModel(0,1);
model.addRow(new String [] {
< html>我的老师带走了我的iPod。< br>她说他们有一条规则;< br>我无法将它带入class< br>甚至是学校。< / html>
});
model.addRow(new String [] {
< html>她说她会退还它的;< br>我会在那天退回。< br>我的耳机在< br>上点击了Play。< / html>
});
model.addRow(new String [] {
< html>)她看起来有点吃惊,< br>
+,但过了一会儿< br>
+,她确信我们被占用了"
+"并破解了一个邪恶的微笑。< br>
});
model.addRow(new String [] {
< html>< br>< br>
+她的脚趾开始点击。< br>
+她开始在自己的座位上开槽,
+并摇动说唱。< / html>
});
model.addRow(new String [] {
< html>)我的老师说她改变了主意。< br>
+她认为现在可以< br>
+将我的iPod带入课堂。< br>
+她每天都会收到。< / html>
});

setLayout(new GridBagLayout());

JTable table = new JTable(model);
table.setRowHeight(75);
add(new JScrollPane(table));

}

}

}

也许在你的代码中有其他东西,你没有向我们展示,这是造成这个问题的原因......


用动态示例更新

这是通过原始问题,但是, TableModel 代表它支持的数据,它提供 JTable 的结构来显示它。



因此,给定一堆断开值,它是 TableModel ,它将根据您的要求缝合它们。



以下示例简单地将上一首诗的每一行分割成一个数组,每行代表一个元素。



再一次,所以这首诗的每一部分都是一行... ...

 字符串数据[] [] = {
我的老师拿走了我的iPod,她说他们有规则;,我c不要把它带进课堂,甚至到学校。},
{她说她会回来的,那天我会回来的。但是她尝试我的耳机,并点击播放。},
等...


$ b $然后,该示例使用一个自定义的 TableModel ,当它被询问单元格的值时,它将使用给定的section并构建一个字符串,根据字符串包装到< html> / p>

此外,您需要点击添加按钮以添加每一行,然后才能显示

 公共类TestPane扩展JPanel {

私有MyTableModel模型;
private int index = 0;
public TestPane(){
String data [] [] = {
{我的老师拿走了我的iPod。,她说他们有一个规则;,我不能把它带到课堂上,甚至到学校去。},
{她说她会回来的,那天我会收回来的。但是后来她尝试了我的耳机,点击播放。},
{她看起来有点吃惊,但过了一段时间,她确定我们被占领了,并且破解了一个恶人微笑,},
{她的身体开始晃动。,她的脚趾开始敲打。,她开始在她的座位上开槽,并摇摆说唱。 b $ b {我的老师说她改变了主意,她认为现在好了,把我的iPod带到课堂上,她每天都会接受它。

setLayout(new BorderLayout());

model = new MyTableModel();

JTable table = new JTable(model);
table.setRowHeight(75);
add(new JScrollPane(table));

JButton add = new JButton(Add);
add.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
if(index< data.length){
model如果(index> = data.length){
add.setEnabled(false);
}
}
});

add(Add,BorderLayout.SOUTH);
}

public class MyTableModel extends AbstractTableModel {

private List< String []> rowData;

public MyTableModel(){
rowData = new ArrayList<>(25);
}

public void addRow(String [] data){
rowData.add(data);
fireTableRowsInserted(rowData.size() - 1,rowData.size() - 1);
}

@Override
public int getColumnCount(){
return 1;
}

@Override
public Class<?> getColumnClass(int columnIndex){
return String.class;

$ b @Override
public Object getValueAt(int rowIndex,int columnIndex){
Object value = null;
switch(columnIndex){
case 0:
String [] data = rowData.get(rowIndex);
StringJoiner joiner = new StringJoiner(< br>,< html>,< / html>); (字符串文本:数据){
joiner.add(text);

}
value = joiner.toString();
休息;
}
返回值;
}

@Override
public int getRowCount(){
return rowData.size();
}

}

}



<阅读如何使用表格以获取更多信息详情

i would like to insert multiple strings in the same cell in a jtable line by line.This is the way i added the data into jtable

       String Model,Brand,Serial;

       String itemdetails=Model+Brand+Serial

       model.addRow(new Object[]{itemdetails,amountText.getText()});

Here what the problem is,getting the output in single line,But i want output like this in a jtbale's cell.

      Model                    //it is string coming from database
      Brand                      //it is string coming from database
      Serial                   //it is string coming from database

i have tried this but its working only data within double quotes,not with strings.

                  "<html>lineOne <br/> lineTwo </html>"   

解决方案

So, without doing anything special, I can make <html>...<br>...</html> work just fine...

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            DefaultTableModel model = new DefaultTableModel(0, 1);
            model.addRow(new String[]{
                "<html>My teacher took my iPod.<br>She said they had a rule;<br>I couldn't bring it into class<br>or even to the school.</html>"
            });
            model.addRow(new String[]{
                "<html>She said she would return it;<br>I'd have it back that day.<br>But then she tried my headphones on<br>and gave a click on Play.</html>"
            });
            model.addRow(new String[]{
                "<html>She looked a little startled,<br>"
                + "but after just a while<br>"
                + "she made sure we were occupied<br>"
                + "and cracked a wicked smile.<br>"
            });
            model.addRow(new String[]{
                "<html>Her body started swaying.<br>"
                + "Her toes began to tap.<br>"
                + "She started grooving in her seat<br>"
                + "and rocking to the rap.</html>"
            });
            model.addRow(new String[]{
                "<html>My teacher said she changed her mind.<br>"
                + "She thinks it's now okay<br>"
                + "to bring my iPod into class.<br>"
                + "She takes it every day.</html>"
            });

            setLayout(new GridBagLayout());

            JTable table = new JTable(model);
            table.setRowHeight(75);
            add(new JScrollPane(table));

        }

    }

}

Maybe there's something else in your code, which you're not showing us, which is causing the problem...

Updated with "dynamic" example

This is going past the original question, BUT, the TableModel represents the data it's backing, it provides the structure for the JTable to show it.

So, given a bunch of "disconnected" values, it's the TableModel which is going to "sew" them together, based on your requirements.

The following example simple splits each line of the previous poem in a an array, when each line represents a element.

This is then wrapped again so each section of the poem is an array of lines...

String data[][] = {
            {"My teacher took my iPod.", "She said they had a rule;", "I couldn't bring it into class", "or even to the school."},
            {"She said she would return it;", "I'd have it back that day.", "But then she tried my headphones on", "and gave a click on Play."}, 
            etc...

The example then uses a custom TableModel, which when asked for the value of the cell, takes the given "section" and builds a String out of each line, wrapping into a <html> based String.

Further, you need to click the Add button to add each new line before it can be displayed

public class TestPane extends JPanel {

    private MyTableModel model;
    private int index = 0;
    public TestPane() {
        String data[][] = {
            {"My teacher took my iPod.", "She said they had a rule;", "I couldn't bring it into class", "or even to the school."},
            {"She said she would return it;", "I'd have it back that day.", "But then she tried my headphones on", "and gave a click on Play."},
            {"She looked a little startled,", "but after just a while", "she made sure we were occupied", "and cracked a wicked smile.", ""},
            {"Her body started swaying.", "Her toes began to tap.", "She started grooving in her seat", "and rocking to the rap."},
            {"My teacher said she changed her mind.", "She thinks it's now okay", "to bring my iPod into class.", "She takes it every day."}
        };

        setLayout(new BorderLayout());

        model = new MyTableModel();

        JTable table = new JTable(model);
        table.setRowHeight(75);
        add(new JScrollPane(table));

        JButton add = new JButton("Add");
        add.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (index < data.length) {
                    model.addRow(data[index]);
                }
                index++;
                if (index >= data.length) {
                    add.setEnabled(false);
                }
            }
        });

        add(add, BorderLayout.SOUTH);
    }

    public class MyTableModel extends AbstractTableModel {

        private List<String[]> rowData;

        public MyTableModel() {
            rowData = new ArrayList<>(25);
        }

        public void addRow(String[] data) {
            rowData.add(data);
            fireTableRowsInserted(rowData.size() - 1, rowData.size() - 1);
        }

        @Override
        public int getColumnCount() {
            return 1;
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return String.class;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object value = null;
            switch (columnIndex) {
                case 0:
                    String[] data = rowData.get(rowIndex);
                    StringJoiner joiner = new StringJoiner("<br>", "<html>", "</html>");
                    for (String text : data) {
                        joiner.add(text);
                    }
                    value = joiner.toString();
                    break;
            }
            return value;
        }

        @Override
        public int getRowCount() {
            return rowData.size();
        }

    }

}

Take a look at How to Use Tables for more details

这篇关于Java-Swing在jtable的单元格中添加多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆