How to do getValueAt() when using an AbstractTableModel - java

I'm trying to make an program that shows all files in the temerary folder using an AbstractTableModel but how do i code the getValueAt() method.
The names of the files should be in the first column and the file path should be in the second column.
I nulled it for now but can someone show me hoe i should code it?
This is what i got so far:
public class UI extends JFrame {
private JPanel contentPane;
private JTable table;
File[] dir = new File(System.getProperty("java.io.tmpdir")).listFiles();
public static void main(String[] args) {
public UI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 542, 422);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTabbedPane tabbedPane = new JTabbedPane(SwingConstants.TOP);
tabbedPane.setBounds(0, 0, 526, 384);
contentPane.add(tabbedPane);
JPanel panel = new JPanel();
tabbedPane.addTab("Temp Files", null, panel, null);
panel.setLayout(null);
final AbstractTableModel myAbstractTableModel = new AbstractTableModel() {
#Override
public int getColumnCount() {
return 2;
}
#Override
public int getRowCount() {
return dir.length;
}
#Override
public Object getValueAt(int arg0, int arg1) {
return null;
}
};
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 11, 402, 334);
panel.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
table.setModel(myAbstractTableModel);
}
}

In your example, arg0 is the row and arg1 is the col, so dir[arg0] is the File for each row. In your implementation of getValueAt(), return file.getName() or file.getPath() as indicated by the col value. EnvTableTest is a related example that uses the more descriptive parameter names.

Related

Java JTable set JButton and JTextField but output shows nothing

I have written the following code to make a JTable. I am practicing to edit value on row by setting JButton and JTextField but the output of JButton and JTextField is unseen.
public class quotingtable extends javax.swing.JFrame {
DefaultTableModel model;
JTable table;
String col[] = { "Symbol", "Name", "LastPrice" };
JButton button = new JButton("Set Value at 1, 1");
JTextField text = new JTextField(20);
JPanel panel = new JPanel();
public void start() {
model = new DefaultTableModel(col,50);
table = new JTable(model) {
#Override
public boolean isCellEditable(int arg0 ,int arg1) {
return false;
}
};
panel.add(table);
panel.add(text);
panel.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String value = text.getText();
model.setValueAt(value, 1, 0);
}
});
JScrollPane pane = new JScrollPane(table);
table.setValueAt("VNM", 0, 0);
add(pane);
setSize(500, 400);
setLayout(new FlowLayout());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String args[]) {
new quotingtable().start();
}
}

How to create a custom JTable?

I am making a chat application in Java. They can add friends and chat with them.
Here is my add friend JFrame idea:
I tried to google search Multi jpanel in one jscrollpane but I found nothing. I ended up with custom JTable. I want to create a custom JTable which have JLabels in different position in each slot. Users can just select a slot in JTable, then they can use the JButton below to chat with them.
Is it possible to do this in Java. Is yes, please share your idea. Thanks.
Here is a proposal. But it contains some flaws yet
Size propagation is fiexed (may be better client or server based sizing)
No event delegation to underlying Component
Performance, because heavyweight panel instances are created frequently inside paint loop
But here is how it can be done. The code is separated into parts.
A value class
Just a simple class to represent the date inside your panels for each cell.
class Value {
public final String text;
public final boolean flag;
public Value(String text, boolean flag) {
this.text = text;
this.flag = flag;
}
}
My individual panel class
The representation can be modelled within a gui editor like google's window builder. This panel makes use of the value and displays it accordingly.
public class MyPanel extends JPanel {
public MyPanel(Value v) {
JLabel lblNewLabel = new JLabel(v.text);
add(lblNewLabel);
JCheckBox chckbxSomeValue = new JCheckBox("some value");
chckbxSomeValue.setSelected(v.flag);
add(chckbxSomeValue);
}
}
A table cell renderer class
Just returns some panel instance showing up the desired values.
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
class MyPanelCellRenderer implements TableCellRenderer {
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
return new MyPanel((Value)value); // maybe performance problem
}
}
A custom table model
import javax.swing.table.DefaultTableModel;
class MyTableModel extends DefaultTableModel {
public MyTableModel() {
super(new Object[][] {
new Object[] { 1, new Value("asdf", true) },
new Object[] { 2, new Value("qwer", false) } },
new String[] {"Id", "MyPanel" });
}
Class[] columnTypes = new Class[] { Integer.class, Value.class };
MyTableModel(Object[][] data, Object[] columnNames) {
super(data, columnNames);
}
public Class getColumnClass(int columnIndex) {
return columnTypes[columnIndex];
}
}
A frame class
import java.awt.BorderLayout;
public class MyFrame {
JFrame frame;
private JTable table;
public MyFrame() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
table = new JTable();
table.setModel(new MyTableModel());
table.setFillsViewportHeight(true);
table.getColumnModel()
.getColumn(1)
.setCellRenderer(new MyPanelCellRenderer());
table.setRowHeight(40); // static sizing
JScrollPane scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
scrollPane.setViewportView(table);
}
}
Main Function
import java.awt.EventQueue;
public class MyApp {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyFrame window = new MyFrame();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
The final result
The panel MyPanel is created using eclipse and google's window builder
This is a completely different approach using neither a table nor a list. It uses panels as items arranged as a list inside of another panel. This solution doesn't requires any further modification to delegate any events to the underlying controls. The events are processed natively. The idea comes from this post. I have separated the logic into two parts for now.
JPanelList class
This class is a JPanel and maintains a list of such. ATM they can be added using the methods addPanel and addPanels.
public class JPanelList extends JPanel {
private static final long serialVersionUID = 1L;
private JPanel mainList;
private List<JPanel> panels = new ArrayList<JPanel>();
public JPanelList() { this(new ArrayList<JPanel>()); }
public JPanelList(List<JPanel> panels) {
setLayout(new BorderLayout());
mainList = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.weighty = 1;
mainList.add(new JPanel(), gbc);
add(new JScrollPane(mainList));
addPanels(panels);
}
public void addPanels(List<JPanel> panels) {
for (JPanel panel : panels)
addPanel(panel);
}
public void addPanel(JPanel panel) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
mainList.add(panel, gbc, 0);
panels.add(panel);
validate();
repaint();
}
}
JListFrame test class with main function
public class JPanelListFrame {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JPanelListFrame window = new JPanelListFrame();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public JPanelListFrame() {
frame = new JFrame();
frame.setBounds(100, 100, 210, 192);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanelList panelList = new JPanelList();
frame.getContentPane().add(panelList, BorderLayout.CENTER);
JButton btnAddMypanel = new JButton("Add MyPanel");
btnAddMypanel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// just add a MyPanel with a Value containing a
// "asdf" and a random boolean
panelList.addPanel(new MyPanel(new Value("asdf",
(int) (2 * Math.random()) % 2 == 0)));
}
});
panelList.add(btnAddMypanel, BorderLayout.SOUTH);
}
}
One drawback with this solution is that the selection mechanics are lost. When selecting elements is a key requirement maybe a JList might be more appropriate. Another thing is that the items are not rendered as they would be rendered inside a JList or JTable e.g. using fancy borders. This can be solved by somehow adding a border decorator before adding the panels into the mainList of the JPanelList.

CellRenderer - making multiple cells bold

I would like to make multiple cells bold, I have arraylist with the cell names that should be bold but doesn't seem to work. My Arraylist with the cells that I want to bold is called bibNumbers, so far tried converting the arralist into array and putting the if statement into a loop and loop results into bolding variable
//edit
added example, so now id want all the 0's and 1's in the column 2 to be bold.
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
public class as extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTable table;
private ArrayList<String> ShadowBibNumber;
/**
* Launch the application.
*/
public static void main(String[] args) {
as frame = new as();
frame.setVisible(true);
}
/**
* Create the frame.
*/
public as() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
ShadowBibNumber = new ArrayList<String>();
ShadowBibNumber.add("0");
ShadowBibNumber.add("1");
JLabel lblNewLabel = new JLabel("New label");
contentPane.add(lblNewLabel, BorderLayout.NORTH);
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.addColumn("column 0");
tableModel.addColumn("column 1");
tableModel.addColumn("column 2");
tableModel.addColumn("column 3");
tableModel.addColumn("column 4");
new JScrollPane(table);
table = new JTable(tableModel);
table.setEnabled(false);
table.setPreferredScrollableViewportSize(new Dimension(200, 100));
JScrollPane scrollPaneForTable = new JScrollPane(table);
contentPane.add(scrollPaneForTable, BorderLayout.CENTER);
for (int i = 0; i < 20; ++i) {
tableModel
.addRow(new Object[] { i, i, i, i, i });
}
table.getColumn("column 2").setCellRenderer(new boldRenderer());
}
class boldRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
Component cellComponent = super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
for (Object x: ShadowBibNumber) {
if (table.getValueAt(row, 2).equals(x)) {
cellComponent.setFont(cellComponent.getFont().deriveFont(
Font.BOLD));
} else {
cellComponent.setFont(cellComponent.getFont().deriveFont(
Font.PLAIN));
}
}
return cellComponent;
}
} }

Prevent JComboBox rendering on update JLabel

I'm doing an application that play a video and in a JLabel i'm showing timecode of video. Also have a JCombobox that allows to change subtitles of the video.
That JCombobox has a ListCellRenderer that change default output of each item of combobox.
Problem is that each time the JLabel change its value the JCombobox is rendered again.
I think this is a waste of resources there is some way of change that behavior?.
There is the code relative to the JComboBox. The JLabel is modified by a swing.Timer each second.
JComboBox comboBox = new JComboBox<>();
comboBox.setEditable(false);
DefaultComboBoxModel<File> defaultComboBox = new DefaultComboBoxModel<>();
for (File f : Player.capitulo.getFicheros()) {
if (f.getAbsolutePath().endsWith(".srt")) {
System.out.println(f.getAbsolutePath());
defaultComboBox.addElement(f);
}
}
comboBox.setModel(defaultComboBox);
comboBox.setRenderer(new ListRenderer());
public class ListRenderer implements ListCellRenderer<File> {
protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
#Override
public Component getListCellRendererComponent(JList<? extends File> list,
File value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel renderer = new JLabel();
// JLabel renderer = (JLabel) defaultRenderer
// .getListCellRendererComponent(list, value, index, isSelected,
// cellHasFocus);
if (value != null) {
Path p = value.toPath();
System.out.println(p.getParent());
String language = value.getName().trim().replace(".srt", "");
language = language.substring(language.lastIndexOf(".") + 1,
language.length());
// System.out.println(language.length());
if (language.length() == 3) {
renderer.setText(language);
} else {
renderer.setText("Subtitulo " + (index + 1));
}
}
return renderer;
}
}
UPDATED: Here is an example that reproduce the problem
Ok, here is SSCCE code. Doing the example i noticed that when JLabel es in the same line of JCombobox reproduce the same problem but when is in other line doesn't happen.
public class Example extends JFrame {
private JPanel contentPane;
private JLabel lblNewLabel;
private JComboBox<String> comboBox;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Example frame = new Example();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Example() {
initGUI();
}
private void initGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 428, 362);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
lblNewLabel = new JLabel("New label");
contentPane.add(lblNewLabel, BorderLayout.WEST);
Timer t = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Random r = new Random();
lblNewLabel.setText(String.valueOf(r.nextInt()));
}
});
t.start();
comboBox = new JComboBox<>();
comboBox.setRenderer(new ListCellRenderer<String>() {
#Override
public Component getListCellRendererComponent(
JList<? extends String> list, String value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = new JLabel("");
System.out.println("Pass");
return label;
}
});
contentPane.add(comboBox, BorderLayout.CENTER);
}
}

Different imageIcon in different cells in JTable

I think I got the imageIcon to show up differently in each cell but for some reason when I compile it, the images don't show up. It displays the name of the image but the image itself doesn't show up. Here is an image. http://i49.tinypic.com/r9ibrn.jpg
public class movies extends JFrame {
public movies() {
initComponents();
}
private void initComponents() {
panel = new JPanel();
logo = new JLabel();
pane = new JScrollPane();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBackground(new Color(255, 255, 204));
setResizable(false);
panel.setBackground(new Color(51, 51, 51));
panel.setPreferredSize(new Dimension(290, 75));
logo.setIcon(new ImageIcon(getClass().getResource("logo.png")));
logo.setName("logo");
logo.setRequestFocusEnabled(false);
logo.setVerifyInputWhenFocusTarget(false);
logo.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
ImageIcon icon1 = new ImageIcon("1.jpg");
ImageIcon icon2 = new ImageIcon("2.jpg");
ImageIcon icon3 = new ImageIcon("3.jpg");
String[] columnNames = {"Section 1", "Section 2"};
Object[][] data =
{
{icon1 + " Music", icon2 + " News"},
{icon2 + " Movies"},
{icon3 + " Games"},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable( model )
{
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.setBackground(new Color(255, 255, 204));
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
table.setRowHeight(50);
pane.setViewportView(table);
table.getColumnModel().getColumn(0).setResizable(false);
table.getColumnModel().getColumn(1).setResizable(false);
}
public static void main(String args[]) {
public void run() {
new movies().setVisible(true);
}
});
}
private JLabel logo;
private JScrollPane pane;
private JPanel panel;
}
You can pass in the name of the image when you call the new ImageRenderer constructor (read this).
public class Movies extends javax.swing.JFrame {
public Movies() {
initComponents();
table.getColumnModel().getColumn(1).setCellRenderer(new ImageRenderer("1.jpg"));
table.getColumnModel().getColumn(0).setCellRenderer(new ImageRenderer("2.jpg"));
}
}
class ImageRenderer extends DefaultTableCellRenderer {
ImageIcon icon = null;
ImageRenderer(String iconName) {
icon = new ImageIcon(getClass().getResource(iconName));
}
}

Categories