I have written this code. Here I want to make a JScrollPane work with JTextArea. But it is not working at all. Earlier I almost did the same thing. It used to work. Please provide a solution. Thanks in advance. I have posted the code.
protected void startServerProcess(int port) {
serverFrame = new JFrame("SERVER NOTIFICATIONS PANEL | Labyrinth Developers");
serverFrame.setSize(500, 500);
serverFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
serverFrame.setLocationByPlatform(true);
serverFrame.setLocationRelativeTo(null);
serverFrame.setVisible(true);
notificationsTA = new JTextArea();
notificationsTA.setBounds(0,0,466,500);
notificationsTA.setLineWrap(true);
notificationsTA.setRows(1000);
notificationsSP = new JScrollPane();
notificationsSP.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
notificationsSP.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
notificationsSP.setViewportView(notificationsTA);
notificationsSP.setWheelScrollingEnabled(true);
notificationsSP.setBounds(470, 0, 30, 500);
serverFrame.add(notificationsTA);
serverFrame.add(notificationsSP);
}
JTextArea is already added in JScrollPane so there is no need to add it again in JFrame as well. Remove below line:
serverFrame.add(notificationsTA);
You can add the component in the viewport of scroll pane using its Constructor as well that internally calls JScrollPane#setViewport() method.
notificationsSP = new JScrollPane(notificationsTA);
Some Points:
JFrame be default uses BorderLayout and you can add only single component in each section (North, South, East, West and Center).
Read more How to Use BorderLayout
Call serverFrame.setVisible(true); in the end after adding all the components.
Don't use setBounds() at all. Just leave it for Layout Manager to set the size and position of the components.
Use SwingUtilities.invokeLater() to make sure that EDT is initialized properly.
Read more
Why to use SwingUtilities.invokeLater in main method?
SwingUtilities.invokeLater
Related
ive got a JPane within a JScrolledPane. When i add content to JPane , JScrollPane doesnt show scrollbar. I tried repaint() and revalidate() but it didnt help.
static void ladowaniePaneli()
{
int b;
for(b=0;b<o;b++)
{
bgPanel[b] = new JBackgroundPanel();
nowyPanel[b] = new JPanel();
((FlowLayout)bgPanel[b].getLayout()).setVgap(0);
nowyPanel[b].setPreferredSize(new Dimension(790,518));
nowyPanel[b].setOpaque(false);
vertical[b] = new JScrollPane(nowyPanel[b]);
vertical[b].setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
vertical[b].setPreferredSize(new Dimension(789,517));
vertical[b].setOpaque(false);
vertical[b].getViewport().setOpaque(false);
bgPanel[b].add(vertical[b]);
}
}
It makes sense that scrollbars are never seen since you restrict the size of the contained component so that it's always trivially larger than the scrollopane's viewport:
nowyPanel[b].setPreferredSize(new Dimension(790,518));
Solution: don't do that.
if i dont use setPreferredSize method components wont warp to another line
You can try the Wrap Layout.
pairs should be warped to new line if they exceed JScrollPane width
Components are layed out individually. I you want a group of components to wrap then you would need to add the components to a separate panel first. Then add the panel to the panel using the WrapLayout.
I am new to the java (and programming in general) and I am trying to make my very first program. I'm stuck on the same problem for about 5 hours now, so I've decided to ask for help.
Basically I'm trying to make a program (2d game) that has about 20 positions on the board. Each position is either blue (owned by player1), red(owned by player2) or black(not owned by anyone).
The way I'm going about this is in main I've put a method that calls setup game, and then a method that plays game. I am working on the setup game, basically all it does is it makes an object of class Background (extends JPanel, and overrides paintComponent()) and 20 objects of class Position(extends JPanel, and overrides paintComponent()).
So far I'm stuck on putting those Position objects on top of Background object.
When I do:
Background background= new Background();
frame.getContentPane().add(background);
Position position1= new Position;
frame.getContentPane().add(position1);
frame.setVisible(true);
it shows only a circle and no background as I was hoping, if I first add position and then background, I only have background and no circle.
Anyway I'm new to the java and I am still having trouble founding my way around, however I've tried to search for solutions, and I've found many different solutions to this problem (such as adding position to background first, and then adding background to frame, etc.) but I couldn't make any of them to work.
I am aware that the way I am adding them both to frame is (very likely) completely wrong, but I wrote it that way so you would (hopefully) be sure that what I've wrote actually does show you that my code for each of those classes draws something on the screen.
PS: I didn't copy my code here as most of variable and method names aren't in English so it's fairly hard to read, but if you still think its needed, I will add it. Also I'm sorry for my probably stupid question, but I'm kinda hitting a wall here and I've no idea what else to try.
Basically I'm trying to make a program (2d game) that has about 20
positions on the board. Each position is either blue (owned by
player1), red(owned by player2) or black(not owned by anyone).
Painting in Swing by default never returns PreferredSize, is required to override getPreferedSize()
JPanel has implemented FlowLayout in API, this LayoutManager accepting only PreferredSize came from JComponents added to this container
after a.m. changes to post an SSCCE, short, runnable, compilable
Background background= new Background();
frame.getContentPane().add(background);
Position position1= new Position;
frame.getContentPane().add(position1);
A JFrame uses a BorderLayout by default. Also by default when you add a component to a Container that uses a BorderLayout the comopnent is added to the CENTER. Only one comonent can be added to the CENTER so your Position comonent replaces the Background component.
You want to add the Position to the Background and then add the Background to the frame. Something like:
Background background= new Background();
Position position1= new Position;
background.add(position1);
frame.add(background);
Note: there is no need to uses getContentPane() when adding a component to the frame.
The root panel should be a JFrame with a Container class underneath. When you call someRoot.window.container = yourJPanel, that loads the JPanel as the main component view of the JFrame. Note, a JFrame can only hold one JPanel but other JPanels can hold other JPanels. Just as you add the initial JPanel to the JFRam, a JPanel's own container can be another JPanel. Hope this helps.
Like this:
JPanel temp = new JPAnel();
frame.getContentPane().add(temp);
temp.getContentPane().add(new JPanel());
After these additions, there is a command that is illuding me but you call on JFrame to get it to refresh in real time. I think it is something like:
frame.validate(); //thanks #SMT
or something,
Try using something like
jPanelExampleName.validate();
jPanelExampleName.repaint();
after adding your JPanels.
It sounds like you want to use one JFrame and attach JPanels to it. This is how I personally would do it.
Declare your JFrame and JPanels
JFrame frame1 = new JFrame( "App Name");
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
Set the Background (I'm using colors but you get the idea)
panel1.setBackground(Color.orange);
panel2.setBackground(Color.orange);
panel3.setBackground(Color.orange);
panel4.setBackground(Color.orange);
Set your layout for the JFrame (I'm using BoxLayout not sure which would be best for you) You can find the best one for you and some sample code here. Also just set the default close operation.
frame1.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame1.setLayout( new BoxLayout( frame1.getContentPane(), BoxLayout.Y_AXIS ) );
Then Just attach your JPanels
frame1.add( panel1);
frame1.add( panel2);
frame1.add( panel3);
frame1.add( panel4);
frame1.pack();
frame1.setVisible( true );
This will allow you to use the JPanels you created and then change the colors via other methods.
I am trying to create a JScrollPane that contains a JPanel that will be increasing and decreasing in height. When it becomes larger than the size of the JScrollPane, it should create a vertical scroll bar which will allow me to scroll through the entire JPanel. However, I am having difficulty achieving this. Yes, I know I am not using LayoutManagers. No, I will not be using them, and I need a solution that does not involve their usage.
Here are the two button's AbstractActions that add and subtract from the JPanel:
class AddACT extends AbstractAction
{
public void actionPerformed(ActionEvent e)
{
info.setSize(420,info.getHeight() + 40);
info.add(new SubPanel); // Adds another JPanel into the main JPanel (for content input)
gui.repaint();
infoS.validate();
}
}
class RemoveACT extends AbstractAction
{
public void actionPerformed(ActionEvent e)
{
info.remove(subPanel()); // This would remove the last JPanel added to the main JPanel
info.setSize(420,info.getHeight() - 40);
gui.repaint();
infoS.validate();
}
And here is the code for the main JPanel and the JScrollPane:
final JPanel info = new JPanel();
final JScrollPane infoS = new JScrollPane(info, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
info.setLayout(null);
info.setSize(420,600);
infoS.setLocation(10,80);
infoS.setSize(420,490);
gui.add(infoS); // gui is the frame's content pane (the overall JPanel)
This is the second project I've been trying to learn GUI by doing. I am a complete novice in Swing and am only intermediate in Java. Sorry if I am making a blindingly obvious mistake.
1) Use LayoutManagers (+1 to #kleopatra and #GagandeepBali comments)
The absence of LayoutManagers only guarantees your GUI's will look very trashy (especially when run on other OSes/builds) and being a Novice you should rather learn the correct way than learn the wrong way and get into bad habits like calling setSize() etc.
Have a read on these links to get you started:
A Visual Guide to Layout Managers
Concurrency in Swing
2) See this example for how to use a JScrollPane, it simply adds a JPanel with buttons to a JScrollPane which in-turn is added to the JFrame.
3) Also see this example for how to make the JScrollPane vertically scroll-able only.
4) For more on JScrollPanes have a look here: How to Use Scroll Panes.
5) As for how it interacts with LayoutManager, if you do not explicitly set its size via setPreferredSize(Dimension d) the scroll pane computes it based on the preferred size of its nine components (the viewport, and, if present, the two scroll bars, the row and column headers, and the four corners)
6) On your usage of validate():
validate() is used when new JComponents are added to a visible component
revalidate() is used when JComponent is removed/added from a visible component
revalidate() covers validate() too
Thus always use this:
//add or remove component(s)
revalidate();
repaint();
References:
http://www.daniweb.com/software-development/java/threads/405568/validate-vs-revalidate
LayoutManager is not required to solve the problem. The problem in Thrfoot's example is in these lines:
final JScrollPane infoS = new JScrollPane(info, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
info.setLayout(null);
info.setSize(420,600);
The program appears to recognize there is a need for scroll bars (it would show the scroll bar if your setting was VERTICAL_SCROLLBAR_AS_NEEDED), but the actual scrolling does not work (the scroll bar slider is not there).
To fix this, first set the preferred size of info, then construct the infoS.
Example:
info.setPreferredSize(420,600);
final JScrollPane infoS = new JScrollPane(info, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
The idea is to set the preferred size of the info panel before it is used for the scroll pane. This is the same reason to set the size and location of infoS before adding to the gui:
infoS.setLocation(10,80);
infoS.setSize(420,490);
gui.add(infoS); // gui is the frame's content pane (the overall JPanel)
I've got a JPanel inside a JScrollPane. I draw things in the JPanel, and at some point I might draw past the width of the JScrollPane. In this case, I'd like the horizontal scroll bar to appear, and I'd like to be able to scroll around to view different parts of the JPanel. However, I end up clearing the JScrollPane.
frame = new JFrame();
frame.setBounds(100, 100, 1000, 800);
localScrollPane = new JScrollPane();
localScrollPane.setBounds(768, 6, 226, 350);
frame.getContentPane().add(localScrollPane);
localView = new JPanel();
localScrollPane.setViewportView(localView);
drawSomeThings(localView.getGraphics());
// wait for user input
int newWidth = drawThingsPastTheWidth(localView.getGraphics());
// these next two lines clear it
localView.setPreferredSize(new Dimension(newWidth, localView.getHeight()));
localView.revalidate();
What am I doing wrong? Thanks!
drawSomeThings(localView.getGraphics());
Don't use the getGraphics() method to do painting. The painting will be lost the next time Swing determines the components needs to be repainted.
Instead custom painting is done by overriding the paintComponent() method of your component.
Do not use setPreferredSize method, here's a related thread.
Do not specify explicetly the size of the JScrollPane with setBounds. Let the LayoutManager of it's parent take care of this.
JScrollPane should use a
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED by default. So
the scrollbar should appear automatically when the preferred size of
the child component is higher than the displayed area. Try to
revalidate the JScrollPane instead of the JPanel.
It would appear that redraw is being called at some point, I've not used swing for a while so I'm not entirely sure what the problem is but try debugging and running through the code step by step to see where redraw is being called would be a good starting place.
you should certainly use repaint instead of revalidate. revalidate only marks all the container upto the top level as invalid.
This is my first time using a JFrame. I can't get the window to display the text areas I've nested inside the JFrame. I am trying to get the text field with my name in it to display above the tabulated results, which I have omitted the formatting for until I can get the JFrame to work.
public void printResults(String[] names, int[] temp, int[][] scores, float[] averages, char[] letters){
JTextArea outarea= new JTextArea(5,20);
JTextArea name = new JTextArea(5,20);
Font font = new Font("Tahoma", Font.BOLD, 48);
name.setFont(font);
name.setText("Made By Durka Durka");
JFrame window = new JFrame();
window.getContentPane().add(name);
window.getContentPane().add(outarea);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.pack();
window.getContentPane().setVisible(true)
String out = "foo";
outarea.setText(out);
//JOptionPane.showMessageDialog(null,window);
}
The probable reason why the JFrame is not appearing is because of this line:
window.getContentPane().setVisible(true)
The above line is setting the visibility of the Container to which the JTextAreas have been added, but does not control the visibility of the JFrame itself -- therefore, the JFrame itself is not being displayed.
(To be more precise, the JFrame.getContentPane method returns a Container, so the above code is actually calling the Containter's setVisible method.)
Try the following instead:
window.setVisible(true);
This will set the visibility of the JFrame itself to be visible.
Also, as the other answers have suggested, try using Layout Managers to control the locations of where the components should be displayed. The following are links to using two of the several Layout Managers which could be used to layout components.
How to Use BorderLayout
How to Use GridLayout
You should use some of the layout managers. This link should help you:
http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html
The standard java layout managers are sometimes really hard to handle. Maybe you should also look into the JGoodies: http://www.jgoodies.com/ "Framework". It is easier to use and you realize that even a java gui can look nice..
First things first - are you calling printResults on the Event Dispatch Thread using SwingUtilities.invokeLater(Runnable runnable); or SwingUtilities.invokeAndWait(Runnable runnable);? Remember that you need to do all GUI work on the EDT.
If so, try this:
JFrame window = new JFrame();
// CHANGES HERE
window.getContentPane().setLayout(new BorderLayout();
window.getContentPane().add(name, BorderLayout.NORTH);
window.getContentPane().add(outarea, BorderLayout.CENTER);
// END CHANGES