i'm trying to add a jtable component to my jPanel but i am unable to see it. What am i doing wrong?.
table gui = new table(data,colum);
mainPanel.add(gui.table);
class table extends JFrame
{
public JTable table;
public table(Vector data, Vector colum)
{
setLayout(new FlowLayout());
table = new JTable(data,colum);
table.setPreferredScrollableViewportSize(new Dimension(900,10));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
}
Extending JFrame seems odd; you don't use any of the top level container capabilities. Here's an example that extends JPanel, with a main() that drops the panel into a JFrame.
--Edited to accept an existing JPanel
public class TablePanel
{
public static void addTableToPanel(JPanel jPanel, Vector rowData, Vector columnNames)
{
JTable jTable = new JTable(rowData, columnNames);
jTable.setFillsViewportHeight(true);
JScrollPane jScrollPane = new JScrollPane(jTable);
jScrollPane.setPreferredSize(new Dimension(300, 50));
jPanel.add(jScrollPane);
}
public static void main(String[] args) throws Exception
{
SwingUtilities.invokeAndWait(new Runnable()
{
#Override
public void run()
{
Vector cols = new Vector();
Vector rows = new Vector();
Vector row1 = new Vector();
cols.add("A");
cols.add("B");
cols.add("C");
row1.add("1");
row1.add("2");
row1.add("3");
rows.add(row1);
rows.add(row1.clone());
rows.add(row1.clone());
rows.add(row1.clone());
JFrame frame = new JFrame("TableTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jPanel = new JPanel();
jPanel.setLayout(new BorderLayout(0, 0));
TablePanel.addTableToPanel(jPanel, rows, cols);
frame.getContentPane().add(jPanel);
frame.pack();
frame.setVisible(true);
}
});
}
}
Related
I have a database with tables. I passed the name of the tables into the buttons. When you click, you need a table with fields and filling to appear. The problem is that I have a new table added every time I click on the button.
Can someone please say me how to do it? Thanks in advance!
public class App extends JPanel {
static List<FieldElement> fields = new ArrayList<>();
static List<Map<String, Object>> data = new ArrayList<>();
static JTable jTable = new JTable();
public static void createGUI() throws SQLException {
TableContent tableContent = new TableContent();
JFrame frame = new JFrame();
MetadataHelper databaseMetadata = new MetadataHelper();
List<ButtonElement> elements = databaseMetadata.showTables();
JPanel panel = new JPanel();
JPanel buttons = new JPanel(new GridLayout(0, 1));
for (ButtonElement buttonElements : elements) {
JButton jButton = new JButton(buttonElements.getTablesInMigrateSchema());
buttons.add(jButton);
jButton.addActionListener(new ActionListener() {
#SneakyThrows
#Override
public void actionPerformed(ActionEvent e) {
fields = tableContent.getDatabaseMetadata().showFields(buttonElements.getTablesInMigrateSchema());
data = tableContent.getDatabaseMetadata().selectAll(buttonElements.getTablesInMigrateSchema());
Object[][] objectRows = data.stream().map(m -> m.values().toArray()).toArray(Object[][]::new);
jTable = new JTable(objectRows, fields.toArray());
panel.add(new JScrollPane(jTable));
frame.revalidate();
frame.repaint();
}
});
}
panel.add(buttons, BorderLayout.EAST);
frame.add(panel);
frame.setTitle("SwingSandbox");
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#SneakyThrows
public void run() {
JFrame.setDefaultLookAndFeelDecorated(true);
createGUI();
}
});
}
}
One easy possibility is to store the JScrollPane in a variable (which holds your table that you want to remove):
static JTable jTable = new JTable();
static JScrollPane jScrollPane;
And then in your actionPerformed method:
public void actionPerformed(ActionEvent e) {
...
if (jScrollPane != null) {
panel.remove(jScrollPane);
}
jTable = new JTable(objectRows, fields.toArray());
jScrollPane = new JScrollPane(jTable);
panel.add(jScrollPane);
frame.revalidate();
frame.repaint();
}
I am trying to display small panels in a Table form and added to a ScrollPane . but the scrollpane never scrolls
is it the layout or the size of the container ? or what ?!
Here is an example of what i wanna do:
public class ScrollPanePanels extends JFrame{
JPanel container = new JPanel(null);
JScrollPane scroll = new JScrollPane(container);
public ScrollPanePanels()
{
super();
setLayout(null);
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel Panel1 = new JPanel();
JPanel Panel2= new JPanel();
JPanel Panel3 = new JPanel();
Panel1.setBounds(0,0,500,250);
Panel2.setBounds(0,250,500,250);
Panel3.setBounds(0,500,500,250);
Panel1.setBackground(Color.BLUE);
Panel2.setBackground(Color.RED);
Panel3.setBackground(Color.GREEN);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setBounds(50,50,500,500);
container.setSize(500,750);
container.add(Panel1);
container.add(Panel2);
container.add(Panel3);
add(scroll);
setVisible(true);
}
public static void main(String [] args)
{
ScrollPanePanels s = new ScrollPanePanels();
}
}
I want to write a simple Java program, which consists of a JFrame that integrates a JScrollPane. Just it does not work the way I do it.
What is the issue of the my approach ?
public class TestView {
JFrame frame;
JScrollPane scrollPane;
public TestView(){
frame = new JFrame();
scrollPane = new JScrollPane();
scrollPane.add(new JLabel("Klick me"));
scrollPane.setMinimumSize(new Dimension(200,200));
frame = new JFrame();
frame.getContentPane().add(scrollPane);
frame.setSize(200,200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void createAndShowGui(){
TestView tv = new TestView();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGui();
}
});
If the issue is that you do not see your label in the scrollpane, you might need to use
scrollpane.setViewportView(new JLabel("Klick me"));
instead of
scrollPane.add(new JLabel("Klick me"));
Additionally, I suggest you create a JPanel, give it a layout, and place your label there, instead of passing the label to the scrollpane. Then set this panel as the viewport.
Please see
Difference between JscrollPane.setviewportview vs JscrollPane.add
use for example:
final JPanel myPanel = new JPanel();
myPanel.setPreferredSize(new Dimension(50, 50));
final JScrollPane scrollPane = new JScrollPane(myPanel);
setMinimumSize will be ignored.
I want to add some images to my jlist. following code works great
public class MarioList {
private final Map<String, ImageIcon> imageMap;
public MarioList() {
String[] nameList = {"Mario", "Luigi", "Bowser", "Koopa", "Princess"};
imageMap = createImageMap(nameList);
JList list = new JList(nameList);
list.setCellRenderer(new MarioListRenderer());
JScrollPane scroll = new JScrollPane(list);
scroll.setPreferredSize(new Dimension(300, 400));
JFrame frame = new JFrame();
frame.add(scroll);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class MarioListRenderer extends DefaultListCellRenderer {
Font font = new Font("helvitica", Font.BOLD, 24);
#Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
label.setIcon(imageMap.get((String) value));
label.setHorizontalTextPosition(JLabel.RIGHT);
label.setFont(font);
return label;
}
}
private Map<String, ImageIcon> createImageMap(String[] list) {
Map<String, ImageIcon> map = new HashMap<>();
try {
map.put("Mario", new ImageIcon(new URL("http://i.stack.imgur.com/NCsHu.png")));
map.put("Luigi", new ImageIcon(new URL("http://i.stack.imgur.com/UvHN4.png")));
map.put("Bowser", new ImageIcon(new URL("http://i.stack.imgur.com/s89ON.png")));
map.put("Koopa", new ImageIcon(new URL("http://i.stack.imgur.com/QEK2o.png")));
map.put("Princess", new ImageIcon(new URL("http://i.stack.imgur.com/f4T4l.png")));
} catch (Exception ex) {
ex.printStackTrace();
}
return map;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MarioList();
}
});
}
}
above code creates a new frame and add a jscrollpane to it. Instead of that I tried to create the frame and jcrollpane mannually using Netbeans. So instead of this code;
JList list = new JList(nameList);
list.setCellRenderer(new MarioListRenderer());
JScrollPane scroll = new JScrollPane(list);
scroll.setPreferredSize(new Dimension(300, 400));
JFrame frame = new JFrame();
frame.add(scroll);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
I used this code;
jList1.add(nameList);
jList1.setCellRenderer(new MarioListRenderer());
Here jList1 is my jlist created via Netbeans and it has been put in a jscrollpane.
but this code doesn't work.
Please tell me a way to get this work... Thank you
Assuming you're using Java 7+...
jList1.add(nameList);
Should be
jList1.setListData(nameList);
Otherwise you will need to wrap the nameList within a ListModel implementation
I want to add multiple jpanels to jpanel.So i added a root panel to jscrollpane.and then added all individual jpanels to this root panel.I made jscrollpane's scrolling policy as needed.i.e HORIZONTAL_SCROLLBAR_AS_NEEDED,VERTICAL_SCROLLBAR_AS_NEEDED.
But the problem is all individual panels are not shown inside root panel.
Code:
JScrollPane scPanel=new JScrollPane();
JPanel rootPanel=new JPanel();
rootPanel.setLayout(new FlowLayout());
JPanel indPanel = new JPanel();
rootPanel.add(indPanel);
JPanel indPanel2 = new JPanel();
rootPanel.add(indPanel2);
//.....like this added indPanals to rootPanel.
scPanel.setViewPortView(rootPanel);
//scPanel.setHorizontalScrollPolicy(HORIZONTAL_SCROLLBAR_AS_NEEDED);
And one more thing is, as i scroll the scrollbar the panels are going out of jscrollpane area.
I am not able to see all individual panels,
Please suggest me.
Edit: code snippet from double post:
MosaicFilesStatusBean mosaicFilesStatusBean = new MosaicFilesStatusBean();
DefaultTableModel tableModel = null;
tableModel = mosaicFilesStatusBean.getFilesStatusBetweenDates(startDate, endDate);
if (tableModel != null) {
rootPanel.removeAll();
rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS));
for (int tempRow = 0; tempRow < tableModel.getRowCount(); tempRow++) {
int fileIdTemp = Integer.parseInt(tableModel.getValueAt(tempRow, 0).toString());
String dateFromTemp = tableModel.getValueAt(tempRow, 3).toString();
String dateToTemp = tableModel.getValueAt(tempRow, 4).toString();
int processIdTemp = Integer.parseInt(tableModel.getValueAt(tempRow, 5).toString());
int statusIdTemp = Integer.parseInt(tableModel.getValueAt(tempRow, 6).toString());
String operatingDateTemp = tableModel.getValueAt(tempRow, 7).toString();
MosaicPanel tempPanel =
new MosaicPanel(fileIdTemp, dateFromTemp, dateToTemp, processIdTemp, statusIdTemp, operatingDateTemp);
rootPanel.add(tempPanel);
}
rootPanel.revalidate();
}
The main reason, why you couldn't see your JPanel is that you are using FlowLayout as the LayoutManager for the rootPanel. And since your JPanel added to this rootPanel has nothing inside it, hence it will take it's size as 0, 0, for width and height respectively. Though using GridLayout such situation shouldn't come. Have a look at this code example attached :
import java.awt.*;
import javax.swing.*;
public class PanelAddition
{
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("Panel Addition Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 1));
JScrollPane scroller = new JScrollPane();
CustomPanel panel = new CustomPanel(1);
contentPane.add(panel);
scroller.setViewportView(contentPane);
frame.getContentPane().add(scroller, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
for (int i = 2; i < 20; i++)
{
CustomPanel pane = new CustomPanel(i);
contentPane.add(pane);
contentPane.revalidate();
contentPane.repaint();
}
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PanelAddition().createAndDisplayGUI();
}
});
}
}
class CustomPanel extends JPanel
{
public CustomPanel(int num)
{
JLabel label = new JLabel("" + num);
add(label);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(200, 50));
}
}
Don't use FlowLayout for the rootPanel. Instead consider using BoxLayout:
JPanel rootPanel=new JPanel();
// if you want to stack JPanels vertically:
rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS));
Edit 1
Here's an SSCCE that's loosely based on your latest code posted:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.*;
#SuppressWarnings("serial")
public class PanelsEg extends JPanel {
private static final int MAX_ROW_COUNT = 100;
private Random random = new Random();
private JPanel rootPanel = new JPanel();
public PanelsEg() {
rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS));
JScrollPane scrollPane = new JScrollPane(rootPanel);
scrollPane.setPreferredSize(new Dimension(400, 400)); // sorry kleopatra
add(scrollPane);
add(new JButton(new AbstractAction("Foo") {
#Override
public void actionPerformed(ActionEvent arg0) {
foo();
}
}));
}
public void foo() {
rootPanel.removeAll();
// rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS)); // only need to set layout once
int rowCount = random.nextInt(MAX_ROW_COUNT);
for (int tempRow = 0; tempRow < rowCount ; tempRow++) {
int fileIdTemp = tempRow;
String data = "Data " + (tempRow + 1);
MosaicPanel tempPanel =
new MosaicPanel(fileIdTemp, data);
rootPanel.add(tempPanel);
}
rootPanel.revalidate();
rootPanel.repaint(); // don't forget to repaint if removing
}
private class MosaicPanel extends JPanel {
public MosaicPanel(int fileIdTemp, String data) {
add(new JLabel(data));
}
}
private static void createAndShowGui() {
PanelsEg mainPanel = new PanelsEg();
JFrame frame = new JFrame("PanelsEg");
frame.setDefaultCloseOperation(JFrame.EXIT_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();
}
});
}
}
This SSCCE works, in that it easily shows removing and adding JPanels to another JPanel that is held by a JScrollPane. If you're still having a problem, you should modify this SSCCE so that it shows your problem.