I have Jtable that I want to add to the main JFrame when a MenuItem is triggered, but the problem is that will not show.
If I add the table to panel from the beginning it shows, but I need it to show when the action occures.
Here is the main class that creates the frame(I removed several items which are not needed to be posted like creating the menubar,menu etc):
package gestiune;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.awt.*;
public class Gestiune {
static Gest gest;
static Action actListaAng;
static JPanel panouPrinc;
static ListaAngajati lang;
static JMenuItem listaAng;
static class Gest extends JFrame{
public Gest(){
actListaAng = new ActListaAng("List");
listaAng=new JMenuItem(actListaAng);
panouPrinc = new JPanel();
panouPrinc.setBackground(Color.white);
Container cp = getContentPane();
cp.add(panouPrinc);
pack();
setTitle("Some title");
setSize(1000,700);
setLocation(0,0);
setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
}
public static void main(String[] args) {
gest = new Gest();
}
//class for listing action
static class ActListaAng extends AbstractAction {
public ActListaAng(String text){
super(text);
}
#Override
public void actionPerformed(ActionEvent e) {
lang = new ListaAngajati();
panouPrinc.add(lang);
}
}
}
Here is the table class:
package gestiune;
import javax.swing.*;
import java.awt.*;
public class ListaAngajati extends JPanel {
JTable tabel;
JScrollPane panouScroll;
public ListaAngajati() {
panouScroll = new JScrollPane(tabel);
String[] numeCol = {
"Nume",
"Prenume",
"Categorie",
"Data Adaugare",
"Ultima Modificare"
};
Object[][] linii = {
{"verban","adrian","sds","16-03-1989","acum"}
};
tabel = new JTable(linii,numeCol);
setLayout(new BorderLayout());
add(tabel.getTableHeader(), BorderLayout.PAGE_START);
add(panouScroll);
add(tabel);
}
}
I've tried several things, like using repaint on ActionEvent, or directly into the the table class......and while if I add lang=new ListaAngajati(); panouPrinc.add(lang); directly into the main jframe constructor works, from action it doesn't, so I kind of run out of options, so can someone give me a hand?
If you revalidate() and repaint() it works. You should always revalidate() and repaint() after adding a component during runtime.
#Override
public void actionPerformed(ActionEvent e){
lang=new ListaAngajati();
panouPrinc.add(lang);
panouPrinc.revalidate();
panouPrinc.repaint();
}
Also there was no button to click on, so I added a button here, and added the Action
Container cp=getContentPane();
JButton button = new JButton(new ActListaAng("Action"));
button.setText("Open");
cp.add(button, BorderLayout.PAGE_START);
cp.add(panouPrinc);
pack();
Works fine.
As a side note, you really need go through a tutorial on static. You're totally overly and unnecessarily using it.
call updateUI() or repaint() or revalidate(); as the table is added but the UI is not getting refreshed.
//Global Declaration
private Vector<Vector<String>> data; //used for data from database
private Vector<String> header; //used to store data header
private int count=0;
//Display only header on form load
//create header for the table
header = new Vector<String>();
header.add("Column1");
header.add("Column2");
...
model=new DefaultTableModel(data,header);
table = new JTable(model);
//in actionPerformed()
public void actionPerformed(ActionEvent ae){
if(ae.getSource()==yourMenuItem){
data=get();
for(int i=0;i<count;i++){
Object[] d={data.get(i).get(0),data.get(i).get(1),data.get(i).get(2)};
model.addRow(d);
}
}
}
This will help you to get data from database
get(){
Vector<Vector<String>> doublevector = new Vector<Vector<String>>();
Connection conn = dbConnection();//Your Database connection code
PreparedStatement pre1 = conn.prepareStatement("select * from Table");
ResultSet rs1 = pre1.executeQuery();
while(rs1.next())
{
Vector<String> singlevector = new Vector<String>();
singlevector.add(rs1.getString(1));
singlevector.add(rs1.getString(2));
....
doublevector.add(singlevector);
count++
}
return doublevector;
}
Related
I have 2 classes. Both implements runnable to create the GUI. The first one is the main, and the second one is the secondary class.
I want within the actionlistener of the main class to startup the secondary class.
Here is the code (the two classes are separated files):
public class Main implements Runnable
{
private JTextField txt1, txt2;
private JLabel lbl1, lbl2;
public void run()
{
JFrame frame = new JFrame("Secondary");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = frame.getContentPane();
JPanel background = new JPanel();
background.setLayout(new BoxLayout(background, BoxLayout.LINE_AXIS));
.........
// Horizontally adding the textbox and button in a Box
Box box = new Box(BoxLayout.Y_AXIS);
......
background.add(box);
pane.add(background);
frame.pack();
frame.setVisible(true);
}
private class SListener implements ActionListener
{
public void actionPerformed(ActionEvent a)
{
Secondary s = new Secondary();
}
}
public static void main (String[] args)
{
Main gui = new Main();
SwingUtilities.invokeLater(gui);
}
}
public class Secondary implements Runnable
{
private JTextField txt1, txt2;
private JLabel lbl1, lbl2;
public Secondary()
{
Secondary gui = new Secondary();
SwingUtilities.invokeLater(gui);
}
public void run()
{
JFrame frame = new JFrame("Secondary");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = frame.getContentPane();
JPanel background = new JPanel();
background.setLayout(new BoxLayout(background, BoxLayout.LINE_AXIS));
.........
// Horizontally adding the textbox and button in a Box
Box box = new Box(BoxLayout.Y_AXIS);
......
background.add(box);
pane.add(background);
frame.pack();
frame.setVisible(true);
}
}
I want to keep the code in two files, I don't want to mixed the two classes in one file.
As you can see from the code, in the Secondary class, in it's constructor I create an Instance of the Secondary class and I run the gui so that when the Instance of this class is created in the Main class, to run the gui.
Unfortunately this technique is not working.
Any ideas?
Thanks
The following line are complety wrong:
public Secondary(){
Secondary gui = new Secondary();
SwingUtilities.invokeLater(gui);
}
Each time you call new Secondary() somewhere in your code, the above code will be triggered, which in turn calls new Secondary() again, and again, and again, ... and your program is blocked.
You probably want to replace it either by
public Secondary(){
SwingUtilities.invokeLater(this);
}
which will avoid the loop, but this is weird behaviour for a constructor.
It makes much more sense to switch to an empty constructor (or delete it all together)
public Secondary(){
}
and rewrite your listener to
public void actionPerformed(ActionEvent a){
Secondary s = new Secondary();
SwingUtilities.invokeLater( s );
}
I would recommend that you completely re-design your program. I find that it is most helpful to gear my GUI's towards creation of JPanels, not top level windows such as JFrame, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. I find that this greatly increase the flexibility of my GUI coding, and is exactly what I suggest that you do. So...
Your first class creates a JPanel that is then placed into a JFrame.
In the first class's ActionListener, create an instance of the 2nd class, place it into a JDialog (not a JFrame), and then display it.
For example,
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class TwoWindowEg {
public TwoWindowEg() {
// TODO Auto-generated constructor stub
}
private static void createAndShowGui() {
GuiPanel1 mainPanel = new GuiPanel1();
JFrame frame = new JFrame("Main GUI");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class GuiPanel1 extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = 650;
private GuiPanel2 guiPanel2 = new GuiPanel2(); // our second class!
private JDialog dialog = null; // our JDialog
public GuiPanel1() {
setBorder(BorderFactory.createTitledBorder("GUI Panel 1"));
add(new JButton(new LaunchNewWindowAction("Launch New Window")));
add(new JButton(new DisposeAction("Exit", KeyEvent.VK_X)));
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class LaunchNewWindowAction extends AbstractAction {
public LaunchNewWindowAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
if (dialog == null) {
// get the Window that holds this JPanel
Window win = SwingUtilities.getWindowAncestor(GuiPanel1.this);
dialog = new JDialog(win, "Second Window", ModalityType.APPLICATION_MODAL);
dialog.add(guiPanel2);
dialog.pack();
}
dialog.setVisible(true);
}
}
}
class GuiPanel2 extends JPanel {
public GuiPanel2() {
setBorder(BorderFactory.createTitledBorder("GUI Panel 1"));
add(new JLabel("The second JPanel/Class"));
add(new JButton(new DisposeAction("Exit", KeyEvent.VK_X)));
}
}
class DisposeAction extends AbstractAction {
public DisposeAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Component comp = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(comp);
win.dispose();
}
}
Alternatively, you could swap JPanel "views" using a CardLayout, but either way, you will want to avoid showing two JFrames. Please have a look at The Use of Multiple JFrames, Good/Bad Practice?.
I'm using IntelliJ GUI Builder to design a GUI for my application. In it, there is a JTable inside a JScrollPane that doesn't seem to be working. Firstly, I can't get the column headers to display. Second, table clicking is not working. It acts as if I'm clicking 3 rows down from where I actually am, both in default row selection and in any MouseListeners I implement. Lastly, if the table exceeds the size of the JScrollPane, it just ignores the last X rows and doesn't provide a scroll bar to view them.
I've reworked the project a couple times now, trying extensions of AbstractTableModel, then DefaultTableModel, and lately I have tried ditching a custom TableModel altogether and just using a DefaultTableModel constructor to no avail. Here is all relevant code (some of it is auto-generated by the GUI Builder and I can't modify it directly).
BaldGUI.java (the main gui)
package client;
import client.DataTypes.Record;
import client.DataTypes.RecordSet;
import client.GuiElements.FileTree;
import client.GuiElements.RecordsTable;
import client.GuiElements.TextConsole;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
public class BaldGUI extends JFrame {
//Menu
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem newBatchItem = new JMenuItem("New Batch");
private JMenuItem saveBatchItem = new JMenuItem("Save Batch");
private JMenuItem loadBatchItem = new JMenuItem("Load Batch");
private static String rootDir = "C:/Users/wf1946/IdeaProjects/DocumentumLoaderTest01/data";
private JPanel mainPanel;
private JPanel LeftSideBarPanel;
private JTree fileTree;
private JButton AddFileButton;
private JButton ChangeDirectoryButton;
private JButton AddDirectoryButton;
private JCheckBox IncludeSubDirectoriesCheckBox;
private JScrollPane DataTableWrapper;
private JTable DataTable;
private JEditorPane Console;
private JScrollPane ConsoleScroller;
public BaldGUI() {
$$$setupUI$$$();
this.loadComponents();
this.AddFileButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
((RecordsTable) DataTable).addItem(new Record());
}
});
this.add(this.mainPanel);
}
private void loadComponents() {
//Menu
this.setJMenuBar(this.menuBar);
this.menuBar.add(this.fileMenu);
this.fileMenu.add(this.newBatchItem);
this.fileMenu.add(this.saveBatchItem);
this.fileMenu.add(this.loadBatchItem);
//Selection handler for the file tree
this.fileTree.addTreeSelectionListener(new TreeSelectionListener() {
#Override
public void valueChanged(TreeSelectionEvent e) {
TreePath path = e.getPath();
if (!fileTree.getModel().isLeaf(path.getLastPathComponent())) { //Directory
AddDirectoryButton.setEnabled(true);
IncludeSubDirectoriesCheckBox.setEnabled(true);
AddFileButton.setEnabled(false);
} else { //File
AddFileButton.setEnabled(true);
AddDirectoryButton.setEnabled(false);
IncludeSubDirectoriesCheckBox.setEnabled(false);
}
}
});
}
//Getters
public JEditorPane getConsole() {
return Console;
}
public JPanel getMainPanel() {
return mainPanel;
}
public JTree getFileTree() {
return fileTree;
}
public JTable getDataTable() {
return this.DataTable;
}
public JCheckBox getIncludeSubDirectoriesCheckBox() {
return IncludeSubDirectoriesCheckBox;
}
public JScrollPane getDataTableWrapper() {
return DataTableWrapper;
}
private void createUIComponents() {
this.Console = new TextConsole();
this.fileTree = new FileTree(this, new File(this.rootDir));
RecordSet rs = new RecordSet();
for (int i = 0; i < 10; i++) rs.add(new Record());
this.DataTable = new RecordsTable(new DefaultTableModel(rs.getData(), RecordsTable.colNames), this);
this.DataTableWrapper = new JScrollPane(this.DataTable);
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* #noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
mainPanel = new JPanel();
mainPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
mainPanel.setMinimumSize(new Dimension(1080, 810));
mainPanel.setPreferredSize(new Dimension(1080, 810));
LeftSideBarPanel = new JPanel();
LeftSideBarPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
LeftSideBarPanel.setMinimumSize(new Dimension(220, 35));
LeftSideBarPanel.setPreferredSize(new Dimension(220, 600));
mainPanel.add(LeftSideBarPanel);
fileTree.setPreferredSize(new Dimension(200, 530));
fileTree.setShowsRootHandles(true);
LeftSideBarPanel.add(fileTree);
AddFileButton = new JButton();
AddFileButton.setPreferredSize(new Dimension(100, 25));
AddFileButton.setText("Add File");
LeftSideBarPanel.add(AddFileButton);
ChangeDirectoryButton = new JButton();
ChangeDirectoryButton.setPreferredSize(new Dimension(100, 25));
ChangeDirectoryButton.setText("Change Root");
LeftSideBarPanel.add(ChangeDirectoryButton);
AddDirectoryButton = new JButton();
AddDirectoryButton.setPreferredSize(new Dimension(100, 25));
AddDirectoryButton.setText("Add Directory");
LeftSideBarPanel.add(AddDirectoryButton);
IncludeSubDirectoriesCheckBox = new JCheckBox();
IncludeSubDirectoriesCheckBox.setPreferredSize(new Dimension(100, 22));
IncludeSubDirectoriesCheckBox.setText("Subdirectories");
LeftSideBarPanel.add(IncludeSubDirectoriesCheckBox);
DataTableWrapper.setPreferredSize(new Dimension(845, 600));
mainPanel.add(DataTableWrapper);
DataTable.setFillsViewportHeight(true);
DataTableWrapper.setViewportView(DataTable);
ConsoleScroller = new JScrollPane();
mainPanel.add(ConsoleScroller);
Console.setEnabled(false);
Console.setPreferredSize(new Dimension(1070, 195));
ConsoleScroller.setViewportView(Console);
}
/**
* #noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return mainPanel;
}
}
RecordsTable.java
package client.GuiElements;
import client.ActionListeners.RightClickMenuItemClick;
import client.ActionListeners.TableRightClickHandler;
import client.BaldGUI;
import client.DataTypes.Record;
import client.DataTypes.RecordSet;
import javax.swing.*;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.util.ArrayList;
//Table to store the records
public class RecordsTable extends JTable {
//Status codes returned to calling functions to indicate the success or failure of the new record
public static final int APPEND_SUCCESS_CODE = 1;
public static final int APPEND_FAIL_DUPLICATE_CODE = 2;
public static final String[] colNames = {"Status", "File", "Full Path", "Title", "Form Date",
"Form No.", "Language Code", "Filed", "Approval Date", "Filed Form No."};
private RecordSet data = new RecordSet();
//Parent form
BaldGUI parent;
//Right-click menu for table item
JPopupMenu itemRightClickMenu = new JPopupMenu();
JMenuItem itemEdit = new JMenuItem("Edit Record");
JMenuItem itemDelete = new JMenuItem("Remove Record");
public RecordsTable(DefaultTableModel model, BaldGUI form) {
super(model);
this.parent = form;
this.itemRightClickMenu.add(itemEdit);
this.itemRightClickMenu.add(itemDelete);
this.itemEdit.addMouseListener(new RightClickMenuItemClick(this, itemEdit));
this.itemDelete.addMouseListener(new RightClickMenuItemClick(this, itemDelete));
this.addMouseListener(new TableRightClickHandler(this));
this.updateTable();
}
//Attempts to add a new row to the table
//Returns APPEND_FAIL_DUPLICATE_CODE if the selected file is already in the table
//Returns APPEND_SUCCESS_CODE if the record is successfully added
public int addItem(Record newRecord) {
TextConsole tc = ((TextConsole)this.parent.getConsole());
if(this.itemInData(newRecord)) {
tc.addText(
"File " + newRecord.getFileName() + " already included.\n", TextConsole.redStyle
);
return this.APPEND_FAIL_DUPLICATE_CODE;
}
this.data.add(newRecord);
tc.addText("File " + newRecord.getFileName() + " added successfully.\n", TextConsole.greenStyle);
this.updateTable();
return this.APPEND_SUCCESS_CODE;
}
//Updates the table to display any new data
public void updateTable() {
}
//Returns true if the record is already in the table
//Record equality is defined based on the full path to the file
public boolean itemInData(Record item) {
for( Record r : data) {
if(r.equals(item)) return true;
}
return false;
}
public JPopupMenu getItemRightClickMenu() {
return itemRightClickMenu;
}
public JMenuItem getItemEdit() {
return itemEdit;
}
public BaldGUI getParent() {
return parent;
}
}
The Record type is just a basic data container, and RecordSet is just an extension of ArrayList{Record} with a method to turn the data therein into an Object[][] for the DefaultTableModel.
So, as I expected, it was a really simple, dumb mistake. In my RecordsTable class, I stored off the parent GUI (BaldGUI) as a variable called parent. I then had a method getParent() to fetch that parent, and I didn't realize that JTable comes with a method getParent() which gets the surrounding component. By overriding that method, the entire program more or less broke. I changed the method, and it works as it should.
I have a fully functional console-based database which I need to add GUIs to. I have created a tab page (currently only one tab) with a button "Display All Student" which when triggered will display a list of students inside a JTextArea which of course is in its own class and not inside the button's action listener class. Problem is, the JTextArea is not recognised inside button's action listener. If I add parameter into the action listener, more errors arise. Help?
I have searched Stack Overflow for similar problems but when I tried it in my code, doesn't really do the trick? Or maybe I just need a nudge in the head. Anyways.
Here is my code so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class StudDatabase extends JFrame
{
private JTabbedPane tabbedPane;
private JPanel studentPanel;
private static Scanner input = new Scanner(System.in);
static int studentCount = 0;
static Student studentArray[] = new Student[500];
public StudDatabase()
{
setTitle("Student Database");
setSize(650, 500);
setBackground(Color.gray);
JPanel topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
// Create the tab pages
createStudentPage();
// more tabs later...
// Create a tab pane
tabbedPane = new JTabbedPane();
tabbedPane.addTab( "Student Admin", studentPanel );
topPanel.add( tabbedPane, BorderLayout.CENTER );
}
public void createStudentPage()
{
studentPanel = new JPanel();
studentPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
JButton listButton = new JButton("List All Student(s)");
listButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(studentCount > 0)
{
for(int i=0; i<studentCount; i++)
{
// print out the details into JTextArea
// ERROR! textDisplay not recognised!!!
textDisplay.append("Student " + i);
}
System.out.printf("\n");
}
else // no record? display warning to user
{
System.out.printf("No data to display!\n\n");
}
}
});
studentPanel.add(listButton);
JTextArea textDisplay = new JTextArea(10,48);
textDisplay.setEditable(true); // set textArea non-editable
JScrollPane scroll = new JScrollPane(textDisplay);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
studentPanel.add(scroll);
}
public static void main(String[] args)
{
StudDatabase mainFrame = new StudDatabase();
mainFrame.setVisible(true);
}
Your code isn't working for the same reason this wouldn't work:
int j = i+5;
int i = 4;
You have to declare variables before using them in Java.
Secondly, in order to use a variable (local or instance) from inside an inner class - which is what your ActionListener is - you need to make it final.
So, the below code will compile and run:
final JTextArea textDisplay = new JTextArea(10,48);
...
listButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
...
textDisplay.append("Student " + i);
I'm a kinda newbie actually and just self-studying. I really want to learn how to use JComboBox properly. I have created a simple program but it took me forever to fix it.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SampleButtonKo {
JComboBox combo;
public void ComboBox1() {
String course[] = {
"PM1", "PM2", "PM3", "PM4"
};
JFrame frame = new JFrame("Mang Inasal Ordering System");
JPanel panel = new JPanel();
combo = new JComboBox(course);
combo.setBackground(Color.gray);
combo.setForeground(Color.red);
panel.add(combo);
frame.add(panel);
combo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
String str = (String) combo.getSelectedItem();
System.out.print("You have chosen " + str);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}
public static void main(String[] args) {
JComboBox = new JComboBox();
}
}
You forgot a name for the variable
Instead of
JComboBox = new JComboBox();
try
JComboBox j = new JComboBox();
^
But perhaps, as iTech suggests, you want to create an instance of your class.
new SampleButtonKo();
There are obvious few errors in your code, you need to have the constructor named exactly as your class with no return type. Second, in your main you should create an instance of your class not the JComboBox
public class SampleButtonKo{
JComboBox combo;
public SampleButtonKo(){
// Copy your code from "ComboBox1" here
}
public static void main(String[] args) {
new SampleButtonKo();
}
}
My aim is to create a JTable, and render the far left column cells only, with the aim of creating row headers for the table.
All row table examples I have come across online seem convoluted or do not fit my purposes, so I am wondering is there a simple way of creating JTable row headers through rendering the left column cells only?
Below I have code of a simple table with 2 columns and two rows. Is it possible someone could modify this, or explain in simple terms, how I could go about rendering the far left column for row header purposes.
Thank you.
import javax.swing.*;
import java.awt.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.BufferedImage;
import java.util.*;
public class GUITable extends JFrame{public GUITable(){
init();
}
public final void init(){
String[] columnNames = {"", "Gross Weight"};
Object[][] data = {
{"", new Integer(100)},};
final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
GUITable ex = new GUITable();
ex.setVisible(true);
}
});
}
}
Yes - by using a custom TableCellRenderer, you can modify the way the first column (and first column only) displays.
Essentially you can use this to set the TableCellRenderer on the first column only:
table.getColumnModel().getColumn(0).setCellRenderer(new CustomRenderer());
And you can extend the DefaultTableCellRenderer to take care of any special rendering you want to do:
//Custom Renderer - does the default rendering except if told the row should be a different color
public static class CustomRenderer extends DefaultTableCellRenderer{
public CustomRenderer(){
super();
//Customize the rendering however you want
setBackground(UIManager.getColor("TableHeader.background"));
}
}
To put it all together in your example:
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
public class TestTable extends JFrame{
public TestTable(){
init();
}
public final void init(){
String[] columnNames = {"", "Gross Weight"};
Object[][] data = {{"", new Integer(100)},};
final JTable table = new JTable(data, columnNames);
// Add Renderer to first column only
table.getColumnModel().getColumn(0).setCellRenderer(new CustomRenderer());
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(300, 200));
add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
TestTable ex = new TestTable();
ex.pack();
ex.setVisible(true);
}
});
}
//Custom Renderer - does the default rendering except if told the row should be a different color
public static class CustomRenderer extends DefaultTableCellRenderer{
public CustomRenderer(){
super();
//Customize the rendering however you want
setBackground(UIManager.getColor("TableHeader.background"));
}
}
}
your code example could be
import javax.swing.*;
import java.awt.*;
public class GUITable extends JFrame {
public GUITable() {
init();
}
public final void init() {
String[] columnNames = {"", "Gross Weight"};
Object[][] data = {{"", new Integer(100)},};
final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");//Java6
//UIManager.setLookAndFeel(
//"javax.swing.plaf.nimbus.NimbusLookAndFeel");//Java7
} catch (Exception fail) {
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
GUITable ex = new GUITable();
ex.setVisible(true);
}
});
}
}
not sure from your descriptions, are you meaning Row Number Table by #camickr, or another half_sized attempt