Swing (JScrollPane - scroll bar) help
Hello all..
I am new user in Swing. Currently I am developing a program using JSCrollPane. I have to draw a kind of chart in it. Therefore as a drawing media, I used the JPanel, in which I put it inside my JScrollPane. Then.. since my graphic is long.. then I set the
setHorizontalScrollBarPolicy value to ALWAYS. Then I put my JPanel using the following commands :
this.jScrollPane1.setViewportView(this.jPanel2);
this.jScrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
Fyi, my JPanel size is set to be wider than the jScrollPane3 size. Nevertheless.. during the run time the horizontal scroll bar is not shown. I am completely loss on how to solve this. Does anyone has any clue or solution for this problem. Thank you very much in advance.
Kariyage.
Fyi, my JPanel size is set to be wider than the jScrollPane3 sizeYou should use panel.setPreferredSize(...) not panel.setSize(...);
Similar Messages
-
JScrollPane scroll bar trouble on rebuild
I've been working on this for hours (about 4 hours now) without finding the right solution, so maybe someone can help. I searched through a few pages of the forum but didn't see this exact issue. And the tutorial online doesn't help much.
I have a JPanel in a JScrollPane in a JFrame. The JFrame has it's height reduced if its over a particular size (in the test case, it gets reduced). When it first loads, it's fine. However, if I rebuild the whole JFrame (some event causes the JPanel content to change, and refresh() is called again), the window remains the same size but the vertical scroll bar extends off the bottom of the frame. If I manually resize the frame with the mouse (even by 1 pixel), the scroll bar updates and looks correct again. What is the correct way to do this? Calling revalidate() on the JScrollPane after doing the setSize() doesn't do anything. And why does it work the first time when the JFrame is first built through the Constructor?
example code:
public class MyFrame extends JFrame {
public MyFrame() {
super();
refresh();
private void refresh() {
JPanel jp = new JPanel();
jp.setLayout(new SpringLayout());
// add some stuff to jp
JScrollPane scrollPane = new JScrollPane(
JScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
scrollPane.getViewport().add(jp);
setContentPane(scrollPane);
pack();
if (getHeight() > MAX_HEIGHT) {
setSize(getWidth(),MAX_HEIGHT);
}When you have changed the content, call getRootPane().validate(); instead of pack(), as in this slightly modified version of your sample program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyFrame extends JFrame implements ActionListener {
private static final int MAX_HEIGHT = 100;
public MyFrame() {
super();
refresh(true);
public static void main(String[] args) {
MyFrame myFrame = new MyFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
private void refresh(boolean pack) {
JPanel jp = new JPanel();
jp.setLayout(new BoxLayout(jp,BoxLayout.Y_AXIS));
JButton refreshButton = new JButton("Refresh");
refreshButton.setActionCommand("refresh");
refreshButton.addActionListener(this);
jp.add(refreshButton);
jp.add(new JLabel("Hello"));
jp.add(new JLabel("There"));
jp.add(new JLabel("Why"));
jp.add(new JLabel("Doesn't"));
jp.add(new JLabel("Refresh"));
jp.add(new JLabel("Work"));
JScrollPane scrollPane = new JScrollPane(
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
scrollPane.getViewport().add(jp);
setContentPane(scrollPane);
if (pack) {
pack();
else {
getRootPane().validate();
if (getHeight() > MAX_HEIGHT) {
setSize(getWidth(),MAX_HEIGHT);
public void actionPerformed(ActionEvent ae) {
refresh(false);
} -
JScrollPane - scroll bar not visible
I'm writing a graphical chat application where the user presses buttons to insert images into their message. The buttons reside in a JPanel with a GridLayout. As i have more buttons than can be physically seen on the screen I'm trying to use a JScrollPane encapsulated in the JPanel so that the user can scroll down the button list to select appropriate symbols. The problem i'm having is that the scroll bars do not appear so the user can only use symbols which are visible. Here is the code for what i'm trying to acheive.
buttonPanel.setLayout(new GridLayout(9,3));
buttonPanel.add(Button1);
buttonPanel.add(Button2);
buttonPanel.add(Button3);
buttonPanel.add(Button4);
.....etc to around Button100
buttonHolder.add(new JScrollPane());
buttonHolder.setPreferredSize(new Dimension(400,400));
buttonHolder.setMaximumSize(new Dimension(400,400));I think I'm missing something from the add JScrollPane bit but I'm not sure what exactly!
PLEASE HELP - this is for my third year dissertation and is the last bit I need to do before it is finished.First, you need to add your panel to the JScrollPane object. Then you add the JScrollPane object to the frame, not the panel itself.
As for setting the scrollbars of the JScrollPane, you could try setVerticalScrollbarPolicy() and setHorzontalScrollbarPolicy(). -
Hello anyone,
I am fairly new to flash, I am using the MX version. I am
having trouble getting my scroll bars to load with the page load?
The bar shows up, but it does not give the option to scroll. If I
click off the page and return to it then the slider is there and it
works, but not on initial load. I have tried to set the action
script run on load but this has not worked. I am a little confused
and any help would be greatly appriciated.
Also as an aside issue, can you load images into a text
box?am I on the right board for this type of question? I am not
very knowledgable in action scripts, but I have been trough the
tutorials and I bought the action scripts for dummies book, however
I have done everything that they say to do and still can't get the
bars to work right.
any help or redirection for help somewhere else would be
greatly appriciated. -
Hello,
I am making a website in flash and need some help with the
actionscript,
Firstly I have coded the drop down menu, its a little buggy
but the main problem with it is the buttons will only work if its a
get URL command rather than go to and stop.
Secondly, I need some help coding the scroll bar if someone
wouldn't mind offering a bit of help with that. I have just under 4
days to get this finished, it’s for my final major project in
college, and would you believe it our technician broke FLASH so I
can't get help form my tutors.
If some one could help I would be extremely grateful, thanks.
Oh and here is a link to the flash file so you can have a
look at the coding.
http://www.breeze-studios.com/breezeflash.fla
Also here is the publish bit so far so you can see what im
going on about.
http://www.breeze-studios.com/breezeflash.swfhi
JPanel jp = new JPanel();
JScrollPanel jsp = new JScrollPanel(jp);
getContentPane.add(jsp); -
JScrollPane - SCROLL BAR width?
I currently have a JEditorPane inside a JScrollPane
Whenever I have content that exceeds the height of the JScrollPane, I get a scroll bar on the right. Unfortunately, I think this scroll bar is a bit TOO THICK and is unsightly. Is there anway I can explicitly specify the WIDTH of this scroll bar if and when it's needed? THANKS!Try this when creating the layout:
JScrollBar vsb = JScrollPane.getVerticalScrollBar();
Dimension sbsize = vsb.getSize();
Dimension newsbsize = new Dimension(sbsize.getWidth() - 5 , sbsize.getHeight() );
vsb.setPreferredSize(newsbsize);
You could also try setting the Maximum size using vsb.setMaximumSize(newsbsize);
Adjust the 5 in the new Dimension line to control how much smaller the witdh is from normal. -
Scroll bar :help for a newbie
Hello, I need some help to introduce scroll bar into my programs;
For example I have a JPanel in which I have to introduce a scroll bar when it's needed.
Can you help me please?hi
JPanel jp = new JPanel();
JScrollPanel jsp = new JScrollPanel(jp);
getContentPane.add(jsp); -
Issue with Multithreading and vertical scroll bar - help needed to debug!!!
I have been working on a desktop Visual Studio 2010 application for quite a few years. It is written in C++ and MFC. This code is a combination of code I have written and code I inherited. It worked great for years on Windows XP, but when I ported
it to Windows 7, a tricky problem has come up that I am having the darnest time trying to figure out
In summary, it is a single .exe desktop application. There is the main thread (thread A), which launches another thread (thread B). Both threads share a pointer to a single window object which displays events. This window also implements a vertical and horizontal
scroll bar.
The interaction and message processing between the threads seems a little sticky to me. Both threads A and B call the same member function of the CWnd object. BUT, Thread B ALSO posts messages to thread A's queue.
So, in thread B, you will see code like this, which makes a direct call to the output window object, AND THEN it also posts a message to Thread A's mainframe window like this...
if( m_pEventLog )
pOutputWindow->AddLine("Some test...");
if( m_phNotifyWnd[RECEIVE] && m_puiEventWMsg[RECEIVE] ) {
::PostMessage( m_phNotifyWnd[RECEIVE], m_puiEventWMsg[RECEIVE], 0, (LPARAM) pPkt );
WHEN thread A receives the message that thread B posted above, it only does the following:
LRESULT CMainFrame::OnSocketReceive( WPARAM, LPARAM lParam )
CSPkt* pPkt;
CRWPkt* pRWPkt;
CSPktSocket* pSocket;
ULONG ulType;
CString csTemp;
CBSWords bsWords;
CSSSWords sssWords;
CRWPkt* pLoopBackRWMsg; // used if we have to send a loopback msg back to sender
CLMsg lmsg;
m_wndTextWindow.AddLine("Test message");
return 0;
So both threads are writing to the output window via the .AddLine() member function.
void COutputWnd::AddLine( CString& strLine, COLORREF crColor )
UpdateVScroll();
return;
And this function then makes a call to :UpdateVScroll(). The problem seems to arise because thread B does a
post to thread A, where thread A in turn writes to the output window. Eventually, the program
HANGS in the call to
SetScrollInfo() below...
void COutputWnd::UpdateVScroll()
CSingleLock lock( &m_CSVertScrollLock ); // lock things up while we are in here
BOOL bok = lock.Lock();
if (lock.IsLocked() == TRUE)
int iMax = m_FifoIndices.GetHighestIndex();
if( iMax < ( m_iMaxViewableLines - 1 ) )
iMax = 0;
//SetScrollRange( SB_VERT, 0, iMax, FALSE );
//SetScrollRange( SB_VERT, 0, 9, FALSE );
SCROLLINFO scrollinfo;
scrollinfo.cbSize = sizeof(SCROLLINFO);
scrollinfo.fMask = SIF_RANGE;
scrollinfo.nMin=0;
scrollinfo.nMax= iMax;
SetScrollInfo(SB_VERT, &scrollinfo, FALSE);
lock.Unlock();
It doesn't take long for the program to hang...maybe about 10 seconds.
When I hit DEBUG->BREAK ALL, I get the output below in the CALL STACK WINDOW.
ntdll.dll!770070f4()
[Frames below may be incorrect and/or missing, no symbols loaded for ntdll.dll]
user32.dll!76c0cde0()
user32.dll!76c018d9()
>
mfc100d.dll!AfxInternalPumpMessage() Line 153 + 0x13 bytes
C++
mfc100d.dll!CWinThread::PumpMessage() Line 900
C++
mfc100d.dll!CWinThread::Run() Line 629 + 0xd bytes
C++
mfc100d.dll!_AfxThreadEntry(void * pParam=0x0022f6a4) Line 122 + 0x13 bytes
C++
msvcr100d.dll!_callthreadstartex() Line 314 + 0xf bytes
C
msvcr100d.dll!_threadstartex(void * ptd=0x004f97c0) Line 297
C
kernel32.dll!762cee1c()
ntdll.dll!770237eb()
ntdll.dll!770237be()
NOTE: If I never make the call to SetScrollInfo(), the program never HANGS.
Sooo....I am trying to determine if there is a fundamental issue with the way the threads are communicating that is causing the issue, or if maybe I have a memory overwrite. It always hangs in ::SetScrollInfo(), no matter what I comment and uncomment. This
makes me think that scroll bat behavior is different in Windows 7 than on XP, but I have not been able to find any documentation about it.
Can anyone provide any insight as to what may be the cause of the program hanging>It might look like working but it will crash eventually. The windows are thread affine and other thread must never touch other threads windows. Sometimes you might get along but usually it just crashes.
Thread B must use PostMessage ( or SendMessage if suncronous action is require) to thread A's windows to achieve correct updating. Some very basic calls are implemented directly with SendMessage so they are safe to use but then you must individually check
which ones are safe.
Also having multiple SendMessage calls from B to A require rendezvous which might cause other problems ( thread B stalls or program deadlocks, depending on other program structure).
So PostMessage is the way to do it ( or create yourself another inter-thread mechanism, possible but usually too much troble) -
I've attached the code that I created for using a scroll bar.. When you click to scroll and go back up to the top it doesn't go all the way up to the top..It goes a few lines down still. How can I adjust this to be correct?
import caurina.transitions.*;
laminatetxt_mc.mask = scrollmask_mc
var yOffset:Number;
var yMin:Number = 0;
var yMax:Number = scrollbar_mc.track_mc.height - scrollbar_mc.handle_mc.height;
scrollbar_mc.handle_mc.addEventListener(MouseEvent.MOUSE_DOWN, handleDown);
stage.addEventListener(MouseEvent.MOUSE_UP, handleUp);
function handleDown(e:MouseEvent):void
stage.addEventListener(MouseEvent.MOUSE_MOVE, handleMove);
yOffset = mouseY - scrollbar_mc.handle_mc.y;
function handleUp(e:MouseEvent):void
stage.removeEventListener(MouseEvent.MOUSE_MOVE, handleMove);
function handleMove(e:MouseEvent):void
scrollbar_mc.handle_mc.y = mouseY - yOffset;
if(scrollbar_mc.handle_mc.y <= yMin)
scrollbar_mc.handle_mc.y = yMin;
if(scrollbar_mc.handle_mc.y >= yMax)
scrollbar_mc.handle_mc.y = yMax;
var scrollpercent:Number = scrollbar_mc.handle_mc.y / yMax;
Tweener.addTween(laminatetxt_mc, {y:(-scrollpercent*(laminatetxt_mc.height-scrollmask_mc.height)), time:1});
e.updateAfterEvent();import caurina.transitions.*;
laminatetxt_mc.mask = scrollmask_mc
var yOffset:Number;
var yMin:Number = 0; // set minimum handle_mc y
var yMax:Number = scrollbar_mc.track_mc.height - scrollbar_mc.handle_mc.height; // set max handle_mc.y
scrollbar_mc.handle_mc.addEventListener(MouseEvent.MOUSE_DOWN, handleDown);
stage.addEventListener(MouseEvent.MOUSE_UP, handleUp);
function handleDown(e:MouseEvent):void
stage.addEventListener(MouseEvent.MOUSE_MOVE, handleMove);
yOffset = mouseY - scrollbar_mc.handle_mc.y;
function handleUp(e:MouseEvent):void
stage.removeEventListener(MouseEvent.MOUSE_MOVE, handleMove);
function handleMove(e:MouseEvent):void
scrollbar_mc.handle_mc.y = mouseY - yOffset;
if(scrollbar_mc.handle_mc.y <= yMin)
scrollbar_mc.handle_mc.y = yMin;
if(scrollbar_mc.handle_mc.y >= yMax)
scrollbar_mc.handle_mc.y = yMax;
var n:Number = scrollbar_mc.m*scrollbar_mc.handle_mc.y+scrollbar_mc.b;
Tweener.addTween(laminatetxt_mc, {y:n, time:1});
e.updateAfterEvent();
// the following assigns the parameters needed to scroll correctly.
paramF(scrollbar_mc,yMin,scrollmask_mc.y,yMax,scrollmask_mc.y-laminatetxt_mc.hei ght+scrollmask_mc.height);
function paramF(mc:MovieClip,x1:Number,y1:Number,x2:Number,y2:Number):void{
mc.m = (y1-y2)/(x1-x2);
mc.b = y1 - mc.m*x1; -
Scroll bar problems ..Please help!!!!!!
This is what the program looks like. topPanel has newItemPanel on top of it. when you click continue newItemPanel becomes invisible and newItemDescriptionPanel becomes visible. When you click continue newItemDescriptionPanel becomes invisible and priceEnterPanel becomes visible.
I want newItemDescriptionPanel and priceEnterPanel to have a scroll bar. but everything I have tried hasn't worked. I am new. You will see the code is ugly and there is an attempt to add a scrollbar.
Please help
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
import java.lang.System;
public class MainPanel extends JFrame implements ActionListener
private boolean firstRun = true;
private final int ITEM_PLAIN = 0; // Item types
private final int ITEM_CHECK = 1;
private final int ITEM_RADIO = 2;
private JPanel topPanel;
private JPanel newItemPanel;
private JRadioButton onlineAuctionRadio;
private JRadioButton fixedPriceRadio;
private ButtonGroup bg;
private JButton continueButton;
private JLabel blankLabel; //used to give space between things
private JPanel newItemDescriptionPanel;
private JPanel takeAdditionalSpacePanelCheckBox;
private JPanel takeAdditionalSpacePanel;
private JPanel takeAdditionalSpacePanelLabel;
private JPanel takeAdditionalSpacePanelLabel2;
private JPanel takeAdditionalSpacePanel2;
private JPanel takeAdditionalSpacePanel3;
private JPanel takeAdditionalSpacePanel4;
private JPanel takeAdditionalSpacePanel5;
JScrollPane displayScroller;
JEditorPane itemDescriptionTextArea;
GridBagLayout gridbag;
GridBagConstraints gbc;
private JCheckBox secondCategoryCheckBox;
private JLabel itemTitleLabel;
private JLabel requiredLabel, requiredLabel2;
private JLabel requiredStarLabel;
private JTextField itemTitleTextField;
private JLabel subtitleLabel;
private JTextField subtitleTextField;
private JLabel itemDescriptionLabel;
private JButton itemDescriptionContinueButton;
private JLabel percentageLabel;
//------- price enter page ----------------
private JLabel startingPriceLabel;
private JLabel dollarSignLabel;
private JTextField startingPriceTextField;
private JPanel fillUpSpacePanel;
private JPanel fillUpSpacePanel1;
private JPanel fillUpSpacePanel2;
private JLabel buyItNowLabel;
private JPanel fillUpSpacePanel3;
private JLabel dollarSignLabel2;
private JTextField buyItNowTextField;
private JPanel fillUpSpacePanel4;
private JPanel fillUpSpacePanel5;
private JPanel fillUpSpacePanel6;
private JPanel fillUpSpacePanel7;
private JPanel fillUpSpacePanel8;
private JPanel fillUpSpacePanel9;
private JPanel fillUpSpacePanel10;
private JPanel fillUpSpacePanel11;
private JPanel fillUpSpacePanel12;
private JPanel fillUpSpacePanel13;
private JPanel fillUpSpacePanel14;
private JPanel fillUpSpacePanel15;
private JPanel fillUpSpacePanel16;
private JPanel fillUpSpacePanel17;
private JPanel fillUpSpacePanel18;
private JLabel donatePercentageLabel;
private JTextField donatePercentageTextField;
private JPanel fSp; // fill space panel
private JPanel fSp1;
private JPanel fSp2;
private JPanel fSp3;
private JPanel fSp4;
private JPanel fSp5;
private JPanel fSp6;
private JPanel fSp7;
private JPanel fSp8;
private JPanel fSp9;
private JLabel numberOfPicturesLabel;
private JTextField numberOfPicturesTextField;
private JCheckBox superSizePicturesCheckBox;
private JLabel superSizePicturesLabel;
private JRadioButton standardPictureRadioButton;
private JRadioButton picturePackRadioButton;
private JCheckBox listingDesignerCheckBox;
private ButtonGroup bgPictures;
private JCheckBox valuePackCheckBox;
private JCheckBox galleryPictureCheckBox;
private JCheckBox subtitleCheckBox;
private JCheckBox boldCheckBox;
private JCheckBox borderCheckBox;
private JCheckBox highlightCheckBox;
private JCheckBox featuredPlusCheckBox;
private JCheckBox galleryFeaturedCheckBox;
private JLabel homePageFeaturedLabel;
private JComboBox homePageFeaturedComboBox;
private JCheckBox giftCheckBox;
JScrollPane priceEnterPanelScroll;
private JButton backToRadioButton;
private JButton backToItemDescriptionButton;
private JPanel priceEnterPanel;
private final static String RADIOPANEL = "JPanel with radios";
private final static String DESCRIPTIONPANEL = "JPanel with description";
private final static String PRICEENTERPANEL = "JPanel with price entering";
private JPanel cards;
private JMenuBar menuBar;
private JMenu menuFile;
private JMenu menuEdit;
private JMenu menuProperty;
private JMenuItem menuPropertySystem;
private JMenuItem menuPropertyEditor;
private JMenuItem menuPropertyDisplay;
private JMenu menuFileNew;
private JMenuItem menuFileNewAccount;
private JMenuItem menuFileNewItem;
private JMenuItem menuFileOpen;
private JMenuItem menuFileSave;
private JMenuItem menuFileSaveAs;
private JMenuItem menuFileExit;
private JMenuItem menuEditCopy;
private JMenuItem menuEditCut;
private JMenuItem menuEditPaste;
public MainPanel()
requiredLabel = new JLabel ("* Required");
requiredLabel.setForeground (Color.red);
requiredLabel2 = new JLabel ("* Required");
requiredLabel2.setForeground (Color.red);
requiredStarLabel = new JLabel ("*");
requiredStarLabel.setForeground (Color.green);
setTitle( "photo galleries" );
setSize( 310, 130 );
topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
topPanel.setBorder (BorderFactory.createTitledBorder ("TopPanel"));
//topPanel.setPreferredSize(new Dimension (300,300));
getContentPane().add( topPanel );
topPanel.setVisible (false);
// For New Item Panel
ButtonListener ears = new ButtonListener();
blankLabel = new JLabel (" "); // used to give space between radio buttons and continue button
continueButton = new JButton ("Continue >");
continueButton.addActionListener (ears);
backToRadioButton = new JButton ("< back");
backToRadioButton.addActionListener (ears);
itemDescriptionContinueButton = new JButton ("Continue >");
itemDescriptionContinueButton.addActionListener (ears);
backToItemDescriptionButton = new JButton ("< back");
backToItemDescriptionButton.addActionListener (ears);
newItemPanel = new JPanel();
newItemPanel.setLayout (new BoxLayout(newItemPanel, BoxLayout.Y_AXIS));
//topPanel.add (newItemPanel, BorderLayout.NORTH);
newItemPanel.setBorder (BorderFactory.createTitledBorder ("NewItemPanel"));
newItemPanel.setVisible (false);
onlineAuctionRadio = new JRadioButton ("Sold item at online Auction" );
fixedPriceRadio = new JRadioButton ("Sold at a Fixed Price");
bg = new ButtonGroup();
bg.add(onlineAuctionRadio);
bg.add(fixedPriceRadio);
onlineAuctionRadio.addActionListener (ears);
fixedPriceRadio.addActionListener (ears);
newItemPanel.add (onlineAuctionRadio);
newItemPanel.add (fixedPriceRadio);
newItemPanel.add (blankLabel);
newItemPanel.add (continueButton);
// ------ After continue pressed ---------
newItemDescriptionPanel = new JPanel();
newItemDescriptionPanel.setLayout (new BoxLayout(newItemDescriptionPanel, BoxLayout.Y_AXIS));
newItemPanel.add (newItemDescriptionPanel, BorderLayout.NORTH);
newItemDescriptionPanel.setBorder (BorderFactory.createTitledBorder ("newItemDescriptionPanel"));
secondCategoryCheckBox = new JCheckBox ("The item was listed in a second category");
newItemDescriptionPanel.setVisible (false);
itemTitleLabel = new JLabel ("Item title");
itemTitleTextField = new JTextField (30);
subtitleLabel = new JLabel ("Subtitle ($0.50)");
subtitleTextField = new JTextField (30);
itemDescriptionLabel = new JLabel ("Item description");
itemDescriptionTextArea = new JEditorPane();
itemDescriptionTextArea.setContentType( "text/html" );
itemDescriptionTextArea.setEditable( false );
itemDescriptionTextArea.setPreferredSize(new Dimension (500,250));
itemDescriptionTextArea.setFont(new Font( "Serif", Font.PLAIN, 12 ));
itemDescriptionTextArea.setForeground( Color.black );
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 4;
displayScroller = new JScrollPane( itemDescriptionTextArea );
gridbag = new GridBagLayout ();
gridbag.setConstraints( displayScroller, gbc );
itemDescriptionTextArea.setEditable( true );
takeAdditionalSpacePanelCheckBox = new JPanel(new FlowLayout(FlowLayout.LEFT));
takeAdditionalSpacePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
takeAdditionalSpacePanelLabel = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
takeAdditionalSpacePanelLabel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
takeAdditionalSpacePanel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
takeAdditionalSpacePanel3 = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
takeAdditionalSpacePanel4 = new JPanel(new FlowLayout(FlowLayout.LEFT));
takeAdditionalSpacePanel5 = new JPanel(new FlowLayout(FlowLayout.LEFT));
//takeAdditionalSpacePanel2.setBorder (BorderFactory.createTitledBorder ("Additonal 2"));
takeAdditionalSpacePanelCheckBox.add (secondCategoryCheckBox);
newItemDescriptionPanel.add (takeAdditionalSpacePanelCheckBox);
//newItemDescriptionPanel.add (blankLabel);
takeAdditionalSpacePanelLabel.add (itemTitleLabel);
takeAdditionalSpacePanelLabel.add (requiredLabel);
newItemDescriptionPanel.add (takeAdditionalSpacePanelLabel);
//newItemDescriptionPanel.add (itemTitleTextField);
takeAdditionalSpacePanel.add(itemTitleTextField);//<--add textfield to panel
newItemDescriptionPanel.add (takeAdditionalSpacePanel);//<--add panel to boxlayout panel
takeAdditionalSpacePanelLabel2.add (subtitleLabel);
newItemDescriptionPanel.add (takeAdditionalSpacePanelLabel2);
takeAdditionalSpacePanel2.add (subtitleTextField);
newItemDescriptionPanel.add (takeAdditionalSpacePanel2);
takeAdditionalSpacePanel4.add (itemDescriptionLabel);
//takeAdditionalSpacePanel4.add (requiredLabel2);
newItemDescriptionPanel.add (takeAdditionalSpacePanel4);
takeAdditionalSpacePanel3.add (displayScroller);
newItemDescriptionPanel.add (takeAdditionalSpacePanel3);
takeAdditionalSpacePanel5.add (backToRadioButton);
takeAdditionalSpacePanel5.add (itemDescriptionContinueButton);
newItemDescriptionPanel.add (takeAdditionalSpacePanel5);
//newItemDescriptionPanel.setLayout (new BoxLayout(newItemDescriptionPanel, BoxLayout.Y_AXIS));
//----------- Price Enter Page ----------------
priceEnterPanel = new JPanel();
priceEnterPanel.setLayout (new BoxLayout(priceEnterPanel, BoxLayout.Y_AXIS));
newItemDescriptionPanel.add (priceEnterPanel, BorderLayout.NORTH);
priceEnterPanel.setBorder (BorderFactory.createTitledBorder ("Price enter Panel"));
priceEnterPanel.setVisible (false);
priceEnterPanelScroll = new JScrollPane (priceEnterPanel);
topPanel.add (priceEnterPanelScroll);
standardPictureRadioButton = new JRadioButton ("Standard");
picturePackRadioButton = new JRadioButton ("Picture Pack ($1.00 for up to 6 pictures or $1.50 for 7 to 12 pictures)");
bgPictures = new ButtonGroup();
bgPictures.add(standardPictureRadioButton);
bgPictures.add(picturePackRadioButton);
standardPictureRadioButton.addActionListener (ears);
picturePackRadioButton.addActionListener (ears);
superSizePicturesCheckBox = new JCheckBox ("Supersize Pictures ($0.75)");
listingDesignerCheckBox = new JCheckBox ("Listing designer $0.10");
valuePackCheckBox = new JCheckBox ("Get the Essentials for less! Gallery, Subtitle, Listing Designer. $0.65 (save $0.30)");
superSizePicturesCheckBox.setEnabled (false);
superSizePicturesCheckBox.addActionListener (ears);
listingDesignerCheckBox.addActionListener (ears);
valuePackCheckBox.addActionListener (ears);
startingPriceLabel = new JLabel ("Starting Price");
dollarSignLabel = new JLabel ("$");
startingPriceTextField = new JTextField (10);
buyItNowLabel = new JLabel ("Buy It Now");
dollarSignLabel2 = new JLabel ("$");
buyItNowTextField = new JTextField (10);
donatePercentageLabel = new JLabel ("Donate percentage of sale");
donatePercentageTextField = new JTextField (2);
donatePercentageTextField.setText ("0");
percentageLabel = new JLabel ("%");
// Right-justify the text
donatePercentageTextField.setHorizontalAlignment(JTextField.RIGHT);
numberOfPicturesLabel = new JLabel ("Number of pictures used");
numberOfPicturesTextField = new JTextField (1);
numberOfPicturesTextField.setText ("0");
galleryPictureCheckBox = new JCheckBox ("Gallery ($0.35) [Requires a picture]");
subtitleCheckBox = new JCheckBox ("Subtitle ($0.50)");
boldCheckBox = new JCheckBox ("Bold ($1.00)");
borderCheckBox = new JCheckBox ("Border ($3.00)");
highlightCheckBox = new JCheckBox ("Highlight ($5.00)");
featuredPlusCheckBox = new JCheckBox ("Featured Plus! ($19.95)");
galleryFeaturedCheckBox = new JCheckBox ("Gallery Featured ($19.95) [Requires a picture]");
homePageFeaturedLabel = new JLabel ("Home Page Featured ($39.95 for 1 item, $79.95 for 2 or more items)");
homePageFeaturedComboBox = new JComboBox ();
homePageFeaturedComboBox.addItem (("None..."));
homePageFeaturedComboBox.addItem (("1 item"));
homePageFeaturedComboBox.addItem (("2 or more items"));
giftCheckBox = new JCheckBox ("Show as a gift ($0.25)");
fillUpSpacePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel3 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel4 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel5 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel6 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel7 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel8 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel9 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel10 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel11 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel12 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel13 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel14 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel15 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel16 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel17 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel18 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp3 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp4 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp5 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp6 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp7 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp8 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp9 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel.add (startingPriceLabel);
fillUpSpacePanel.add (requiredLabel2);
priceEnterPanel.add (fillUpSpacePanel);
fillUpSpacePanel2.add (dollarSignLabel);
fillUpSpacePanel2.add (startingPriceTextField);
priceEnterPanel.add (fillUpSpacePanel2);
// fillUpSpacePanel1.add (backToItemDescriptionButton);
// priceEnterPanel.add (fillUpSpacePanel1);
fillUpSpacePanel3.add (buyItNowLabel);
priceEnterPanel.add (fillUpSpacePanel3);
fillUpSpacePanel4.add (dollarSignLabel2);
fillUpSpacePanel4.add (buyItNowTextField);
priceEnterPanel.add (fillUpSpacePanel4);
fillUpSpacePanel1.add (donatePercentageLabel);
priceEnterPanel.add (fillUpSpacePanel1);
fillUpSpacePanel5.add (donatePercentageTextField);
fillUpSpacePanel5.add (percentageLabel);
priceEnterPanel.add (fillUpSpacePanel5);
fillUpSpacePanel6.add (numberOfPicturesLabel);
priceEnterPanel.add (fillUpSpacePanel6);
fillUpSpacePanel7.add (numberOfPicturesTextField);
priceEnterPanel.add (fillUpSpacePanel7);
fillUpSpacePanel8.add (standardPictureRadioButton);
priceEnterPanel.add (fillUpSpacePanel8);
fillUpSpacePanel10.add (blankLabel);
fillUpSpacePanel10.add (superSizePicturesCheckBox);
priceEnterPanel.add (fillUpSpacePanel10);
fillUpSpacePanel9.add (picturePackRadioButton);
priceEnterPanel.add (fillUpSpacePanel10);
fillUpSpacePanel11.add (picturePackRadioButton);
priceEnterPanel.add (fillUpSpacePanel11);
fillUpSpacePanel12.add (listingDesignerCheckBox);
priceEnterPanel.add (fillUpSpacePanel12);
fillUpSpacePanel13.add (valuePackCheckBox);
priceEnterPanel.add (fillUpSpacePanel13);
fSp.add (galleryPictureCheckBox);
priceEnterPanel.add (fSp);
fSp1.add (subtitleCheckBox);
priceEnterPanel.add (fSp1);
fSp2.add (boldCheckBox);
priceEnterPanel.add (fSp2);
fSp3.add (borderCheckBox);
priceEnterPanel.add (fSp3);
fSp4.add (highlightCheckBox);
priceEnterPanel.add (fSp4);
fSp5.add (featuredPlusCheckBox);
priceEnterPanel.add (fSp5);
fSp6.add (galleryFeaturedCheckBox);
priceEnterPanel.add (fSp6);
fSp7.add (homePageFeaturedLabel);
priceEnterPanel.add (fSp7);
fSp8.add (homePageFeaturedComboBox);
priceEnterPanel.add (fSp8);
fSp9.add (giftCheckBox);
priceEnterPanel.add (fSp9);
newItemDescriptionPanel.add (priceEnterPanelScroll);
//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(newItemPanel, RADIOPANEL);
cards.add(newItemDescriptionPanel, DESCRIPTIONPANEL);
cards.add(priceEnterPanel, PRICEENTERPANEL);
topPanel.add(cards, BorderLayout.NORTH);
// Create the menu bar
menuBar = new JMenuBar();
// Set this instance as the application's menu bar
setJMenuBar( menuBar );
// Build the property sub-menu
menuProperty = new JMenu( "Properties" );
menuProperty.setMnemonic( 'P' );
// Create property items
menuPropertySystem = CreateMenuItem( menuProperty, ITEM_PLAIN,
"System...", null, 'S', null );
menuPropertyEditor = CreateMenuItem( menuProperty, ITEM_PLAIN,
"Editor...", null, 'E', null );
menuPropertyDisplay = CreateMenuItem( menuProperty, ITEM_PLAIN,
"Display...", null, 'D', null );
//Build the File-New sub-menu
menuFileNew = new JMenu ("New");
menuFileNew.setMnemonic ('N');
//Create File-New items
menuFileNewItem = CreateMenuItem( menuFileNew, ITEM_PLAIN,
"Item", null, 'A', null );
menuFileNewAccount = CreateMenuItem( menuFileNew, ITEM_PLAIN,
"Account", null, 'A', null );
// Create the file menu
menuFile = new JMenu( "File" );
menuFile.setMnemonic( 'F' );
menuBar.add( menuFile );
//Add the File-New menu
menuFile.add( menuFileNew );
// Create the file menu
// Build a file menu items
menuFileOpen = CreateMenuItem( menuFile, ITEM_PLAIN, "Open...",
new ImageIcon( "open.gif" ), 'O',
"Open a new file" );
menuFileSave = CreateMenuItem( menuFile, ITEM_PLAIN, "Save",
new ImageIcon( "save.gif" ), 'S',
" Save this file" );
menuFileSaveAs = CreateMenuItem( menuFile, ITEM_PLAIN,
"Save As...", null, 'A',
"Save this data to a new file" );
// Add the property menu
menuFile.addSeparator();
menuFile.add( menuProperty );
menuFile.addSeparator();
menuFileExit = CreateMenuItem( menuFile, ITEM_PLAIN,
"Exit", null, 'X',
"Exit the program" );
//menuFileExit.addActionListener(this);
// Create the file menu
menuEdit = new JMenu( "Edit" );
menuEdit.setMnemonic( 'E' );
menuBar.add( menuEdit );
// Create edit menu options
menuEditCut = CreateMenuItem( menuEdit, ITEM_PLAIN,
"Cut", null, 'T',
"Cut data to the clipboard" );
menuEditCopy = CreateMenuItem( menuEdit, ITEM_PLAIN,
"Copy", null, 'C',
"Copy data to the clipboard" );
menuEditPaste = CreateMenuItem( menuEdit, ITEM_PLAIN,
"Paste", null, 'P',
"Paste data from the clipboard" );
public JMenuItem CreateMenuItem( JMenu menu, int iType, String sText,
ImageIcon image, int acceleratorKey,
String sToolTip )
// Create the item
JMenuItem menuItem;
switch( iType )
case ITEM_RADIO:
menuItem = new JRadioButtonMenuItem();
break;
case ITEM_CHECK:
menuItem = new JCheckBoxMenuItem();
break;
default:
menuItem = new JMenuItem();
break;
// Add the item test
menuItem.setText( sText );
// Add the optional icon
if( image != null )
menuItem.setIcon( image );
// Add the accelerator key
if( acceleratorKey > 0 )
menuItem.setMnemonic( acceleratorKey );
// Add the optional tool tip text
if( sToolTip != null )
menuItem.setToolTipText( sToolTip );
// Add an action handler to this menu item
menuItem.addActionListener( this );
menu.add( menuItem );
return menuItem;
public void actionPerformed( ActionEvent event )
CardLayout cl = (CardLayout)(cards.getLayout());
if (event.getSource() == menuFileExit)
System.exit(0);
if (event.getSource() == menuFileNewAccount)
System.out.println ("hlkadflkajfalkdjfalksfj");
if (event.getSource() == menuFileNewItem){
if (firstRun){
newItemPanel.setVisible (true);
topPanel.setVisible (true);
cl.show(cards,RADIOPANEL);
firstRun = false;
//System.out.println( event );
private class ButtonListener implements ActionListener
public void actionPerformed(ActionEvent event)
CardLayout cl = (CardLayout)(cards.getLayout());
// cl.show(cards, (String)evt.getItem());
if (event.getSource() == continueButton){
if (!(onlineAuctionRadio.isSelected()) && !(fixedPriceRadio.isSelected()))
JOptionPane.showMessageDialog(null, "You must select at least one.", "Error", JOptionPane.ERROR_MESSAGE);
else{
if (onlineAuctionRadio.isSelected()){
cl.show (cards, DESCRIPTIONPANEL);
//newItemPanel.setVisible (false);
//newItemDescriptionPanel.setVisible (true);
if (event.getSource() == itemDescriptionContinueButton){
if (itemTitleTextField.getText().trim().equalsIgnoreCase(""))
JOptionPane.showMessageDialog(null, "You must enter a title.", "Error", JOptionPane.ERROR_MESSAGE);
else
cl.show (cards, PRICEENTERPANEL);
if (event.getSource() == backToRadioButton){
cl.show (cards, RADIOPANEL);
if (event.getSource() == backToItemDescriptionButton){
cl.show(cards, DESCRIPTIONPANEL);
if (standardPictureRadioButton.isSelected()){
superSizePicturesCheckBox.setEnabled (true);
if (picturePackRadioButton.isSelected()){
superSizePicturesCheckBox.setEnabled (false);
} //end of action performed
}Mostly I see there is about 100 times as much code as I care to look at.
So you don't know how to get a panel in a scroll pane, and then get that scroll pane into your GUI? Then try doing that by itself, not encumbered with 10000 lines of irrelevant code. Once you have it working, plug it into the big lump of code. Or if you can't get it working, ask about the small problem here. -
Scroll Bar code in Awt Required Plz Help me
Hi,
My requirment is to add Vertical Scrollbar to the table.There are 12 rows in a table like from January to December.
I am able to see data of rows as jan,feb,mar,apr only .
i want to see the data of rows of next months by adding vertical scroll bar using Awt code.
I added vertical scroll bar using awt code. When i click on that Vertical scroll bar event is going to below method.
public void adjustmentValueChanged(AdjustmentEvent e) {
I tried with some logic inside above method but it is not working.what is the code i have to write inside the above method inorder to scroll the next months.
Plz Help me.
Thanks In Advance.........But i want to do this code In Using Awt only......Well, a JTable is a Swing component so I have no idea what you are talking about.
To control the size of the table you can use:
table.setPreferredScrollableViewportSize(???);
JScrollPane scrollPane = new JScrollPane( table ); -
Double Scroll Bars, Side By Side, End To End, In A JScrollPane
I'm trying to create double scroll bars next to each other, end to end. One scroll bar is for the position in the grid, while the other, smaller scroll bar controls the zoom level. I am masquerading a JPanel as a JScrollBar. I'm adding two scroll bars to the panel, and encapsulating the panel in a subclass of JScrollBar. You might wonder why I would do that. Because JScrollPane only accepts JScrollBar classes in setHorizontalScrollBar() and setVerticalScrollBar(). I tried to override every painting method I could think of that was important, but when I test it, nothing is shown. It is completely blank. Here is the code below. I know I still have to override the general JScrollBar methods and pass them to the primary scrollbar. Does anyone have any ideas on how to do somethink like I am attempting to do?
import java.awt.*;
import javax.swing.*;
import java.lang.reflect.*;
* <p>Title: </p>
* <p>Description: This class masquerades as a JScrollBar, but it wraps two scrollbars next to each other. The
* main scrollbar, and the secondary scrollbar which is smaller. Any calls which treat this as a regular scrollbar
* will return the main scrollbar's values, while the special methods can be used to return the seondary scrollbar's
* values.
* </p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
public class DoubleScrollBar extends JScrollBar {
JPanel panel = new JPanel();
JScrollBar primary;
JScrollBar secondary;
public DoubleScrollBar(int orientation) {
init(orientation);
void init() {
panel.setLayout(new GridBagLayout());
if ( orientation == JScrollBar.HORIZONTAL ) {
primary = new JScrollBar(JScrollBar.HORIZONTAL);
secondary = new JScrollBar(JScrollBar.HORIZONTAL);
GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 0.75, 0.0,
GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0);
panel.add(primary, gbc);
gbc.gridx = 1;
gbc.weightx = 0.25;
gbc.anchor = GridBagConstraints.EAST;
panel.add(secondary, gbc);
} else if ( orientation == JScrollBar.VERTICAL ) {
primary = new JScrollBar(JScrollBar.VERTICAL);
secondary = new JScrollBar(JScrollBar.VERTICAL);
GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 0.0, 0.75,
GridBagConstraints.NORTH, GridBagConstraints.VERTICAL, new Insets(0, 0, 0, 0), 0, 0);
panel.add(primary, gbc);
gbc.gridy = 1;
gbc.weighty = 0.25;
gbc.anchor = GridBagConstraints.SOUTH;
panel.add(secondary, gbc);
public Dimension getPreferredSize() {
return panel.getPreferredSize();
public void setPreferredSize(Dimension d) {
panel.setPreferredSize(d);
public Dimension getSize() {
return panel.getSize();
public void paint(Graphics g) {
panel.paint(g);
public void paintAll(Graphics g) {
panel.paintAll(g);
protected void paintComponent(Graphics g) {
try {
Method m = panel.getClass().getMethod("paintComponent", new Class[] {Graphics.class});
m.invoke(panel, new Object[] {g});
catch (SecurityException ex) {
System.out.println("SecurityException");
catch (NoSuchMethodException ex) {
System.out.println("NoSuchMethodException");
catch (InvocationTargetException ex1) {
System.out.println("InvocationTargetException");
catch (IllegalArgumentException ex1) {
System.out.println("IllegalArgumentException");
catch (IllegalAccessException ex1) {
System.out.println("IllegalAccessException");
public void paintComponents(Graphics g) {
panel.paintComponents(g);
public void repaint(long tm, int x, int y, int w, int h) {
if ( panel != null ) {
panel.repaint(tm, x, y, w, h);
public int getWidth() {
return panel.getWidth();
public int getHeight() {
return panel.getHeight();
public static void main(String[] args) {
JFrame f = new JFrame();
DoubleScrollBar dsb = new DoubleScrollBar(JScrollBar.HORIZONTAL);
dsb.setPreferredSize(new Dimension(200, 50));
f.getContentPane().add(dsb);
f.pack();
f.show();I know this isn't zooming, but maybe it will help.import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test3 extends JFrame {
MyPanel mp = new MyPanel();
public Test3() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = getContentPane();
JScrollBar jsb = new JScrollBar();
jsb.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent ae) {
mp.setSize(ae.getValue()*5);
content.add(jsb, BorderLayout.EAST);
mp.setPreferredSize(new Dimension(500,500));
content.add(new JScrollPane(mp), BorderLayout.CENTER);
setSize(300, 300);
public static void main(String[] args) { new Test3().setVisible(true); }
class MyPanel extends JPanel {
int size;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.drawRect(10,10,size,size);
public void setSize(int size) {
this.size=size;
repaint();
} -
JScrollPane: Can the Vertical Scroll Bar go on the left?
Hope you can help,
Im using a JScrollPane within another one, i.e, I have a component inside a JScrollPane, and one of its components is a JScrollPane. This is fine and dandy, but the internal scrolled component gets pretty tall and wide, so people end up using the OUTER horizontal scroll bar to scroll to the INNER vertical scrollbar to scroll DOWN the inner component.
What would be really nice would be to have the INNER scrolled component to have its scroll bar on the LEFT to save the above hassle.
Is this possible with JScrolledPane?In JScrollPane (jdk1.3)
public void setComponentOrientation(ComponentOrientation co)
Sets the orientation for the vertical and horizontal scrollbars as determined by the ComponentOrientation argument.
Parameters:
co - one of the following values:
java.awt.ComponentOrientation.LEFT_TO_RIGHT
java.awt.ComponentOrientation.RIGHT_TO_LEFT
java.awt.ComponentOrientation.UNKNOWN -
Keep vertical scroll bar still y JScrollPane
Hello all!
I have got a JTable added into a JScrollPane, which scroll bars are always shown.
I have to repaint the JTable each 3 seconds and I would like to keep the vertical scroll bar in its original position, for example if I am watching row 24 of the JTable when the JTable is repainted I would like the vertical scroll bar to be in the same position as it was before repainting because now the vertical scroll bar is repainted always at the top...
With the horizontal bar it works, the bar does not move from its previous state when the JTable is repainted...
Any idea of what is happening?
Thanks in advance :)This would do for u! ... do it after you have updated the table with the new rows... if you are not using the default table model then you can still get the row count through your JTable object ...
This part moves the scrollbar to the last row coz im doing "myDefaultTableModel.getRowCount()-1", you can keep the current row index in an instance level variable bjust before refreshing the table and use it in this.setRowSelectionInterval() method ...
this.setRowSelectionInterval(myDefaultTableModel.getRowCount()-1, myDefaultTableModel.getRowCount()-1);
this.setColumnSelectionInterval(1, 1); //didnt need any specific column coz I wanted the row basically..
this.scrollRectToVisible(this.getCellRect(this.getSelectedRow(), 1, true));This basically selects the given row and then moved the scrollbar over to that point as well ...
OR, here's another alternative!! you can also get the current scrollbar value similarly jsut before refreshing and pass that on to this method ...
this.jScrollPane1.getVerticalScrollBar().setValue(jScrollPane1.getVerticalScrollBar().getValue());Hope it helps...
Cheers!
Asim -
JList in JScrollPane never shows horizontal scroll bar
I have a JList inside a JScrollPane. When I add a lot of cells to the list, the vertical scroll bar appears as expected. However, if I add a cell that would require lots of horizontal space in which to render, the horizontal scroll bar never appears.
Is there a way to make the JList take on the width of the widest rendered cell?
JoshHere's some code that will demonstrate the problem. Run the code, then resize the window so that the horizontal scroll bar should appear.
Code for jds.toys.Main:
package jds.toys;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class Main extends JFrame {
protected DefaultListModel model;
public Main()
super("JList in JScrollPane");
model = new DefaultListModel();
model.addElement("A very very very very very very long String");
model.addElement("A very very very very very very very long String");
model.addElement("A very very very very very very very very long String");
model.addElement("A very very very very very very very very very long String");
model.addElement("A very very very very very very very very very very long String");
model.addElement("A very very very very very very very very very very very long String");
JList list = new JList(model);
list.setSize(300,300);
list.setFixedCellHeight(30);
list.setCellRenderer(new MyCellRenderer());
JScrollPane scrollPane = new JScrollPane(list);
add(scrollPane);
setSize(400,400);
public static void main(String[] args) throws InterruptedException {
final Main m = new Main();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
m.setVisible(true);
Code for jds.toys.MyCellRenderer:
package jds.toys;
import java.awt.Component;
import java.awt.Graphics;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
public class MyCellRenderer extends JPanel implements ListCellRenderer
private Object currentValue;
private JList currentList;
public MyCellRenderer()
public Component getListCellRendererComponent( JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
currentValue = value;
currentList = list;
return this;
public void paintComponent(Graphics g)
int stringLen = g.getFontMetrics().stringWidth(currentValue.toString());
int ht = currentList.getFixedCellHeight();
g.setColor(getBackground());
g.fillRect(0,0,stringLen,ht);
g.setColor(getForeground());
g.drawString(currentValue.toString(),0,ht/2);
}
Maybe you are looking for
-
How can I get my iPod touch to download and install updates to apps?
I am having difficulties with getting updates for my apps to download and install. When requested, I supply my password for my apple ID, and select "update". It immediately jumps to the screen with my icon, and then gives me a status bar and says "
-
Msql error when connect to webtogo.world
Every time I run msql system/<password>@webtogo.world I get a No suitable Driver error. The Oracle DB is a in a different server and Mobile Server and the Mobile Kt are in a development machine. I can see the polite db with no problem using msql syst
-
my iPhone 5 randomly switched itself when somebody was calling me and now won't turn on. it had 90% battery, I've tried factory reset, connecting to iTunes and nothing works. the phone is approx 18 months old so surprise surprise out of warranty.
-
Hi All, Did any one use the 'Customized Bar Code Scanning for one-shot scan of multi-fields? Can I populate any field in mobile screen by using the 'Customized Bar Code Scanning and Java Call Out? Best Regards, Ami Ben-Dror. [email protected]
-
Photo does not fit in the screen
I watched that video http://www.youtube.com/watch?v=KJMi5l9Ru-g and tried this to do the parallax scrolling with the image this on my page. Unfortunately, my photo does not fit in the whle screen, even if I take a . jpg image 3000 px wide. ( loo