Why is my JScrollPane not working? - java

Can someone work out why my JScrollPane is not working. Perhaps something I may have missed. I realize this might be silly without any more context than what I've shown but please ask and I shall be happy to provide more.
public ApplicationFrame(String title, int x, int y, int width, int height) {
// Constructor for the ApplicationFrame, no implicit Construc.
setTitle(title);
setResizable(true);
setBounds(x, y, width, height);
setLayout(new BorderLayout());
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setIconImage(new ImageIcon(getClass().getResource("resources/topLeft.png")).getImage());
topMostMenuBar = new TopMenuBar(this);
setJMenuBar(topMostMenuBar.getMyJMenuBar());
paneEdge = BorderFactory.createLineBorder(Color.gray);
blackline = BorderFactory.createLineBorder(Color.black);
this.frameContent = new ApplicationPanel() {
//#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(TI, 0, 0, null);
}
};
mainImageScrollPane = new JScrollPane(frameContent);
statusPanel = new ApplicationPanel(new Color(0xfff0f0f0));
leftPanel = new ApplicationPanel(new Color(0xfff0f0f0));
testPanel = new ColorPanel(new Color(0xfff0f0f0));
testPanel.setPreferredSize(new Dimension(50,300));
add(mainImageScrollPane, BorderLayout.CENTER );
add(statusPanel, BorderLayout.SOUTH);
add(leftPanel, BorderLayout.WEST);
Container visibleArea = getContentPane();
visibleArea.add(frameContent);
setVisible(true);
do {
loadImageIn();
} while (!initLoadSuccess);
initButtons();
leftPanel.add(testPanel, BorderLayout.SOUTH);
} // end Constructor **
This is a big piece of code so I'm not sure how to make an SSCCE out of it. What youre looking at is the constructor to my subclass of a JFrame, which holds 3 panels. The ApplicationPanel is at this point just a JPanel. The loadImageIn() method opens a filechooser and then loads the chosen image which is painted onto frameContent. The image displays fine, everything works, except when I resize the window, there are no scrollbars.

You have this line, which adds the ApplicationPanel to the visibleArea...
visibleArea.add(frameContent);
Maybe you actually mean this, which adds the JScrollPane to the visibleArea (and the JScrollPane already contains the ApplicationPanel)...
visibleArea.add(mainImageScrollPane);
When you call new JScrollPane(frameContent), it doesn't do anything to the panel inside it, it just adds a wrapper around the outside. So, if you want the ability to scroll, you need to refer to the JScrollPane wrapper, rather than the panel itself.

You didn't specify any size for your frameContent. Is it intentional?
Additionally your frameContent is later on being added to visibleArea. Meaning no longer in the mainImageScrollPane JScrollPane
Maybe you wanna have:
visibleArea.add(mainImageScrollPane);, but you need to set your panel size

mainImageScrollPane.setViewportView(<component_to_be_scrollable>);

Related

How to add elements to GridBagLayout from paintComponent()

In the following code, in the constructor the label gets correctly created and displayed on the screen. Note that it is added to the GridBagLayout() layout manager. Then, in the paintComponent() method that we override from the JPanel extention, we reset the contents of the JPanel and add the label again. However, this time the label is not displayed on the screen. I would expect it to be added normally, but it is not. Why is this the case?
public class MyPanel extends JPanel {
private final GridBagConstraints grid = new GridBagConstraints();
public MyPanel () {
setBounds(200, 200, 1000, 1000);
setLayout(new GridBagLayout());
setOpaque(false);
setVisible(false);
grid.anchor = GridBagConstraints.PAGE_END;
JLabel oldLabel = new JLabel("This is an old Label");
add(oldLabel, grid);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
removeAll();
JLabel newLabel = new JLabel("This is a new Label");
add(newLabel, grid);
revalidate();
repaint();
}
}
In this example the component is known, but in my situation I have a variable amount of components that is not known beforehand and changes during the program.
Like the comments to my question kindly say, my approach is not correct.
Under no circumstances should a paintComponent create, add, or remove components. Painting is triggered by the system, for many many reasons, including seemingly trivial events like moving the mouse over the window. Also, never call repaint from a paintComponent method; that forces Swing to eventually called paintComponent again, which means you have created an infinite loop.
The solution is to add the components to the panel and invoke revalidate() on the panel instead.

Best practice to resize JScrollPane

I read some answered questions in this forum (this one for example) where it is strictly recommended to avoid the use of setXXXSize() methods to resize components in swing applications.
So, coming to my problem, i would like to know how to best resize a JScrollPane in order to avoid its parent panel to increase its size without any control.
Before writing some code, i want to describe the real situation, since i will post a "toy example".
In my JFrame i'm currently using a border layout for my content pane. At BorderLayout.CENTER there is a JPanel where i do some custom painting.
At BorderLayout.EAST there is a JPanel (say eastPanel) containing some components inside another panel (this panel will be added to eastPanel at BorderLayout.NORTH), and a JScrollPane which contains a JTable (added to eastPanel at BorderLayout.CENTER). This table will have a lot of rows.
Since i want eastPanel's height to be the same as centerPanel's height, i need some way to avoid the JScrollPane to increase its size in order to try to display as much rows as possible.
For now i wasn't be able to find another solution apart from calling setPreferredSize on the eastPanel containing the scrollpane, but i have to admit that i hate this kind of solution.
Sample Code
In this code sample i added some random labels at the north of eastPanel and inside the JScrollPane, since my purpose was to post a short sample of code.
However, the situation is very similar to the one i have described above.
I wasn't be able to solve my problem without using this "terrible" line of code :
eastPanel.setPreferredSize(new Dimension(eastPanel.getPreferredSize().width, centerPanel.getPreferredSize().height));
I would like to avoid a more complex layout for a simple situation like this. Am i missing something ? Also, is setting that empty border an acceptable way to set the size of the panel where i will do some custom painting?
Code :
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class Test
{
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new TestFrame().setVisible(true);
}
catch(Exception exception) {
JOptionPane.showMessageDialog(null, "Fatal error while initialiing application", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
}
}
class TestFrame extends JFrame
{
public TestFrame() {
super("Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel pane = new JPanel(new BorderLayout(20, 0));
pane.setBorder(new EmptyBorder(20, 20, 20, 20));
JPanel centerPanel = new JPanel();
centerPanel.setBackground(Color.WHITE);
centerPanel.setBorder(new EmptyBorder(400, 400, 0, 0));
// centerPanel.setPreferredSize(new Dimension(400, 400));
JPanel eastPanel = new JPanel(new BorderLayout(0, 20));
JPanel labelsContainer = new JPanel(new GridLayout(0, 1));
for(int i=0;i<7;i++) labelsContainer.add(new JLabel(String.valueOf(i)));
eastPanel.add(labelsContainer, BorderLayout.NORTH);
JPanel moreLabelsContainer = new JPanel(new GridLayout(0, 1));
for(int i=7;i<70;i++) moreLabelsContainer.add(new JLabel(String.valueOf(i)));
JScrollPane scroll = new JScrollPane(moreLabelsContainer, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
eastPanel.add(scroll, BorderLayout.CENTER);
eastPanel.setPreferredSize(new Dimension(eastPanel.getPreferredSize().width, centerPanel.getPreferredSize().height));
pane.add(centerPanel, BorderLayout.CENTER);
pane.add(eastPanel, BorderLayout.EAST);
setContentPane(pane);
pack();
setLocationRelativeTo(null);
}
}
Thanks for your help !
I am not aware of a layout manager that restricts the height of the panel based on the height of a specific component in the panel.
One way is to customize the behaviour of the parent panel that contains the two child components.
The code might be something like:
#Override
public Dimension getPreferredSize()
{
Dimension d = super.getPreferredSize();
BorderLayout layout = (BorderLayout)getLayout();
Component center = layout.getLayoutComponent(BorderLayout.CENTER);
int centerHeight = center.getPreferreidSize().height;
if (d.height > centerHeight)
d.height = centerHeight;
return d;
}
This approach will allow for dynamic calculation of the height based on the component in the center.
Another option is to write you own layout manager. Then you can control this type of logic from within the layout manager.
Also, is setting that empty border an acceptable way to set the size of the panel where i will do some custom painting?
I override the getPreferredSize() to return the appropriate dimension.
By using the EmptyBorder you lose the ability to add a true Border to the panel, so I wouldn't recommend it.

Adding JScrollPane to JPanel

I'm trying to add a JScrollPane to an JPanel from a separate class. And thanks to some questions, which were asked so far, I could help myself create them. But my problem is still a little bit special.
I want to display an image on a JPanel and if the image is to large for the panel, I want to add scrollbars. But the scrollbars won't appear.
(When I set the ScrollPaneConstants to ****_SCROLLBAR_ALWAYS the frame of the bar appears, but without the bars to scroll).
I guess i have to connect the imagesize with the bars, so that they appear?
Some pieces of my code:
MainWindow
public class Deconvolutioner extends JFrame
{
Draw z;
Picturearea picturearea;
class Draw extends JPanel
{
public void paint(Graphics g)
{
}
}
public Deconvolutioner()
{
setTitle("Deconvolutioner");
setLocation(30,1);
setSize(1300,730);
super.setFont(new Font("Arial",Font.BOLD,11));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
this.setLayout(flow);
picturearea = new Picturearea();
picturearea.setLayout(new GridBagLayout());
JScrollPane scrollPane = new JScrollPane(picturearea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setPreferredSize(new Dimension(1000, 664));
getContentPane().add(scrollPane, flow); // add scrollpane to frame
add(z = new Draw());
setVisible(true);
}
}
JPanel Class
public class Picturearea extends JPanel
{
BufferedImage image;
int panelWidth, panelHeight, imageWidth, imageHeight;
public Picturearea()
{
setBackground(new Color(210,210,210));
setBorder(LineBorder.createBlackLineBorder());
setVisible(true);
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
public void setPicture(BufferedImage picture)
{
try
{
image = picture;
}
catch (Exception e)
{
System.err.println("Some IOException accured (did you set the right path?): ");
System.err.println(e.getMessage());
}
repaint();
}
}
Thanks for your time.
The problem is that the JScrollPane has no way to know if it should display scroll bars or not, since the Picturearea it contains doesn't tell anything about its preferred size (or rather, it returns the preferred size based on its layout and on the components it contains. But since it doesn't contain any component, the returned preferred size is probably (0, 0)).
I would simply use a JLabel instead of the custom Picturearea class. A JLabel can display an image just fine, and it returns the appropriate Dimension when asked for its preferred size.
You can create a JLabel first and then add the Label to JPanel picturearea before creating instance for JScrollPane .
Have a try and it will work.
Example code is as follows:
JLabel imageLabel = new JLabel(new ImageIcon("d:\\099.jpg"));
picturearea.add(imageLabel);**
JScrollPane scrollPane = new JScrollPane(picturearea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

Painting a custom JButton and a text line

I'm designing an optimization system for public transport in a big city. So I have a map with some points on it, but don't care about it)
All I need is: my own JButton, which looks like a color-filled circle and a small text tag near it. I got some problems while overriding the paintComponent() method.. the round button is painted correctly, but not the text.
BUT, when i'm resizing the window manually, the text appears for a second, then it gets repainted again and dissapears.
Hope you guys understood my needs, thanks for help ;)
import java.awt.*;
import javax.swing.*;
public class JRoundButton extends JButton {
String label;
Color color;
int x,y;
public JRoundButton(Color color,int x,int y,String str)
{
label=str;
this.x=x;
this.y=y;
this.color=color;
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Dimension size = getPreferredSize();
setPreferredSize(size);
this.setBounds(0, 0, 10, 10);
setContentAreaFilled(false);
g.setFont(new Font("Arial",Font.BOLD,14));
g.drawChars(label.toCharArray(), 0, label.length(), 12,12);
g.fillOval(0,0,8,8);
}
public void paintBorder(Graphics g)
{
g.setColor(Color.white);
g.drawOval(0,0, 9, 9);
}
public static void main(String[] args)
{
JButton button = new JRoundButton(Color.GRAY,150,150,"Times Square");
JFrame frame = new JFrame();
frame.getContentPane().setBackground(Color.black);
frame.setSize(300, 300);
frame.setVisible(true);
frame.add(button);
}
}
Seems that the call to 'setBounds( 0, 0, 10, 10 )' sets a component footprint that is too small to accomodate the text string. Extending the bounds to 100px wide and bringing down the point size to 6 looks to work okay.
1) NEVER set properties of the button in the paintComponent() method.
Dimension size = getPreferredSize();
setPreferredSize(size);
this.setBounds(0, 0, 10, 10);
setContentAreaFilled(false);
Get rid of the above code.
2) Dont set the Font of the Graphics object in the paintComponent() method. Thats what the setFont(...) method is used for.
3) There is no need to do any custom painting. If you want a circle, then add an Icon to the JLabel.
4) Don't override the paintBorder() method. If you want a Border then create a custom border and add it to the button using the setBorder() method.
In short there is no need to extend the button. Get rid of your JRoundButton class. Your code should simply look something like:
JButton = new JButton("Times Square");
button.setFont( new Font("Arial",Font.BOLD,14) );
button.setIcon( new OvalIcon(Color.WHITE, iconSize) );
Of course you will need to create an OvalIcon class but that is easy to implement since there are only three methods and you already know what the painting code should be.
I'd just cheat and use a unicode circle in the JButton's text. E.g.:
import javax.swing.*;
JFrame frame = new JFrame();
frame.getContentPane().add(new JButton("<html><font size='+10' color='red'>●</font> I'm next to a red circle!</html>"));
frame.pack();
frame.show();

How to display panels with component in frame

Why my JFrame 'frame' is diplaying empty window, when it should give me 3 menu buttons and my own painted JComponent below ? What am I missing here ?
import java.awt.*;
import javax.swing.*;
public class Eyes extends JFrame {
public static void main(String[] args) {
final JFrame frame = new JFrame("Eyes");
frame.setPreferredSize(new Dimension(450, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel players = new JPanel(new GridLayout(1, 3));
players.add(new JButton("Eyes color"));
players.add(new JButton("Eye pupil"));
players.add(new JButton("Background color"));
JPanel eyes = new JPanel();
eyes.add(new MyComponent());
JPanel content = new JPanel();
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(players);
content.add(eyes);
frame.getContentPane();
frame.pack();
frame.setVisible(true);
}
}
class MyComponent extends JComponent {
public MyComponent(){
}
#Override
public void paint(Graphics g) {
int height = 120;
int width = 120;
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
BasicStroke bs = new BasicStroke(3.0f);
g2d.setStroke(bs);
g2d.setColor(Color.yellow);
g2d.fillOval(200, 200, height, width);
g2d.setColor(Color.black);
g2d.drawOval(60, 60, height, width);
}
}
Your line:
frame.getContentPane();
doesnt do anything but access the content pane of the frame. Instead of getting the content pane, you should set your content pane, like this:
frame.setContentPane(content);
EDIT:
alternatively, as #trashgod points out, you could use the getContentPane method to access the default content pane and add your content component to that:
frame.getContentPane().add(content);
I think you are attempting to use nested JPanels. This is certainly a way to organize your components, but downside to is the fact that it gets difficult to manage in some cases. You could try this snippet of code below. In the program you will find:
1) An array of JLabel
2) An array of JTextField
3) Nested JPanels
At the end of the program I use the Container to add the final product of these object to my Graphics Window.
The most efficient way I can think of is to define these components at the top of my program so that I can reuse them later as I need to.
To achieve this you can try this snippet of code:
import javax.swing.*; //Required to use Swing Components
public class TestGUI extends JFrame
{
JLabel[] label; //Define this with an array
JTextField[] textField; //Define this with an array as well
private int nLabels; //Number of labels preferred
private int nTextFields; //Number of text fields preferred
public testGUI(int amt)
{
//Assuming that you want equal amounts of each,
//set these two variables to the "ant" input parameter
nLabels = amt;
nTextFields = amt;
//Set component attributes
label = new JLabel[2]; //Label compared text fields
textField = new JTextField[2]; //Use two of these for comparison
textField[0].setEnabled(false); //Disabled editing
//Do nothing with the second text field
JPanel labels = new JPanel(); //Place JLabels here
//Use this to align the labels vertically
labels.setLayout(new GridLayout(2, 1));
//Use this for loop to add the labels to this JPanel
for(int i = 0; i < nLabels; i++)
{
labels.add(label[i]);
//You can also define and apply additional properties
//to labels inside this loop. TIP: You can do this in
//any loop
}
JPanel txtFields = new JPanel(); //Place JTextFields here
//Use this to align the text fields vertically
txtFields.setLayout(new GridLayout(2, 1));
//Use this for loop to add the labels to this JPanel
for(int i = 0; i < nTextFields; i++)
{
textFields.add(textField[i]);
//You can also define and apply additional properties
//to text fields inside this loop. TIP: You can do
//this in any loop
}
//Now we have the two components, you asked for help with, set up
//Next, we will need another JPanel to add these to panels to.
//This JPanel will be added to the JFrame Container
//You probably know how to run this via the "main" method
JPanel window = new JPanel();
//Place the JPanel for the labels and text fields
//This requires a horizontal grid
window.setLayout(new GridLayout(1, 2));
//Add the the two JPanels: "labels" and "txtFields"
window.add(labels);
window.add(txtFields);
//Define the Container object to set up the GUI
Container container = getContentPane();
//Apply the "window" JPanel object to the container
container.add(window, BorderLayout.CENTER);
//Center this in the Graphics Window when displayed
}
//Any other methods and/or functions can be added as well
//If they are, they must placed in the constructor method above
}
This is the approach that I would use when trying to go at making and manipulating my Graphics Windows that I write. Sometimes I write applets, but only after making sure that I have everything functioning properly in a plain Graphics Window.
I hope this helps.
If you have any other questions, just let me know and I will answer the to the best of my ability, thanks.

Categories