JScrollPane with scroll arrows but no scrollbar - java

I want to create scrollpane like on this picture:
With arrows on component sides and with no scrollbar visible. Only horizontal scrolling is needed. Can It be done with JScrollPane?

You can make you own component by using a scrollpane and by creating your own buttons that will use the Actions of the scrollbar:
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
public class ScrollPaneSSCCE extends JPanel
{
public ScrollPaneSSCCE()
{
setLayout( new BorderLayout() );
JTextArea textArea = new JTextArea(1, 80);
textArea.setText("Hopefully this will answer your question");
JScrollPane scrollPane = new JScrollPane( textArea );
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
add(scrollPane);
JScrollBar horizontal = scrollPane.getHorizontalScrollBar();
BasicArrowButton west = new BasicArrowButton(BasicArrowButton.WEST);
west.setAction( new ActionMapAction("", horizontal, "negativeUnitIncrement") );
add(west, BorderLayout.WEST);
BasicArrowButton east = new BasicArrowButton(BasicArrowButton.EAST);
east.setAction( new ActionMapAction("", horizontal, "positiveUnitIncrement") );
add(east, BorderLayout.EAST);
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("ScrollPaneSSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ScrollPaneSSCCE(), BorderLayout.NORTH);
frame.setSize(100, 100);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
You will also need to use the Action Map Action class.

Related

How to start something on a new line in Java SWING?

I am trying to set my JTextArea to take up the max horz length of the screen, so that the next thing, in this case a button, will start on a new line, but I have no clue how to do it. I have messed around by setting the size of the JTextArea to change from, say, 20 to 1000 but that does not do anything.
How can I get my textarea to take up the entire first row and then have the next item that I add to begin on the following row? Here is what I have so far...
MyFrame(){//constructor
super("Simple Calculator");
p = new JPanel();
grid = new GridLayout(4, 4, 3, 3);
p.setLayout(grid);
setSize(400, 500);
setResizable(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setUpTextScreen();
//create buttons
for(int i = 0; i < buttonValues.length; i++){
p.add(new JButton(buttonValues[i]));
}
add(p);
setVisible(true);
}
private void setUpTextScreen() {
textOnScreen = new JTextArea(7, 1000);
textOnScreen.setText("0");//default
textOnScreen.setEditable(false);
p.add(textOnScreen);
}
How can I get my textarea to take up the entire first row and then have the next item that I add to begin on the following row?
Break your layout up into logical pieces. Start with your main panel using a BorderLayout.
First I would use a JTextField for the calculator display, not a JTextArea. Then you can add the text field using: mainPanel.add(textField, BorderLayout.PAGE_START);
Then you create a JPanel using a GridLayout for the buttons. Then you add the buttons to the button panel and use: maonPanel.add(buttonPanel, BorderLayout.CENTER);
For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CalculatorPanel extends JPanel
{
private JTextField display;
public CalculatorPanel()
{
Action numberAction = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
// display.setCaretPosition( display.getDocument().getLength() );
display.replaceSelection(e.getActionCommand());
}
};
setLayout( new BorderLayout() );
display = new JTextField();
display.setEditable( false );
display.setHorizontalAlignment(JTextField.RIGHT);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setBorder( new LineBorder(Color.BLACK) );
button.setPreferredSize( new Dimension(30, 30) );
buttonPanel.add( button );
InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(KeyStroke.getKeyStroke(text), text);
inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
button.getActionMap().put(text, numberAction);
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Calculator Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new CalculatorPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
Hava a look at Nested layouts, you can add one panel with a BorderLayout (there are other options too though) and add the textarea to it. Then you only need one more panel with a GridLayout that displays the buttons. This is an example: (Note that a few lines are unnecessary in this code, but they help understand layouts)
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.LineBorder;
public class Example extends JFrame {
Example() {//
super("Simple Calculator");
// The Main Panel where the 2 other panels will be on
JPanel mainPanel = new JPanel(new BorderLayout());
// The textarea will be inside this panel
JPanel areaPanel = new JPanel(new BorderLayout());
JTextArea area = new JTextArea(
"This is a JTextArea -Long text to show it works -Long text to show it works- -Long text to show it works- -Long text to show it works- -Long text to show it works- -Long text to show it works-");
area.setBorder(new LineBorder(Color.BLACK));
area.setWrapStyleWord(true);
area.setLineWrap(true);
// Fill the whole space of the panel with the area
areaPanel.add(area, BorderLayout.CENTER);
// The buttons will be inside this panel
JPanel buttonPanel = new JPanel(new GridLayout(4, 4, 3, 3));
for (int i = 0; i < 16; i++) { // Adding buttons
buttonPanel.add(new JButton("Button" + i));
}
// The textarea-panel should be on top of the main panel
mainPanel.add(areaPanel, BorderLayout.NORTH);
// The panel with the buttons should fill the remaining space
mainPanel.add(buttonPanel, BorderLayout.CENTER);
getContentPane().add(mainPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setVisible(true);
}
public static void main(String[] args) {
new Example();
}
}
You can also use html tags like:
JButton button = new JButton("<html><b><u>T</u>wo</b><br>lines</html>");
Or in any other JComponent like you got.
So you can use <BR> tag you achieve your need.

JButtons in JPanel in another JPanel

Is it possible to add a JPanel with JButtons to a Split JPanel? Right now, I have the JPanel with JButtons added to a JFrame, but I want it on a JPanel with other JPanels. When I attempt to do this, I get a completely blank JPanel with dividers.
______________________________________________________________________________
public class Panel extends JPanel implements Runnable, ActionListener {
public Panel(){
JFrame frame = new JFrame();
ctsMenu = new JPanel(new GridLayout(2,2));
ctsMenu.setPreferredSize(new Dimension(500,500));
for (int iRows = 0; iRows < 2 ; iRows++){
for (int iColumns = 0; iColumns < 2; iColumns++){
sGrid[iRows][iColumns] = new JButton ("("+iRows+","+iColumns+")");
ctsMenu.add(sGrid[iRows][iColumns]);
sGrid[iRows][iColumns].addActionListener(this);
panel.add(ctsMenu);
}
}
sGrid[0][0].setText("A");
sGrid[0][1].setText("B");
sGrid[1][0].setText("C");
sGrid[1][1].setText("D");
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}}
____________________________________________________________________
public MainFrame()
{
setTitle( "Split Pane Application" );
setBackground( Color.GREEN );
JPanel topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
createPanel1();
createPanel2();
createPanel3();
createPanel4();
splitPaneV = new JSplitPane( JSplitPane.VERTICAL_SPLIT );
topPanel.add( splitPaneV, BorderLayout.CENTER );
splitPaneV.setDividerLocation(300);
splitPaneV.setLeftComponent( gamePanel);
// gamePanel.addKeyListener(new KeyListener());
gamePanel.setFocusable(true);
gamePanel.requestFocusInWindow();
splitPaneV.setRightComponent( panel3 );
}
}
public void createPanel1(){
// deleted to take up less space
}
public void createPanel2(){
// deleted to take up less space
}
public void createPanel3(){
panel3 = new Panel();
}
public void createPanel4(){
//deleted to take up less space
}
}
You ask:
Is it possible to add a JPanel with JButtons to a Split JPanel?
Yes, it is most definitely possible to do this. It's something similar to what we do all the time:
import javax.swing.*;
public class SplitPaneEg {
private static void createAndShowGui() {
JPanel panel1 = new JPanel();
panel1.setBorder(BorderFactory.createTitledBorder("Panel 1"));
panel1.add(new JButton("Button 1"));
panel1.add(new JButton("Button 2"));
JPanel panel2 = new JPanel();
panel2.setBorder(BorderFactory.createTitledBorder("Panel 2"));
panel2.add(new JButton("Button 1"));
panel2.add(new JButton("Button 2"));
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, panel1,
panel2);
JFrame frame = new JFrame("Split Pane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(splitPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
You state:
Right now, I have the JPanel with JButtons added to a JFrame, but I want it on a JPanel with other JPanels. When I attempt to do this, I get a completely blank JPanel with dividers.
Then you have an error in your code, but unfortunately based on code you've posted I doubt that any of us can do more than just guess. If you need more specific help, then you will want to post a small runnable example that demonstrates your problem, an sscce.

JScrollPane won't work

Hey guys I wanted to create a JScrollPane but it won't work... and I don't know why... here's my code...
public class test extends JFrame{
public test(){
setSize(1000,600);
}
private static JButton[] remove;
private static JPanel p = new JPanel();
public static void main(String[]args){
p.setLayout(null);
JFrame t=new test();
remove = new JButton[25];
for(int i=0;i<25;i++){
remove[i]=new JButton("Remove");
remove[i].setBounds(243,92+35*i,85,25);
p.add(remove[i]);
}
JScrollPane scrollPane = new JScrollPane(p);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
t.add(scrollPane);
t.setVisible(true);
}
Umm and Im pretty sure the frame isn't big enough for these 25 buttons... But if i delete that p.setLayout(null); A horizontal scroll bar will be created automatically... I don't really know what is wrong with my code... Pls help thank you very much!
You need to set p's preferredSize for this to work.
p.setPreferredSize(new Dimension(800, 2000));
Or you could have p extend JPanel and then override the getPreferredSize() method to return the proper dimension.
And I agree -- get rid of your null layouts. Learn about and use the layout managers if you want to use Swing correctly and have robust Swing GUI's.
e.g.,
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Foo extends JFrame {
private static final int BUTTON_COUNT = 25;
public static void main(String[] args) {
JPanel btnPanel = new JPanel(new GridLayout(0, 1, 0, 20));
btnPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
AbstractAction removeAction = new AbstractAction("Remove") {
#Override
public void actionPerformed(ActionEvent evt) {
JButton src = (JButton) evt.getSource();
JPanel container = (JPanel) src.getParent();
container.remove(src);
container.revalidate();
container.repaint();
}
};
for (int i = 0; i < BUTTON_COUNT; i++) {
JButton removeBtn = new JButton(removeAction);
btnPanel.add(removeBtn);
}
JPanel borderPanel = new JPanel(new BorderLayout());
borderPanel.add(btnPanel, BorderLayout.NORTH);
JScrollPane scrollpane = new JScrollPane(borderPanel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollpane.setPreferredSize(new Dimension(400, 800));
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(scrollpane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
The issue is that a scroll pane checks the component inside it for a "preferred size" so a pane with a null layout has a preferred size of (0,0). Which it ignores.
You should do something along the lines of:
p.setPreferredSize(1000,600);
And you should see some scroll bars appear, I'm not sure how accurate they will be though.

Make a JtextPane looks like eBook

I have a text editor with Netbeans where i load a text to a JtextPane. If text is too big u can read it with the help of an horizontal scroll.Is there any way to split the text into pages of 24 lines for example so that every page is visible without scrolling and use a next page button for changing page (like eBooks do)?
It is easier to use a JTextArea to do this because you can easily specify the number of lines to display each time you scroll to a new page.
The basic solution is to add a text area to a scroll pane than then hide the scrollbars. You can then use the defaults Actions of the vertical scrollbar to do the scrolling for you. The code below uses code from the Action Map Action blog entry to easily create an Action that you can add to a JButton:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class TextAreaScroll extends JPanel
{
private JTextArea textArea;
public TextAreaScroll()
{
setLayout( new BorderLayout() );
textArea = new JTextArea(10, 80);
textArea.setEditable( false );
JScrollPane scrollPane = new JScrollPane( textArea );
scrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_NEVER );
add(scrollPane);
JButton load = new JButton("Load TextAreaScroll.java");
load.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileReader reader = new FileReader( "TextAreaScroll.java" );
BufferedReader br = new BufferedReader(reader);
textArea.read( br, null );
br.close();
}
catch(Exception e2) { System.out.println(e2); }
}
});
add(load, BorderLayout.NORTH);
// Add buttons to do the scrolling
JScrollBar vertical = scrollPane.getVerticalScrollBar();
Action nextPage = new ActionMapAction("Next Page", vertical, "positiveBlockIncrement");
nextPage.putValue(AbstractAction.MNEMONIC_KEY, KeyEvent.VK_N);
JButton nextButton = new JButton(nextPage);
Action previousPage = new ActionMapAction("Previous Page", vertical, "negativeBlockIncrement");
previousPage.putValue(AbstractAction.MNEMONIC_KEY, KeyEvent.VK_N);
JButton previousButton = new JButton(previousPage);
JPanel south = new JPanel();
add(south, BorderLayout.SOUTH);
south.add( previousButton );
south.add( nextButton );
}
private static void createAndShowUI()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TextAreaScroll());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

Update JscrollBar without resetting position

I have a class which extends JScrollPane, its viewport is another class which extends JComponent and implements Scrollable. When the size of the component changes the JscrollBars do not update unless I call revalidate() however this resets the position of the scroll bars to the top left. Is there a way of updating the size of the scroll bars while maintaining their current position?
Thanks, Rob
Is the problem your custom scroll pane or your custom component? We can't begin to guess what kind of changes you may have made. Post your SSCCE that demonstrates the problem.
It works fine for me.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ScrollSSCCE extends JPanel
{
public ScrollSSCCE()
{
setLayout( new BorderLayout() );
final JPanel panel = new JPanel();
panel.setPreferredSize( new Dimension(200, 200) );
JScrollPane scrollPane = new JScrollPane( panel );
add( scrollPane );
JButton button = new JButton("Adjust");
add(button, BorderLayout.SOUTH);
button.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Dimension d = panel.getPreferredSize();
d.width +=50;
d.height +=50;
panel.setPreferredSize(d);
panel.revalidate();
}
});
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("ScrollSSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new ScrollSSCCE() );
frame.setSize(150, 150);
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

Categories