Create a ScrollPanel - then place the results in there - java

The code : The user enters a value and the code returns the computed value in a frame with a scrollbar because the frame is too small to contain the 100 lines.
package Gui;
import java.awt.*;
import javax.swing.*;
public class Rekenen2 extends JFrame {
public Rekenen2() {
// setLayout(new GridLayout(3,1));
JPanel panel1 = new JPanel();
panel1.setBackground(Color.BLACK);
JButton jbtComputeButton = new JButton("Compute");
JPanel panel2 = new JPanel();
panel2.setBackground(Color.BLACK);
JPanel panel3 = new JPanel();
final JTextField jtxInputTextField = new JTextField(8);
final JLabel outputInPanel = new JLabel();
panel1.add(jbtComputeButton, FlowLayout.LEFT);
panel2.add(jtxInputTextField, FlowLayout.LEFT);
panel3.add(outputInPanel);
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.CENTER);
add(panel3, BorderLayout.SOUTH);
jbtComputeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int total = 0;
int parsedInputValue = Integer.parseInt(jtxInputTextField
.getText());
for (int i = 0; i < 100; i++) {
total = (parsedInputValue * i);
outputInPanel.setText("" + total);
}
}
});
}
public static void main(String[] args) {
JFrame frame = new Rekenen2();
frame.setSize(300, 300);
frame.setTitle("Compute App");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
}

Just put the content in JScrollPane(then add the JScrollPane To JFrame). that will do the trick.

Related

Why is extra space being added to the frame?

So I'm adding this code to a JFrame which has other layout managers and components in them.
private JPanel testing123() {
JPanel j = new JPanel(new FlowLayout());
jbtOk = new JButton("OK");
jbtOk.setMnemonic('K');
jbtExit = new JButton("Exit");
jbtExit.setMnemonic('x');
add(jbtOk);
add(jbtExit);
j.add(jbtOk);
j.add(jbtExit);
return j;
}
Without this code, the JFrame looks fine, but when I add it, it adds a large amount of empty space under these two buttons. Why is this happening?
This replicates it:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class Test extends JFrame implements ActionListener, KeyListener {
JButton jbtOk, jbtExit;
JPanel p = new JPanel(new GridLayout(0,1));
JPanel gui = new JPanel(new BorderLayout(2,2));
public Test() {
super("t");
//setSize(300,300);
setVisible(true);
JPanel test = test();
JPanel testing = testing();
JPanel testing123 = testing123();
p.add(test);
p.add(testing);
p.add(testing123);
this.getContentPane().add(p);
pack();
}
private JPanel test() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel labelFields = new JPanel(new BorderLayout(2,2));
labelFields.setBorder(new TitledBorder("m"));
p.add(gui);
p.add(labelFields);
JPanel labels = new JPanel(new GridLayout(0,1,1,1));
labels.setBorder(new TitledBorder("a"));
JPanel fields = new JPanel(new GridLayout(0,1,1,1));
fields.setBorder(new TitledBorder("b"));
p.add(labels);
p.add(fields);
add(fields);
add(p);
return gui;
}
private JPanel testing() {
JPanel guiCenter = new JPanel(new FlowLayout(FlowLayout.CENTER));
guiCenter.setBorder(new TitledBorder("n"));
guiCenter.add(new JScrollPane(new JTextArea(5,30)));
gui.add(guiCenter, BorderLayout.CENTER);
return guiCenter;
}
private JPanel testing123() {
JPanel j = new JPanel(new FlowLayout());
jbtOk = new JButton("OK");
jbtOk.setMnemonic('K');
jbtExit = new JButton("Exit");
jbtExit.setMnemonic('x');
//add(jbtOk);
//add(jbtExit);
j.add(jbtOk);
j.add(jbtExit);
return j;
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
"I want to get rid of the extra space under the OK and Exit buttons."
The problem is you are using the GridLayout that will make all the JPanel equal size. What you should do instead is wrap the first four JPanel in GridLayout, then keep the default BorderLayout of the JFrame, add the JPanel to BorderLayout.CENTER of the JFrame and add the buttons JPanel to the BorderLayout.PAGE_END. This should solve the problem
public Test() {
super("t");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel test = test();
JPanel testing = testing();
JPanel testing123 = testing123();
p.add(test);
p.add(testing);
add(p, BorderLayout.CENTER); <---
add(testing123, BorderLayout.PAGE_END); <---
pack();
setVisible(true);
}
Complete running code
import java.awt.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class Test extends JFrame {
JButton jbtOk, jbtExit;
JPanel p = new JPanel(new GridLayout(0, 1));
JPanel gui = new JPanel(new BorderLayout(2, 2));
public Test() {
super("t");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel test = test();
JPanel testing = testing();
JPanel testing123 = testing123();
p.add(test);
p.add(testing);
add(p, BorderLayout.CENTER);
add(testing123, BorderLayout.PAGE_END);
pack();
setVisible(true);
}
private JPanel test() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel labelFields = new JPanel(new BorderLayout(2, 2));
labelFields.setBorder(new TitledBorder("m"));
p.add(gui);
p.add(labelFields);
JPanel labels = new JPanel(new GridLayout(0, 1, 1, 1));
labels.setBorder(new TitledBorder("a"));
JPanel fields = new JPanel(new GridLayout(0, 1, 1, 1));
fields.setBorder(new TitledBorder("b"));
p.add(labels);
p.add(fields);
return gui;
}
private JPanel testing() {
JPanel guiCenter = new JPanel(new FlowLayout(FlowLayout.CENTER));
guiCenter.setBorder(new TitledBorder("n"));
guiCenter.add(new JScrollPane(new JTextArea(5, 30)));
gui.add(guiCenter, BorderLayout.CENTER);
return guiCenter;
}
private JPanel testing123() {
JPanel j = new JPanel(new FlowLayout());
jbtOk = new JButton("OK");
jbtOk.setMnemonic('K');
jbtExit = new JButton("Exit");
jbtExit.setMnemonic('x');
j.add(jbtOk);
j.add(jbtExit);
return j;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Test();
}
});
}
}

adding new jpanel with default components in swing

can any one tell me how to add a panel in a jtabbedPane whenever i am clicking on a "add" button.Its like google chrome new tab.But the thing is ,the generated panel must contains some default components.Thanks in advance.
Please see the code below. It shows you how to do what you need.
public class DemoApp {
private JTabbedPane tabPane = new JTabbedPane();
public DemoApp() {
initComponents();
}
private void initComponents() {
JFrame frame = new JFrame("Test");
frame.setSize(500, 400);
frame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
frame.getContentPane().add(panel);
JButton btn = new JButton("Add panel");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int index = tabPane.getTabCount() + 1;
JPanel newPanel = new JPanel();
newPanel.setLayout(new FlowLayout());
newPanel.add(new JLabel("Panel " + index));
tabPane.addTab("Tab " + index, newPanel);
}
});
panel.add(tabPane, BorderLayout.CENTER);
panel.add(btn, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new DemoApp();
}
}

all individual panels are not shown inside root panel

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.

Stack swing elements from top to bottom

Consider the following figure:
I need to develop a swing GUI the looks like this. I simply named them jLabel's but there a few images and jLabels in it. The default awt background visible is a JPanel and each red background visible is a serperate JPanel. Now I need them to get stacked as shown above. I tried a number of LayoutManagers and still it doesn't work.
The important point here is that the number of red colored divs are not constant. If there is only one red colored div then it must be displayed at the top, not at the center. As far as i know GridBagLayout should work, but it centers the single red colored jpanel available. All the layout managers are centering them but not stacking them from top to bottom.
Even with anchor set to NORTH then the panels will still be centered. You could work around it by adding a dummy panel to fill the remaining space. Personally I'd stay well away from GridBagLayout though.
JFrame frame = new JFrame();
JPanel content = new JPanel();
content.setBorder(BorderFactory.createLineBorder(Color.red));
frame.setContentPane(content);
frame.getContentPane().setLayout(new GridBagLayout());
frame.setSize(400, 300);
for (int i = 0; i < 3; i++) {
JPanel panel = new JPanel();
panel.add(new JLabel("label1"));
panel.add(new JLabel("label2"));
panel.add(new JLabel("label3"));
panel.setBorder(BorderFactory.createLineBorder(Color.red));
GridBagConstraints con = new GridBagConstraints();
con.gridy = i;
con.gridx = 0;
con.anchor = GridBagConstraints.NORTHWEST;
con.ipady = 10;
frame.getContentPane().add(panel, con);
}
// dummy panel to use up the space (force others to top)
frame.getContentPane().add(
new JPanel(),
new GridBagConstraints(0, 3, 1, 1, 1, 1,
GridBagConstraints.NORTHWEST,
GridBagConstraints.VERTICAL, new Insets(0, 0, 0, 0), 0,
0));
frame.setVisible(true);
GroupLayout example (my favourite layout manager).
JFrame frame = new JFrame();
JPanel content = new JPanel();
frame.setContentPane(content);
frame.getContentPane().setLayout(
new BoxLayout(content, BoxLayout.Y_AXIS));
frame.setSize(400, 300);
GroupLayout gLayout = new GroupLayout(content);
content.setLayout(gLayout);
ParallelGroup hGroup = gLayout.createParallelGroup();
gLayout.setHorizontalGroup(hGroup);
SequentialGroup vGroup = gLayout.createSequentialGroup();
gLayout.setVerticalGroup(vGroup);
for (int i = 0; i < 3; i++) {
JPanel panel = new JPanel();
panel.add(new JLabel("label1"));
panel.add(new JLabel("label2"));
panel.add(new JLabel("label3"));
panel.setBorder(BorderFactory.createLineBorder(Color.red));
hGroup.addComponent(panel);
vGroup.addComponent(panel, GroupLayout.PREFERRED_SIZE,
GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE);
vGroup.addGap(10);
}
frame.setVisible(true);
you can use Vertical BoxLayout, for example:
http://www.java-tips.org/java-se-tips/javax.swing/how-to-use-swing-boxlayout.html
nobody tell us that all JComponents must be visible, for example
from code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class AddComponentsAtRuntime {
private JFrame f;
private JPanel panel;
private JCheckBox checkValidate, checkReValidate, checkRepaint, checkPack;
public AddComponentsAtRuntime() {
f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel(new GridLayout(0, 1));
f.add(panel, "Center");
f.add(getCheckBoxPanel(), "South");
f.setLocation(200, 200);
f.pack();
f.setVisible(true);
}
private JPanel getCheckBoxPanel() {
checkValidate = new JCheckBox("validate");
checkValidate.setSelected(false);
checkReValidate = new JCheckBox("revalidate");
checkReValidate.setSelected(false);
checkRepaint = new JCheckBox("repaint");
checkRepaint.setSelected(false);
checkPack = new JCheckBox("pack");
checkPack.setSelected(false);
JButton addComp = new JButton("Add New One");
addComp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JPanel b = new JPanel(new GridLayout(0, 4));
b.setBackground(Color.red);
b.setBorder(new LineBorder(Color.black, 2));
//b.setPreferredSize(new Dimension(600, 20));
for (int i = 0; i < 4; i++) {
JLabel l = new JLabel("label" + i + 1);
b.add(l);
if (i == 2) {
l.setVisible(false);
}
}
panel.add(b);
makeChange();
System.out.println(" Components Count after Adds :" + panel.getComponentCount());
}
});
JButton removeComp = new JButton("Remove One");
removeComp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int count = panel.getComponentCount();
if (count > 0) {
panel.remove(0);
}
makeChange();
System.out.println(" Components Count after Removes :" + panel.getComponentCount());
}
});
JPanel panel2 = new JPanel();
panel2.add(checkValidate);
panel2.add(checkReValidate);
panel2.add(checkRepaint);
panel2.add(checkPack);
checkPack.setSelected(true);
panel2.add(addComp);
panel2.add(removeComp);
return panel2;
}
private void makeChange() {
if (checkValidate.isSelected()) {
panel.validate();
}
if (checkReValidate.isSelected()) {
panel.revalidate();
}
if (checkRepaint.isSelected()) {
panel.repaint();
}
if (checkPack.isSelected()) {
f.pack();
}
}
public static void main(String[] args) {
AddComponentsAtRuntime makingChanges = new AddComponentsAtRuntime();
}
}
You should try the MigLayout it is simple yet powerful. Below I tell miglayout to grow elements, and fill all possible space, then after each element I tell it to go to a new line (wrap). You can find examples and tutorial on MigLayout page http://www.miglayout.com/:
import net.miginfocom.swing.MigLayout;
public class PanelLearning extends JPanel {
public PanelLearning() {
setLayout(new MigLayout("", "[grow, fill]", ""));
for (int i = 0; i < 3; i++) {
JPanel panel = new JPanel();
panel.add(new JLabel("label1"));
panel.add(new JLabel("label2"));
panel.add(new JLabel("label3"));
panel.setBorder(BorderFactory.createLineBorder(Color.red));
add(panel, "span, wrap");
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Login");
frame.setVisible(true);
frame.setContentPane(new PanelLearning());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
}
}
Make sure GridBagConstraints.anchor = GridBagConstraints.NORTH when you add components to the panel.

Scrollpane for JPanel?

I want to add Scrollpane to JPanel which is in turn called by another jpanel?
public class test {
JFrame jframe;
JPanel jpanel;
JScrollPane js= null;
public void createFrame()
{
jframe=new JFrame("Thick client Wallboard");
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
jframe.setSize(dim.width,dim.height);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setUndecorated(true);
jframe.setResizable(false);
jframe.setLocation(0, 0);
getJContentPane();
jframe.setContentPane(jpanel);
jframe.setVisible(true);
}
public void getJContentPane()
{
jpanel = new JPanel();
jpanel.setBackground(new Color(0x505050));
jpanel.setLayout(null);
jpanel.setFont(new Font("verdana",Font.BOLD,12));
jpanel.setBorder(new LineBorder(Color.BLACK,2));
getpanel();
jpanel.add(js);
jpanel.setBackground(Color.LIGHT_GRAY);
jpanel.setVisible(true);
}
public void getpanel()
{
JPanel mainPanel=new JPanel();
mainPanel.setBounds(50,50,920,650);
mainPanel.setBackground(Color.WHITE);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
for(int i = 0; i < 30; i++) {
mainPanel.add(new JButton("Button " + i));
}
js=new JScrollPane(mainPanel);
}
public static void main(String[] args) {
test t=new test();
t.createFrame();
}
}
I have done like this but it is not working...
You can do it:
public static void main(String[] args) {
Frame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
for(int i = 0; i < 20; i++) {
panel.add(new JButton("Button " + i));
}
//Creating JScrollPane with JPanel
JScrollPane scrollPane = new JScrollPane(panel);
JPanel otherPanel = new JPanel();
otherPanel.setLayout(new BorderLayout());
//Adding scrollPane to panel
otherPanel.add(scrollPane);
frame.add(otherPanel);
frame.setSize(200,200);
frame.setVisible(true);
}
Also check :
http://www.coderanch.com/t/342486/GUI/java/Adding-ScrollPane-JPanel
JScrollPane is, like all JComponent derivatives, a decorator, and you can decorate any component with it.
You can put any component in the scroll pane.
JScrollPane pane = new JScrollPane(component);
and just add the scrollpane instead of the wrapped component.

Categories

Resources