I have a frame that contains a mainPanel. This last will add other commandPanels (each one contains a button and a textField) Dynamically. the problem is that the JScrollPane does not appear to let me use the unseen commandPanels even if the mainPanel is full.
The below picture shows my case.
To initialize the window I wrote below code:
frame = new JFrame();
frame.setBounds(100, 100, 962, 639);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
mainPanel = new JPanel();
mainPanel.setBounds(264, 6, 692, 500);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
scroll = new JScrollPane();
scroll.getViewport().add(mainPanel);
frame.getContentPane().add(scroll);
and the method that add dynamically the new commandPanels is:
public void loadCommandPanel(String commandName)
{
CommandPanel newCommandPanel = new CommandPanel();
newCommandPanel.getCommandBtn().setText(commandName);
mainPanel.add(newCommandPanel);
scroll.getViewport().add( newCommandPanel );
mainPanel.add( scroll, BorderLayout.EAST);
frame.add( mainPanel);
...
}
Any help to get the scrollPane, will be much more than appreciated.
scroll.getViewport().add(mainPanel); is not how you use JViewport or JScrollPane; instead you should using something like this:
scroll.getViewport().setView(newCommandPanel);
or
scroll.setViewportView(newCommandPanel);
Take a look at How to Use Scroll Panes for more details.
Note also, this doesn't makes sense:
CommandPanel newCommandPanel = new CommandPanel();
newCommandPanel.getCommandBtn().setText(commandName);
mainPanel.add(newCommandPanel);
scroll.getViewport().add( newCommandPanel );
You add newCommandPanel to mainPanel, then promptly add it to another container (albeit incorrectly).
A component can only reside on a single parent; the moment you add it to another container, it is automatically removed from the previous container.
I have made some changes and it works perfectly now. For those who want the same thing here's my code:
import ...
public class mainUserInterface {
private JFrame frame;
private JPanel mainPanel;
private JPanel commandsPanel;
private JScrollPane commandsScrollPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainUserInterface window = new mainUserInterface();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public mainUserInterface() {
initialize();
}
private void initialize() {
frame = new JFrame("CommandsExecutor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(1000, 700));
mainPanel = new JPanel(new BorderLayout(5,5));
mainPanel.setBorder( new TitledBorder("") );
commandsPanel = new JPanel();
commandsPanel.setLayout(new BoxLayout(commandsPanel, BoxLayout.Y_AXIS));
for(int i=0; i<15;i++){
commandsPanel.add(new CommandPanel());
}
commandsScrollPane = new JScrollPane(commandsPanel);
mainPanel.add(commandsScrollPane,BorderLayout.CENTER);
frame.setContentPane(mainPanel);
frame.pack();
frame.setVisible(true);
}
}
and Here's the commandPanel class:
import ...
public class CommandPanel extends JPanel {
private JTextField commandResult;
private JButton commandBtn;
public CommandPanel()
{
this.setLayout( new BorderLayout(10,10));
this.setBorder( new TitledBorder("Command:") );
this.setMaximumSize(new Dimension(692,60));
this.setMinimumSize(new Dimension(692,60));
commandBtn = new JButton("Execute");
commandBtn.setMaximumSize(new Dimension(137, 34));
commandBtn.setMinimumSize(new Dimension(137, 34));
this.add(commandBtn, BorderLayout.WEST);
commandResult = new JTextField();
commandResult.setMaximumSize(new Dimension(518, 34));
commandResult.setMinimumSize(new Dimension(518, 34));
this.add(commandResult, BorderLayout.CENTER);
}
public JTextField getCommandResult() {
return commandResult;
}
public JButton getCommandBtn() {
return commandBtn;
}
public void setCommandResult(JTextField commandResult) {
this.commandResult = commandResult;
}
public void setCommandBtn(JButton commandBtn) {
this.commandBtn = commandBtn;
}
}
Thanks for all who answered my question, it really helped.
Related
I create two jbuttons in one panel(can be Box).i create same panel dynamically several times in same frame.so if two panels created dynamically those button make with same variable name.But i want to identify buttons one by one for put actions.how to identify dynamically created buttons one by one?
button creating code
public class Jscrollpanetest extends JFrame {
JScrollPane scrollPane;
Box box;
private static int panelCount = 0;
public Jscrollpanetest() {
setPreferredSize(new Dimension(200, 400));
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.getVerticalScrollBar().setUnitIncrement(15);
box = Box.createVerticalBox();
scrollPane.getViewport().add(box);
this.add(scrollPane);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
Timer t = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
box.add(new TestPanel(), box.size());
scrollPane.validate();
}
});
t.setRepeats(true);
t.start();
}
public class TestPanel extends JPanel {
int myId = panelCount++;
public TestPanel() {
this.setLayout(new GridBagLayout());
this.setBorder(BorderFactory.createBevelBorder(1));
JButton up = new JButton("^");
JLabel rate = new JLabel("1");
JButton down = new JButton("^");
JLabel label = new JLabel("" + myId);
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
this.setMaximumSize(new Dimension(1000, 200));
this.setPreferredSize(new Dimension(1000, 100));
this.add(label);
this.add(up);
this.add(rate);
this.add(down);
}
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Jscrollpanetest testScrollPane = new Jscrollpanetest();
}
});
}
}
If use and dynamic created ActionListener there will be no problem. So each button will have its own ActionListener.
If using a common ActionListener must add tags to each button as extend JButton.
For some reason I can't get the BorderLayout to set the way it's supposed to. Just would like to know where I'm going wrong.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ColorFactory extends JFrame
{
final int width = 500;
final int height = 300;
private JPanel buttonPanel;
private JPanel radioButtonPanel;
private JLabel msgChangeColor;
public ColorFactory()
{
setTitle("Color Factory");
setSize(width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
createTopPanel();
add(buttonPanel, BorderLayout.NORTH);
createBottomPanel();
add(radioButtonPanel, BorderLayout.SOUTH);
msgChangeColor = new JLabel("Top buttons change the panel color and bottom radio buttons change the text color.");
add(msgChangeColor, BorderLayout.CENTER);
pack();
}
private void createTopPanel()
{
buttonPanel = new JPanel();
setLayout(new FlowLayout());
JButton redButton = new JButton("Red");
redButton.setBackground(Color.RED);
redButton.addActionListener(new ButtonListener());
redButton.setActionCommand("R");
JButton orangeButton = new JButton("Orange");
orangeButton.setBackground(Color.ORANGE);
orangeButton.addActionListener(new ButtonListener());
orangeButton.setActionCommand("O");
JButton yellowButton = new JButton("Yellow");
yellowButton.setBackground(Color.YELLOW);
yellowButton.addActionListener(new ButtonListener());
yellowButton.setActionCommand("Y");
buttonPanel.add(redButton);
buttonPanel.add(orangeButton);
buttonPanel.add(yellowButton);
}
private void createBottomPanel()
{
radioButtonPanel = new JPanel();
setLayout(new FlowLayout());
JRadioButton greenRadioButton = new JRadioButton("Green");
greenRadioButton.setBackground(Color.GREEN);
greenRadioButton.addActionListener(new RadioButtonListener());
greenRadioButton.setActionCommand("G");
JButton blueRadioButton = new JButton("Blue");
blueRadioButton.setBackground(Color.BLUE);
blueRadioButton.addActionListener(new RadioButtonListener());
blueRadioButton.setActionCommand("B");
JButton cyanRadioButton = new JButton("Cyan");
cyanRadioButton.setBackground(Color.CYAN);
cyanRadioButton.addActionListener(new RadioButtonListener());
cyanRadioButton.setActionCommand("C");
radioButtonPanel.add(greenRadioButton);
radioButtonPanel.add(blueRadioButton);
radioButtonPanel.add(cyanRadioButton);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String actionColor = e.getActionCommand();
if(actionColor.equals("R"))
{
buttonPanel.setBackground(Color.RED);
radioButtonPanel.setBackground(Color.RED);
}
if(actionColor.equals("O"))
{
buttonPanel.setBackground(Color.ORANGE);
radioButtonPanel.setBackground(Color.ORANGE);
}
if(actionColor.equals("Y"))
{
buttonPanel.setBackground(Color.YELLOW);
radioButtonPanel.setBackground(Color.YELLOW);
}
}
}
private class RadioButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String actionTextColor = e.getActionCommand();
if(actionTextColor.equals("G"))
{
msgChangeColor.setForeground(Color.GREEN);
}
if(actionTextColor.equals("B"))
{
msgChangeColor.setForeground(Color.BLUE);
}
if(actionTextColor.equals("C"))
{
msgChangeColor.setForeground(Color.CYAN);
}
}
}
public static void main(String[] args)
{
ColorFactory run = new ColorFactory();
run.setVisible(true);
}
}
The problem is you are changing the layout manager for the frame when you create your top and bottom panels...
private void createTopPanel() {
buttonPanel = new JPanel();
setLayout(new FlowLayout()); // <--- This is call setLayout on the frame
This is why it's dangerous to...
Extend from something like JFrame directly...
Dynamically build components
It's all to easy to lose context and start effecting components you didn't actually want to...
Another problem (besides the one posted by MadProgrammer) is that you add your components to the JFrame itself.
You should add content to the content pane of the frame which you can get by calling JFrame.getContentPane().
Example:
JFrame f = new JFrame("Test");
Container c = f.getContentPane();
c.add(new JButton("In Center"), BorderLayout.CENTER);
c.add(new JButton("At the Bottom"), BorderLayout.SOUTH);
c.add(new JButton("At the Top"), BorderLayout.NORTH);
c.add(new JButton("On the Left"), BorderLayout.WEST);
c.add(new JButton("On the Right"), BorderLayout.EAST);
You can set/change the content panel by calling JFrame.setContentPane(). The default content panel already has BorderLayout so you don't even need to change it nor to set a new panel.
I am working on the editor. I am using Java swing for it. I have embedded a JTextArea with JScrollPane. i want to position the jtextarea of particular size at the middle of JScrollPane. To do this I used setLocation function. But this is not working?
public class ScrollPaneTest extends JFrame {
private Container myCP;
private JTextArea resultsTA;
private JScrollPane scrollPane;
private JPanel jpanel;
public ScrollPaneTest() {
resultsTA = new JTextArea(50,50);
resultsTA.setLocation(100,100);
jpanel=new JPanel(new BorderLayout());
jpanel.add(resultsTA,BorderLayout.CENTER);
scrollPane = new JScrollPane(jpanel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(800, 800));
scrollPane.setBounds(0, 0, 800, 800);
setSize(800, 800);
setLocation(0, 0);
myCP = this.getContentPane();
myCP.setLayout(new BorderLayout());
myCP.add(scrollPane);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new ScrollPaneTest();
}
}
You simply have to add the JTextArea to the JScrollPane, and add it to the CENTER of the JPanel having BorderLayout.
Don't use AbsolutePositioning. Add a proper LayoutManager, and let LayoutManager do the rest for positioning and sizing your components on the screen.
In order to use the setBounds(...) method you have to use a null Layout for your component, which is not worth using, provided the perspective, as mentioned in the first paragraph of the AbsolutePositioning. Though in the code example provided by you, you are doing both the thingies together i.e. using Layout and using AbsolutePositioning, which is wrong in every way. My advice STOP DOING IT :-)
In the example provided the ROWS and COLUMNS provided by you are sufficient to size the JTextArea by the Layout concern.
Code Example :
import java.awt.*;
import javax.swing.*;
public class Example
{
private JTextArea tarea;
private void displayGUI()
{
JFrame frame = new JFrame("JScrollPane Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
JScrollPane textScroller = new JScrollPane();
tarea = new JTextArea(30, 30);
textScroller.setViewportView(tarea);
contentPane.add(textScroller);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new Example().displayGUI();
}
});
}
}
This is the JPanel
public class DisplayBoard {
public static void main (String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//The main panel
JPanel main = new JPanel();
main.setPreferredSize(new Dimension(600,800) );
main.setLayout(new BorderLayout());
//The title panel
JPanel title = new JPanel();
title.setPreferredSize(new Dimension(400, 120));
title.setBackground(Color.YELLOW);
JLabel test1 = new JLabel("Title goes here");
title.add(test1);
//The side bar panel
JPanel sidebar = new JPanel();
sidebar.setPreferredSize(new Dimension(200, 800));
sidebar.add(AddSubtract);
sidebar.setBackground(Color.GREEN);
JLabel test2 = new JLabel("Sidebar goes here");
sidebar.add(test2);
//The panel that displays all the cards
JPanel cardBoard = new JPanel();
cardBoard.setPreferredSize(new Dimension(400,640) );
//adding panels to the main panel
main.add(cardBoard, BorderLayout.CENTER);
main.add(title, BorderLayout.NORTH);
main.add(sidebar, BorderLayout.WEST);
frame.setContentPane(main);
frame.pack();
frame.setVisible(true);
}
}
and I want to add this class into the sidebar panel
public class AddSubtract {
int Number = 0;
private JFrame Frame = new JFrame("Math");
private JPanel ContentPane = new JPanel();
private JButton Button1 = new JButton("Add");
private JButton Button2 = new JButton("Subtract");
private JLabel Num = new JLabel ("Number: " + Integer.toString (Number));
public AddSubtract() {
Frame.setContentPane(ContentPane);
ContentPane.add(Button1);
ContentPane.add(Button2);
ContentPane.add(Num);
Button1.addActionListener(new Adding());
Button2.addActionListener(new Subtracting());
}
public class Adding implements ActionListener {
public void actionPerformed(ActionEvent e) {
Number++;
Num.setText ("Number: " + Integer.toString (Number));
}
}
public class Subtracting implements ActionListener {
public void actionPerformed(ActionEvent e) {
Number--;
Num.setText ("Number: " + Integer.toString (Number));
}
}
public void launchFrame(){
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.pack();
Frame.setVisible(true);
}
public static void main(String args[]){
AddSubtract Test = new AddSubtract();
Test.launchFrame();
}
}
Can someone explain to me how I can do this ?
I have a feeling that this is not going to work, but I really want to learn the way to do it.
This definately is not going to work. For starters, you have two main() methods. Second, if you want to add a class to your Frame, it should extend from JComponent. Basically, your code should look like this:
public class MainFrame extends JFrame {
public MainFrame() {
this.add(new MainPanel())
//insert all settings here.
}
}
public class MainPanel extends JPanel {
public MainPanel() {
this.add(new AddSubtract());
this.add(/*more panels*/)
}
}
public class AddSubtract extends JPanel {
public AddSubtract() {
//add buttons and stuff here
}
}
and variables do NOT start with capitals.
Edit: And when you have some JFrame, it's usually best to have a main() method with just one line:
public static void main(String[] args) {
new MainFrame();
}
just set the settings and configuration of the JFrame in the constructor.
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.