Header of JTable's column won't show - java

I am new to Java and need to make a blank table with column header only, but I am stuck at the column header, it won't appear, I have tried the answer in this link JTable won't show column headers (adding JScrollPane) but it won't work. This is my code:
void panelTabel(){
JPanel panelTabel = new JPanel();
panelTabel.setBackground(Color.white);
panelTabel.setLayout(null);
panelTabel.setBounds(0, 260, 1000, 455);
JScrollPane scrollTabel = new JScrollPane();
scrollTabel.setBackground(Color.white);
scrollTabel.setLayout(null);
scrollTabel.setBounds(5,5,990,340);
Vector headerTabel = new Vector(2);
headerTabel.addElement(new String("No."));
headerTabel.addElement(new String("Kode Barang"));
DefaultTableModel modelTabel = new DefaultTableModel(1, headerTabel.size());
modelTabel.setColumnIdentifiers(headerTabel);
JTable tabelBarang = new JTable();
tabelBarang.setModel(modelTabel);
tabelBarang.setBackground(Color.gray);
tabelBarang.setBounds(5,5, 980, 330);
scrollTabel.add(tabelBarang);
panelTabel.add(scrollTabel);
halaman.add(panelTabel);
}
And this is the output :
Blank table with no column header
I know my question may be duplicate, but I am really new to java and don't know what I did wrong, can someone please tell me what am I missing ? Thank you so much.

Here's a simple JTable GUI I created using your method.
Here are the changes I made.
I used a border layout on the JPanel that holds the JTable.
I got rid of all null layouts and positioning statements. I did ask for a preferred size for the JPanel. After you actually add some data to the JTable, you can define the size of the JTable and remove the preferred size hint.
I defined the JTable first, then the JScrollPane. Thanks to Andrew Thompson for his comment.
Here's the minimal, runnable example #38,593,729 of a JTable in a JPanel in a JFrame. I hope this example helps you, unlike the first 38,593,728 examples on the Internet.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class JTableSimpleExample implements Runnable {
private JFrame frame;
#Override
public void run() {
frame = new JFrame("JTable Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panelTabel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel panelTabel() {
JPanel panelTabel = new JPanel();
panelTabel.setLayout(new BorderLayout());
panelTabel.setPreferredSize(new Dimension(400, 100));
Vector<String> headerTabel = new Vector<>(2);
headerTabel.addElement(new String("No."));
headerTabel.addElement(new String("Kode Barang"));
DefaultTableModel modelTabel = new DefaultTableModel(1, headerTabel.size());
modelTabel.setColumnIdentifiers(headerTabel);
JTable tabelBarang = new JTable(modelTabel);
JScrollPane scrollTabel = new JScrollPane(tabelBarang);
panelTabel.add(scrollTabel, BorderLayout.CENTER);
return panelTabel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new JTableSimpleExample());
}
}

Related

Strange behaviour of JTable when selecting rows

I use a JTable inside a JScrollPane with a custom TableModel, cell-/column-selection disabled and only row-selection enabled (single selection). If I select a row, from time to time, the value in the cell on which I perform the click, appears in the neighbour columns too (and overwrites the values in there).
Could anybody give me a hint, what I'm doing wrong or has anybody else faced this problem?
Thanks for your help in advance!
EDIT: I added a SSCCE. After a few selections, the issue should occur. You can accelerate the occurence of it by keeping the mouse pressed while hovering over the rows. If it occured once, it occurs during every selection.
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
public class TableIssueSSCCE {
public TableIssueSSCCE() {
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JTable table = new JTable(new DefaultTableModel());
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addColumn("Test1");
model.addColumn("Test2");
model.addColumn("Test3");
model.addColumn("Test4");
for (int i = 0; i < 1000; i++) {
model.addRow(new String[]{
"Column1" + i, "Column2" + i, "Column3" + i, "Column4" + i});
}
table.setFillsViewportHeight(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setCellSelectionEnabled(false);
table.setColumnSelectionAllowed(false);
table.setRowSelectionAllowed(true);
table.setAutoCreateRowSorter(true);
JScrollPane tableContainer = new JScrollPane(table);
tableContainer.setVerticalScrollBar(new JScrollBar(JScrollBar.VERTICAL));
tableContainer.setHorizontalScrollBar(new JScrollBar(JScrollBar.HORIZONTAL));
frame.add(tableContainer, BorderLayout.CENTER);
frame.setVisible(true);
}
public static void main(String[] args) {
new TableIssueSSCCE();
}
}
I was able to avoid the problem by changing to Oracle's JRE. So this issue seems to be related to OpenJDK.
Some observations:
Whenever a Swing program misbehaves intermittently, I start looking for incorrect synchronization, sometimes resorting to the approach shown here. See also Initial Threads. Because such errors may be difficult to reproduce, it's better to be safe:
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new TableIssueSSCCE();
});
}
Instead of setSize(), override getPreferredScrollableViewportSize(), as suggested here.

JList not showing as a list, just a dot...maybe a graphic dot?

Trying to list the nodes in a JList so I can choose one from the list.
I have this code (and a lot more)...
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JPanel row1 = new JPanel();
JPanel row2 = new JPanel();
JLabel flabel = new JLabel("Förbindelse från " + n1 +" till " + n2, JLabel.CENTER);
JScrollPane scroll = new JScrollPane(JLista);
DefaultListModel<Edge<Node>> Jlistan = new DefaultListModel<Edge<Node>>();
List<Edge<Node>> listan = listGraph.getEdgesBetween(n1,n2);
for (Edge<Node> listEdge : listan) {
Jlistan.addElement(listEdge);
}
JLista = new JList<Edge<Node>> (Jlistan);
JLista.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JLista.setLayoutOrientation(JList.HORIZONTAL_WRAP);
JLista.setVisibleRowCount(5);
JLista.setSize(100, 100);
getJlistVal();
row2.add(scroll);
row1.add(flabel);
add(row1);
add(row2);
}
...
public Edge<Node> getJlistVal(){
return JLista.getSelectedValue();
}
But when listing, i just get a little spot on the Jpanel, i think its a graphical dot, or a very very litte Jlist. :( cant publish a picture yet...
I thought it had to do with pixelsize but dont think so??
Do i have to specify size of the list??
The list to be displayed is a generic LIST as type Node. I have a method that i call, is the return type ok?
//thank you
-Help me StackOverflow. You are my only hope...
You create scroll instance with null list.
JScrollPane scroll = new JScrollPane(JLista);
Just move the line after
JLista = new JList<Edge<Node>> (Jlistan);
Not sure what you're doing wrong because your example won't compile without your other classes, But When I use the above code, adding in a bit of my own, it works. The only difference is I used a Box instead of BoxLayout, which is pretty much the same thing, just a Box uses a JPanel under the hood. I had to do this because it wasn't allowing be to use this from the JFrame subclass. You can test it
import javax.swing.Box;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
/**
*
* #author Paul SamSotha
*/
public class TestList extends JFrame {
public TestList() {
String[] list = {"Hello", "Jello", "Wello"};
JList JLista = new JList(list);
JPanel row1 = new JPanel();
JPanel row2 = new JPanel();
JLabel flabel = new JLabel("Förbindelse från ", JLabel.CENTER);
JScrollPane scroll = new JScrollPane(JLista);
JLista.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JLista.setLayoutOrientation(JList.HORIZONTAL_WRAP);
JLista.setVisibleRowCount(5);
JLista.setSize(100, 100);
row2.add(scroll);
row1.add(flabel);
Box box = Box.createVerticalBox();
box.add(row1);
box.add(row2);
add(box);
}
public static void createAndShowGui() {
JFrame frame = new TestList();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
"Do i have to specify size of the list??"
No, you can just call .pack() on the frame and let the pack do its magic
What you could do is, get the value in the getJlistVal() and return the value as a String.
String selected = jList1.getSelectedItem().toString();
and try to return that value. Tell me if it prints. I can't test it myself right now.
Just a suggestion to try, let me know how it goes.
Currently what your method getJListVal() is doing is, returning the value as an Element. Which may be your problem. Try returning it as a String, int or generic variable type, then try displaying it.

TextArea is overflowing bounds assigned to it as well as the center of the Borderlayout and covering the entire window

So I asked something similar to this earlier and got the answer to the question I asked, but I apparently didn't ask the right question. So, what I'm trying to accomplish here is have the text area populate only in the center of the jFrame. As you can see, it is set up as a borderlayout, and there are buttons on the bottom, a label on the top (which will then - on the full version of this program - be copied into the text frame when it is replaced with text from the action listener on the button)
The problem is, the text area fills the entire window and covers up every other component on the window. I've tried to use preferred size, and I tried to specify columns/rows and I've read the tutorials on docs.oracle, although I suppose since I'm still having trouble i may have missed one.
Also, the offset commented lines I found in the docs.oracle information and it would be a good idea for this to text-wrap because it's going to be a log of what has occurred. I tried adding all the imports suggested on that website but netbeans still gives me a red underline that they're not recognized as commands. Have they been deprecated, did I not use them right, or am I missing an import?
I know I'm asking a lot, but thanks for your time and patience!
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package theproblem;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.TextArea;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
/**
*
* #author Heather
*/
public class TheProblem {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
JFrame window2 = new JFrame();
TextArea battleLogging = new TextArea(3,10);
JScrollPane logScrollPane = new JScrollPane(battleLogging);
JLabel BattleLog = new JLabel();
JLabel p1HPLabel= new JLabel();
JLabel p2HPLabel= new JLabel();
String attack1ButtonContents = "Just an attack";
String attack2ButtonContents = "Just another attack";
JButton attack1=new JButton(attack1ButtonContents);
JButton attack2=new JButton(attack2ButtonContents);
window2.setLayout(new BorderLayout());
window2.setSize(400,400);
JPanel attackPanel = new JPanel();
attackPanel.add(attack1);
attackPanel.add(attack2);
window2.add(battleLogging, BorderLayout.CENTER);
battleLogging.setEditable(false);
logScrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
logScrollPane.setPreferredSize(new Dimension(50, 50));
//battleLogging.setLineWrap(true);
//battleLogging.setWrapStyleWord(true);
window2.add(BattleLog, BorderLayout.NORTH);
window2.add(p1HPLabel, BorderLayout.WEST);
window2.add(p2HPLabel, BorderLayout.EAST);
window2.setVisible(true);
window2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Problems:
When adding any component BorderLayout.CENTER, it fills the center position, no matter what size or preferred size you give it.
You shouldn't even be setting sizes.
Don't use TextAreas with Swing apps. Use JTextAreas
Set the JTextArea's column and row count and let that do its sizing for you.
Don't forget to pack your GUI before displaying it.
For example:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.*;
public class TheProblem2 {
private static void createAndShowGUI() {
int rows = 5;
int cols = 20;
JTextArea textArea = new JTextArea(rows, cols);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 1");
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 0));
btnPanel.add(button1);
btnPanel.add(button2);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(scrollPane);
mainPanel.add(btnPanel, BorderLayout.SOUTH);
JFrame frame = new JFrame("EG 2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

JCheckBox not showing (text appears, but without check box)

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SideNotes {
public static JPanel panel = new JPanel();
private List<String> notes = new ArrayList<String>();
private static JButton add = new JButton("Add note");
public SideNotes() {
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(add);
loadNotes();
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addNote();
}
});
}
public void addNote() {
String note = JOptionPane.showInputDialog("Enter note: ", null);
notes.add(note);
JLabel label = new JLabel(note);
panel.add(label);
panel.revalidate();
panel.repaint();
}
private void loadNotes() {
for (int i = 0; i < notes.size(); i++) {
JCheckBox jcb = new JCheckBox(notes.get(i), false);
panel.add(jcb);
panel.revalidate();
panel.repaint();
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(200, 400);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(add);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
new SideNotes();
}
}
Why isn't my JCheckBox showing up? The text shows up but not the actual box. What's the deal?
I have edited my post to contain all of my code in case that helps solve the issue.
needmoretextneedmoretextneedmoretextneedmoretextneedmoretextneedmoretextneedmoretext
Possible reasons:
panel has not been added to GUI
panel has been added but for some reason is not visible.
panel is too small to show the child component. This can happen for instance if you set a component's size or preferredSize or if you place it in a FlowLayout-using container without thought.
panel uses null layout.
panel's layout manager is not one that easily accepts a new component -- think GroupLayout for this one.
There are other unspecified layout manager problems going on. Do you call pack() on your GUI? Do you use null layout or absolute positioning anywhere? Do you need to put panel in a JScrollPane?
Consider creating and posting an sscce for better help.
Edit
Your posted code doesn't ever add any JCheckBoxes to the JPanel, just JLabels. To prove this is so, click on the labels and you'll see that they don't respond to clicks.
Your code grossly over-uses static fields. Get rid of all static modifiers on all variables. They should all be instance variables. The only static anything in your code above should be the main method, and that's it. If this causes errors, then fix the errors, but not by making fields static.
Give your SideNotes class a method, getPanel() that returns the panel field.
Create a SideNotes instance in the beginning of your main method. Then call the above method on the instance to get the JPanel for the JFrame. i.e., frame.add(sideNotes.getPanel());.
Don't add JLabels to your GUI (I've no idea why you're doing this). Add JCheckBoxes in the actionPerformed method.
Every time you press the button, a new Note (JLabel) is added to the panel. But you never call loadNotes() after adding a new Note. So the JLabel is added but not its respective JCheckBox as intended.
Besides of this I'd suggest you make this change:
public void addNote() {
String note = JOptionPane.showInputDialog("Enter note: ", null);
if(notes != null) {
notes.add(note);
JLabel label = new JLabel(note);
panel.add(label);
panel.add(new JCheckBox(note, false));
panel.revalidate();
panel.repaint();
}
}
So you don't need to call loadNotes() and update the GUI just once.

MigLayout row-height and changing font-size

I have a problem using MigLayout in combination with dynamically changing the font-size of the components which are shown in the MigLayout cells.
In detail: I added a JCheckBox via MigLayout to a JPanel. The font-size of the JCheckBox is default (12pt?) and the row which contains the JCheckBox has a preferred height of 17lp. That all works fine.
(View here: http://www.bilderload.com/bild/227327/migproblemcellheight1UQXP2.png)
Now I change the font-size to e.g. 20pt and start the program again. Now the text of the JCheckBox is cut because the row has also the height of 17lp.
(View here: http://www.bilderload.com/bild/227328/migproblemcellheight2DDPGJ.png)
If I for example let the row definition empty ("[]") the text shows correctly with both font sizes - the normal and the large one. But in this case the row will sadly never reach a minimum of 17lp. (It will always have a minimum of 23lp or so)
How can I change the MigLayout definition to get a minimum row-height of 17lp and to let the cell grow correctly with the components font-size/text etc.?
Or maybe this is a L&F problem?
Thanks & best regards,
Philipp
Here is my sample code (working example):
import java.awt.Font;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
public class TestMigLayoutFontSize extends JFrame {
public TestMigLayoutFontSize() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600, 400);
setContentPane(getTestPanel());
setVisible(true);
}
private JPanel getTestPanel() {
JCheckBox testBox = new JCheckBox("Program argument");
Font normalFont = testBox.getFont();
Font largeFont = new Font(testBox.getFont().getName(), testBox.getFont().getStyle(), 20);
// testBox.setFont(normalFont);
testBox.setFont(largeFont);
JPanel tempPanel = new JPanel(new MigLayout("debug", "0lp![grow,fill]0lp!", "[17lp:17lp:n]"));
tempPanel.add(testBox);
JPanel testPanel = new JPanel(new MigLayout("", "[grow,fill]", "[grow,fill]"));
testPanel.add(tempPanel);
return testPanel;
}
public static void main(String[] args) {
new TestMigLayoutFontSize();
}
}
You may reduce the space around your checkbox by reducing the border size, e.g. put
testBox.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
directly after the assignment of testBox. You may then leave the row definition empty and still get a reasonable height for your panel.
The following works for me. I think the problem is , that you specify the preferred size.
Regards
Roger
package de.test;
import java.awt.Font;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
public class MigTest extends JFrame {
public MigTest() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600, 400);
setContentPane(getTestPanel());
setVisible(true);
}
private JPanel getTestPanel() {
JCheckBox testBox = new JCheckBox("Program argument");
Font normalFont = testBox.getFont();
Font largeFont = new Font(testBox.getFont().getName(), testBox.getFont().getStyle(), 90);
// testBox.setFont(normalFont);
testBox.setFont(largeFont);
JPanel tempPanel = new JPanel(new MigLayout("debug", "0lp![grow,fill]0lp!", "[80:n:]"));
tempPanel.add(testBox);
JPanel testPanel = new JPanel(new MigLayout("", "[grow,fill]", "[grow,fill]"));
testPanel.add(tempPanel);
return testPanel;
}
public static void main(String[] args) {
new MigTest();
}
}

Categories