So I have a table that is displaying data from a database but since there's a lot of data being outputted into the table it goes way beyond the bounds I have set for the JFrame.
I've tried adding a ScrollPane below but instead of allowing me to scroll down the GUI it will display white over the whole GUI! All I need to do is make it so I can scroll down to view the whole table!
Here is my code:
public class ViewAll extends JFrame{
//Jtextfields, buttons, labels
private static JButton one = new JButton("Back");
private static JLabel lblMembTitle = new JLabel("<html><h1>All Members</h1></html>");
private static JLabel lblPlayTitle = new JLabel("<html><h1>All Playlists</h1><br /></html>");
//Containers, Panels, Scrollpanes
private Container mainCon = this.getContentPane();
private static JPanel pnlTable = new JPanel();
//Tables
private static JTable tblShowAllMemb = new JTable();
private static JTable tblShowAllPlay = new JTable();
JScrollPane scrollPane = new JScrollPane(pnlTable, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
public ViewAll(){
super("Search/Edit/Delete Members");
this.setBounds(400, 800, 854,400);
//Add panel and create table model
mainCon.add(pnlTable);
MemTableModel tblMembers = new MemTableModel();
PlayTableModel tblPlaylist = new PlayTableModel();
this.add(scrollPane);
//Add table and set tableModel
pnlTable.add(lblMembTitle);
pnlTable.add(tblShowAllMemb);
tblShowAllMemb.setModel(tblMembers);
pnlTable.add(lblPlayTitle);
pnlTable.add(tblShowAllPlay);
tblShowAllPlay.setModel(tblPlaylist);
}
}
It seems that you add your JPanel pnlTable to multiple containers, first to scrollPane, then to Container mainCon (so it is not in scrollPane, as a component can be only in one container). So when you add scrollPane separetly to ViewAll it display nothing, because it is empty.
So use:
mainCon.add(scrollPane);
or delete mainCon.add(pnlTable); and use only:
this.add(scrollPane);
Related
(using netbeans)
So for my project I need to add a JscrollPane so that the user can see all of the JTextArea output, a piechart and the two buttons I have added. This is the code I have implementing the JscrollPane. However it is causing the program to no longer produce an output screen. My question is do I need to add the JscrollPane to the JPanel or to the JFrame and if so what am I doing wrong (tried to include as much of the code as I thought was relevant)
P.S Should I change from Borderlayout to a Boxlayout? Would that make a difference in terms of adding a jscroll?
JFrame frame1 = new JFrame("Portfolio Results");
frame1.setSize(800,800);
// frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// output screen declartions
frame1.setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
frame1.add(panel1,BorderLayout.PAGE_START);
panel1.setLayout(new BorderLayout());
JTextArea area1 = new JTextArea();
area1.setPreferredSize(new Dimension(600,600));
panel1.add(area1,BorderLayout.PAGE_START);
JScrollPane scp1 = new JScrollPane(frame1,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
frame1.add(scp1);
//code for Pie chart and two button
DefaultPieDataset piedata = new DefaultPieDataset();
piedata.setValue("test", new Integer (100));
JFreeChart chart = ChartFactory.createPieChart("test", piedata, true, true, true);
PiePlot p = (PiePlot)chart.getPlot();
ChartPanel testpan = new ChartPanel(chart);
panel1.add(testpan,BorderLayout.CENTER);
JButton button= new JButton("SAVE");
// button.setPreferredSize(new Dimension(80,20));
// Listener listener = new Listener();
// button.addActionListener(this);
panel1.add(button,BorderLayout.PAGE_END);
JButton pbutton=new JButton("Print");
panel1.add(pbutton,BorderLayout.SOUTH);
You should init the JScrollPane with the object you want to scroll through.
In your example, it seems the JTextArea is the object you want, so:
JScrollPane scp1 = new JScrollPane(area1,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
From the Oracle docs:
JScrollPane(Component view)
Creates a JScrollPane that displays the contents of the specified component, where both horizontal and
vertical scrollbars appear whenever the component's contents are
larger than the view.
Also, see this Oracle example.
I have next part of code:
final JList<String> list = new JList<String>(strings);
list.setLayoutOrientation(JList.VERTICAL);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
/* Create scroll pane instance */
JScrollPane scroll = new JScrollPane(list) {
#Override
public Dimension getPreferredSize()
{
BookFrame frame = BookFrame.instance();
Container parent = getParent();
return new Dimension(frame.getWidth(), parent.getHeight() - parent.getComponent(parent.getComponentCount() - 1).getHeight() - 14);
}
};
/* Create button instance */
JButton button = new JButton("Add Directory");
/* Add new panel */
JPanel panel = new JPanel();
panel.add(scroll);
panel.add(button);
This code runs when program starts and sometimes button height is a normal value (ex. 15) but sometimes it's 0. I think the problem is with JScrollPane instance - it was created before JButton instance - but I can't synchronize. I tried also to add JButton button = ... before JScrollPane scroll = ... but it's not working too.
I'm newby in Java so please tell me what I do wrong.
I don't see any reason you need to override the getPreferredSize() method. I would guess this is the problem.
JScrollPane scroll = new JScrollPane(list)
I don't know what "list" is, but assuming you are using a JList then you can use:
list.setVisibleRowCount(...);
to indicate the number of rows for the size of the list. The scrollpane will then be that size and scrollbars will appear if needed.
What I am trying to do is add two X by 2 grid panels in the first row of a 2x2 grid content panel, leaving the bottom row of the content panel blank.
To populate the cells on the top row I want to use a function which uses a loop to generate a text field and a slider. the text field calling it's input from textList[n].
So this breaks down into two primary questions.
If I have a function:
public static void makeTop(String textName) {
JTextField textBox = new JTextField(textName);
textBox.setPreferredSize(new Dimension(100,50));
textBox.setHorizontalAlignment(JTextField.CENTER);
textBox.setEditable(false);
SpinnerNumberModel numSpinner = new SpinnerNumberModel(10,0,100,1);
JSpinner spinner = new JSpinner(numSpinner);
spinner.setPreferredSize(new Dimension(100,50));
}
And a frame w/ panel:
public static void main(String[] args) {
JFrame frame = new JFrame("Frame");
frame.getContentPane().setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel cPane = new JPanel((new GridLayout(2,2)));
frame.add(cPane, BorderLayout.CENTER);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
How could I add the text field and spinner created in makeTop to cPane?
cPane.add() doesn't like function calls, and making cPane public didn't seem to help when trying to add the content in makeTop().
Secondly, let's say makeTop is called as follows, with N being arbitrary and textList[] being populated with Strings:
for(i=N;i>0;i--){
makeTop(textList[i]);
}
How could I get the text fields and sliders to be unique instances when creating them in such a way?
cPane.add doesn't like function calls, and making cPane public didn't
seem to help when trying to add the content in makeTop()
It won't work, indeed, because by contract makeTop(String textName) is returning void. But if you make this change:
public static JPanel makeTop(String textName){
JTextField textBox = new JTextField(textName);
textBox.setPreferredSize(new Dimension(100,50));
textBox.setHorizontalAlignment(JTextField.CENTER);
textBox.setEditable(false);
SpinnerNumberModel numSpinner = new SpinnerNumberModel(10,0,100,1);
JSpinner spinner = new JSpinner(numSpinner);
spinner.setPreferredSize(new Dimension(100,50));
JPanel panel = new JPanel(new FlowLayout());
panel.add(textBox);
panel.add(spinner);
return panel;
}
Then cPane.add(makeTop("Whatever")); will work like a charm.
Whenever I set the panel's Layout to FlowLayout, the JTable appears, however my imageBackground and buttons are misplaced. And when I set the layout to null, the the table doesn't appear, but the buttons and imageBackground are where I wanted them to be. What am I'm going to do with this?
public class AssetPanel extends JPanel implements ActionListener{
private ArrayList<AssetDetails> assetList;
private Frame frame;
private Database db;
private JTable assetTable;
private JScrollPane scrollPane;
private JButton btnBack;
private JButton btnView;
public AssetPanel (Frame frame){
super();
this.frame = frame;
initialize();
}
public void initialize(){
setName("Assets");
setSize(700, 475);
setLayout(null);
setVisible(true);
db = new Database();
btnView = new JButton("View");
btnView.addActionListener(this);
btnView.setBounds(450, 400, 90, 20);
add(btnView);
btnBack = new JButton("Back");
btnBack.setFont(new Font("Tahoma", Font.BOLD, 12));
btnBack.setBounds(550, 400, 90, 20);
btnBack.addActionListener(this);
add(btnBack);
ImageIcon imageBackground = new ImageIcon(AssetPanel.class.getResource("/resources/assets.png"));
JLabel jlBackground = new JLabel(imageBackground);
jlBackground.setBounds(0,0, 700, 475);
add(jlBackground);
initializeTable();
}
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == btnBack){
frame.changePanel("Main Menu");
}
}
public void initializeTable(){
Object[][] assetData;
assetList = new ArrayList<>();
String[] columnNames = {"Asset Name", "Date Acquired", "Type", "Classification"};
assetList = db.getAssetTable();
assetData = new Object[assetList.size()][columnNames.length];
for(int i = 0; i < assetList.size(); i++){
assetData[i][0] = assetList.get(i).getAssetName();
assetData[i][1] = assetList.get(i).getDateAcquired();
assetData[i][2] = assetList.get(i).getType();
assetData[i][3] = assetList.get(i).getClassification();
}
assetTable = new JTable(assetData, columnNames);
assetTable.setPreferredScrollableViewportSize(new Dimension(400, 100));
assetTable.setLocation(150, 100);
assetTable.setFillsViewportHeight(true);
scrollPane = new JScrollPane(assetTable);
add(scrollPane);
}
}
Don't use a null layout or use the setBounds() method to position and size components.
however my imageBackground and buttons are misplaced
A background is a Container component. That is you create it as a component and paint an image as the background. Then you add other components to the background component. Now the image will appear in the background and the other components appear on top of it.
See the Background Panel to give an example of creating a background component.
On possible solution: I recommend switching to Mig Layout as a solution to all java layout problems. I now use it for the layout of every single container component in my apps. If you switch you'll probably be glad you did (will never again have problems like that listed in this question).
http://www.miglayout.com/
MigLayout may be included in the JDK in a future version of java.
null layouts mean you have to explicitly place all the components.
I recommend BoxLayout. it's really simple, and you can put in spacers to create space between objects, and glue to fill in all remaining space.
you can also nest the boxes, as well.
if you look at java sample code (and at the source for things);
they nest a lot of JPanels to get the complicated layouts.
Try adding this before trying the steps below if it does not work:
// Set your flow layout thus:
setLayout(new FlowLayout(FlowLayout.LEFT,5,5));
// Set your table Auto Resize Mode to OFF
assetTable.setAutoResizeMode(assetTable.AUTO_RESIZE_OFF);
EXTRA: Try if above tips does not help
Technically, your class should extend a JFrame.
Add a root layout to the class(i.e. the JFrame):
setLayout(new FlowLayout(FlowLayout.LEFT,5,5));
Create two panels; one should contain your label and buttons components.
The other should contain the JScrollPane that contains your table.
Both panels can have their Layout which determines how the components will be laid out.
You can use FlowLayout.
Then you can add both panels to the mother layout (JFrame).
I have a JComboBox, and I want to load in a JScrollPane a different content everytime I choose a different element from the JComboBox. The content consists of a various number of JLabels and JTextFields.
What I have done:
JScrollPane scrollPane;
JComboBox combo;
JPanel back = new JPanel(new BorderLayout());
combo = new JComboBox({ "Bird", "Cat", "Dog", "Rabbit", "Pig" });
combo.addActionListener(new AnimalLoader());
scrollPane = showPanel((String) combo.getSelectedItem());
back.add(combo, BorderLayout.NORTH);
back.add(scrollPane, BorderLayout.SOUTH);
back.setVisible(true);
protected JScrollPane showPanel(String name)
{
JPanel contentPanel = new JPanel(new JLabel(name));
scrollPane = new JScrollPane(contentPanel);
return scrollPane;
}
private class AnimalLoader implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JComboBox cb = (JComboBox) e.getSource();
String selected = (String) cb.getSelectedItem();
scrollPane = showPanel(selected);
}
}
I didn't manage to make this reload a different JScrollPane when I choose another item.
Only the JScrollPane that belongs to the first item (the default one) of the JComboBox is loaded.
Any ideas of what I've done wrong please?
scrollPane = showPanel(selected);
Don't create a new scoll pane when you select an item. Instead you need to change the panel that is contained in the viewport of the scroll pane. That is, your "showPanel" method should return the panel, not a scrollpane. Then you can use:
scrollPane.setViewportView( showPanel(selected) );
Next time a proper SSCCE should be posted.
There is no evidence the newly created JScrollPane is ever added to anything.
I would try either of:
Add a JPanel with a CardLayout to
the JScrollPane, and add other
collections of components to the
JPanel.
Call
setViewportView(Component view) on
the existing JScrollPane.
panel.revalidate();
panel.repaint();
As you are using this example, try this variation at line 73, near the end of the ComboBoxDemo constructor:
//Lay out the demo.
add(petList, BorderLayout.PAGE_START);
JScrollPane jsp = new JScrollPane(picture);
jsp.getViewport().setPreferredSize(new Dimension(100, 100));
add(jsp, BorderLayout.PAGE_END);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));