JScrollBar visible - java

Is there some way to know if a JScrollBar is visible or not inside a JPanel?
I mean, some times, my panel has many rectangles (think of it as buttons) and needs a scrollbar and some times it doesn't need it. I'd like to know if I can know when it is being shown.

If you extend the JPanel and add yourself the JScrollbars (horizontal and/or vertical), then you can control when they must be visible or invisible
(you can check if they are currently visible with the isvisible() function)
You can find two example of such classes that determine the need for visible scrollbar depending on their content:
JGraphPanel (its callback actionPerformed(Event e) will adjust the visibility based on a zoom factor)
Plane (its function adjustComponents() will call setVisible() on the JScrollBar if needed)

Assuming you have a reference to a JScrollPane, you should be able to just call
yourJScrollPane.getHorizontalScrollBar().isVisible()
or
yourJScrollPane.getVerticalScrollBar().isVisible()

If you need also to be notified about visibility changes than you can use a code as follows:
final JScrollPane scroll = new JScrollPane(createMyPanel());
scroll.getVerticalScrollBar().addHierarchyListener(new HierarchyListener() {
#Override
public void hierarchyChanged(HierarchyEvent e) {
if (e.getID() == HierarchyEvent.HIERARCHY_CHANGED &&
(e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0) {
System.out.println(scroll.getVerticalScrollBar().isVisible());
}
}
});

Further to the answers by VonC and Joshua, it's worth noting that isVisible() is a method on the super class Component. Also, the javadoc states:
Determines whether this component should be visible when its parent is visible.
Components are initially visible, with the exception of top level components such as Frame objects.
What this means is that until the JScrollPane is added to a sized frame, calling isVisible() on the JScrollBar will always return true.
Consider the following SSCCE:
public static void main(String[] args) {
// creates a small table in a larger scroll pane
int size = 5;
JTable table = new JTable(makeData(size), makeHeadings(size));
JScrollPane pane = new JScrollPane(table);
pane.setPreferredSize(new Dimension(200, 200));
System.out.println(pane.getVerticalScrollBar().isVisible()); // prints true
JFrame frame = new JFrame("JScrollPane Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(pane);
System.out.println(pane.getVerticalScrollBar().isVisible()); // prints true
frame.pack();
System.out.println(pane.getVerticalScrollBar().isVisible()); // prints false
frame.setVisible(true);
System.out.println(pane.getVerticalScrollBar().isVisible()); // prints false
}
private static Object[] makeHeadings(int size) {
Object[] headings = new Object[size];
for (int i=0; i<size; i++){
headings[i] = i;
}
return headings;
}
private static Object[][] makeData(int size) {
Object[][] data = new Object[size][size];
for (int i=0; i<size; i++){
for (int j=0; j<size; j++){
data[i][j] = i*j;
}
}
return data;
}
Similarly, it's worth adding that if you're adding the JScrollPane to an internal frame, then scrollBar.isVisible() will only work once the internal frame has been added to another component.

Related

How to arrange JComboBox item

I have a JComboBox contain 9 image items. How can I arrange them to 3*3?
I want my items arrange like this
I've tried google it for several days, but I don't know what is the keyword for this question. Any advice is appreciated. Thanks for reading my question.
Edit:
Thanks for everyone's feedback.
I am making a map editor where I can put map element together.
The editor.
It is more intuitive to arrange the stone road 3*3. The user can easily know which elements match each other.
I am not necessarily using combo box. I've also consider using buttons, but I think that buttons will waste a lat of space. Because I will have more map elements in the future.
The popup for the combo box uses a JList component to display the items.
You can access and change the orientation of the JList to wrap items:
Object child = comboBox.getAccessibleContext().getAccessibleChild(0);
BasicComboPopup popup = (BasicComboPopup)child;
JList list = popup.getList();
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(3);
This will allow you to navigate through the items using the up/down keys.
To support navigation using the left/right keys you need to add additional Key Bindings to the combo box:
InputMap im = comboBox.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
im.put(KeyStroke.getKeyStroke("LEFT"), "selectPrevious");
im.put(KeyStroke.getKeyStroke("RIGHT"), "selectNext");
However, the popup is based on the width of the largest item added to the combo box. This will be a problem as you won't see all the items. The items will scroll as you use the keys to navigate, but you won't see all 9 items at one time.
To solve this problem you check out Combo Box Popup. It has features that allow you to control the size/behaviour of the popup. You would use:
BoundsPopupMenuListener listener = new BoundsPopupMenuListener(true, false);
comboBox.addPopupMenuListener( listener );
It is possible to do this by giving the JComboBox a custom UI. However that UI is, at least in my case, a mess, so only use it as a workaround and clearly mark it as such with inline documentation.
The following code is made for the default Swing Look and Feel (Metal). If you want to use another L&F you need to exchange the class the custom UI is extending and maybe do some other adjustements. This will get tricky for distribution specific L&F (may force you to use reflection and delegation).
(If you also want to center your images, see this answer.)
Code:
(Sorry for the wierd comment wrapping, don't know whats wrong with my eclipse.)
To set the UI:
comboBox.setUI(new WrapComboBoxUI(3)); // 3 columns
Source code of WrapComboBoxUI:
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.ComboPopup;
import javax.swing.plaf.metal.MetalComboBoxUI;
public class WrapComboBoxUI extends MetalComboBoxUI {
private int columnCount;
public WrapComboBoxUI() {
this(0);
}
/**
* #param columnCount
* the amount of items to render on one row. <br/>
* A value of 0 or less will cause the UI to fit as many items
* into one row as possible.
*/
public WrapComboBoxUI(int columnCount) {
this.columnCount = columnCount;
}
public static ComponentUI createUI(JComponent c) {
return new WrapComboBoxUI();
}
#Override
protected ComboPopup createPopup() {
ComboPopup created = super.createPopup();
try {
if (created instanceof JPopupMenu) {
JPopupMenu popup = (JPopupMenu) created;
JScrollPane scroll = (JScrollPane) popup.getComponent(0);
JList<?> elementList = (JList<?>) scroll.getViewport().getView();
elementList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
elementList.setVisibleRowCount(-1);
new Thread() {
#Override
public void run() {
while (true) {
try {
int fixedWidth = -1;
if (columnCount > 0) {
int width = elementList.getWidth() - elementList.getInsets().left - elementList.getInsets().right;
fixedWidth = width / columnCount;
}
boolean changed = false;
if (fixedWidth < 0 && elementList.getFixedCellWidth() >= 0 || fixedWidth >= 0 && elementList.getFixedCellWidth() < 0) {
// if changed from not fixed to fixed or
// other way around
changed = true;
} else if (fixedWidth > 0 && fixedWidth - elementList.getFixedCellWidth() > 1) {
// if width itself changed, ignoring slight
// changes
changed = true;
}
final int width = fixedWidth;
// no need to loop again before this is done, so
// we wait
if (changed)
SwingUtilities.invokeAndWait(() -> elementList.setFixedCellWidth(width));
sleep(100);
} catch (Throwable e) {
// ignored
}
}
};
}.start();
}
} catch (Throwable e) {
System.err.println("Failed to customize ComboBoxUI:");
e.printStackTrace();
}
return created;
}
}

Jtable dynamical fixed columns problems

I created a class that can dynamically to lock and unlock columns .
In my program i create two tables with the same tablemodel.
One is in the Jviewport of the scrollpane, the other in the RowHeaderView.
The problem is when you unlock all the locked columns
and you want to start to lock again, doesn't work. There are no errors but it's like the event doesn't answer.
Steps to produce the problem:
Try the code,
put all the columns in the fixed table,
then unlock with right double click,
then start again to lock, and unlock
Do this procedure and you can see that the mouse event doesnt answer anymore
public class Prova extends JFrame{
private JTable mainTable,fixedTable;
private JScrollPane scrollPane;
private JTableHeader mainTableHeader;
private TableColumnModel originalColumnModel,mainColumnModel,fixedColumnModel;
private TableColumn[] columns;
private int ncols,counter;
public Prova(){
counter = 0;
TableModel mainTableModel = new DefaultTableModel(5, 10);
scrollPane = new JScrollPane();
mainTable = new JTable(mainTableModel);
mainColumnModel = mainTable.getColumnModel();
fixedTable = new JTable();
fixedTable.setAutoCreateColumnsFromModel(false);
fixedTable.setModel(mainTable.getModel() );
ncols = mainTableModel.getColumnCount();
columns = new TableColumn[ncols];
for (int i=0;i<ncols;i++){
columns[i] = mainColumnModel.getColumn(i);
}
mainColumnModel = mainTable.getColumnModel();
fixedColumnModel = fixedTable.getColumnModel();
mainTableHeader = mainTable.getTableHeader();
mainTableHeader.addMouseListener( new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent me){
if (SwingUtilities.isRightMouseButton(me)){
if (ncols - counter>1){
counter ++;
int col = mainTable.columnAtPoint(me.getPoint());
TableColumn column = mainColumnModel.getColumn(col);
mainColumnModel.removeColumn(column);
fixedTable.getColumnModel().addColumn(column);
scrollPane.setRowHeaderView(fixedTable);
scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedTable.getTableHeader());
}
}
}
});
fixedTable.getTableHeader().addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent me){
if (SwingUtilities.isRightMouseButton(me) && me.getClickCount()== 2 ){
while (mainColumnModel.getColumnCount() > 0){
mainColumnModel.removeColumn(mainColumnModel.getColumn(0));
}
while (fixedColumnModel.getColumnCount() > 0){
fixedColumnModel.removeColumn(fixedColumnModel.getColumn(0));
}
for(int i=0;i<ncols;i++){
mainColumnModel.addColumn(columns[i]);
}
scrollPane.setRowHeaderView(null);
}
}
});
scrollPane.setViewportView(mainTable);
add(scrollPane, BorderLayout.CENTER);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Prova().setVisible(true);
}
});
}
}
A few pointers when posting a SSCCE:
for (int i=0;i<ncols;i++){
Don't be afraid to use whitespace in you code to make it more readable be separating the 3 statements of the for statement.
for (int i = 0; i < ncols; i++){
Keep the code simple and directly related to the problem:
TableModel mainTableModel = new EmployeeTableModel(listEmployees);
You question is about "moving columns", not about the data in the table so there is no need for a special TableModel and the Employee class. Just use the DefaultTableModel:
TableModel mainTableModel = new DefaultTableModel(5, 10);
Your current code won't compile because you didn't include the Employee class. By using JDK classes the code is smaller and easier to read.
The problem is when you unlock all the locked columns and you want to start to lock again, doesnt work
Your looping code is wrong. I didn't bother to figure out what was wrong. Instead I made the code simpler:
//for(int i=0;i<(ncols-counter);i++){
while (mainColumnModel.getColumnCount() > 0)
{
mainColumnModel.removeColumn(mainColumnModel.getColumn(0));
}
//for(int i=0;i<counter;i++){
while (fixedColumnModel.getColumnCount() > 0)
{
fixedColumnModel.removeColumn(fixedColumnModel.getColumn(0));
}
Another problem is your fixed table doesn't have a header so you don't know what the columns are. This is fixed by using:
scrollPane.setRowHeaderView(fixedTable);
scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedTable.getTableHeader());
Now that you have a header you need to add the MouseListener to the header, not the scrollpane:
//scrollPane.addMouseListener(new MouseAdapter() {
fixedTable.getTableHeader().addMouseListener(new MouseAdapter() {
Edit:
You have a similar problem to what I fixed above. That is don't keep using variable to track values when you can use the component itself.
if (ncols - counter>1){
You never reset the value of the counter so the if condition won't be true the second time.
As I did above just use the value from the column model:
//if (ncols - counter>1){
if (mainColumnModel.getColumnCount() > 1) {
This is just basic problem solving. Put a display statement in the block of code to see if it executes when you have problems.

move individual Point3f in shape3D consisting of big Point3f array

I have the following code that paints 4 points in a canvas3D window
public final class energon extends JPanel {
int s = 0, count = 0;
public energon() {
setLayout(new BorderLayout());
GraphicsConfiguration gc=SimpleUniverse.getPreferredConfiguration();
Canvas3D canvas3D = new Canvas3D(gc);//See the added gc? this is a preferred config
add("Center", canvas3D);
BranchGroup scene = createSceneGraph();
scene.compile();
// SimpleUniverse is a Convenience Utility class
SimpleUniverse simpleU = new SimpleUniverse(canvas3D);
// This moves the ViewPlatform back a bit so the
// objects in the scene can be viewed.
simpleU.getViewingPlatform().setNominalViewingTransform();
simpleU.addBranchGraph(scene);
}
public BranchGroup createSceneGraph() {
BranchGroup lineGroup = new BranchGroup();
Appearance app = new Appearance();
ColoringAttributes ca = new ColoringAttributes(new Color3f(204.0f, 204.0f, 204.0f), ColoringAttributes.SHADE_FLAT);
app.setColoringAttributes(ca);
Point3f[] plaPts = new Point3f[4];
for (int i = 0; i < 2; i++) {
for (int j = 0; j <2; j++) {
plaPts[count] = new Point3f(i/10.0f,j/10.0f,0);
//Look up line, i and j are divided by 10.0f to be able to
//see the points inside the view screen
count++;
}
}
PointArray pla = new PointArray(4, GeometryArray.COORDINATES);
pla.setCoordinates(0, plaPts);
Shape3D plShape = new Shape3D(pla, app);
TransformGroup objRotate = new TransformGroup();
objRotate.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
objRotate.addChild(plShape);
lineGroup.addChild(objRotate);
return lineGroup;
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new JScrollPane(new energon()));
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Now i want to add a timertask that regularly updates the position of one of the points in the plaPts Point3f array. However, when i call plaPts[1].setX(2), nothing happens on the screen, they remain in the same position.
Do you have to have each point in a separate TransformGroup (consisting of a shape3D with a Point3f array of size 1) for this to be possible? I'm later going to use 100000 points, is it bad for performance if they all are in separate TransformGroups? Is there an easier way of doing this? Something like shape3D.repaint(), that automatically updates the position of the points based on the new values in plaPTS.
Do not use 10000 TransformGroup instances, it will lead to horrible performance (compared to a single PointArray).
You should have a look at the GeometryArray JavaDocs, particularly about the distiction between using data by copying and by reference.
Newer versions of Java3D only support the by copying method. (Your approach would have worked with the by reference method, but you still would have to trigger an update).
The fact that the data is used by copying means that a copy of your Point3f array is created when you pass it to the constructor of the PointArray method. So modifications of these points will not affect the PointArray.
Instead, you can use the setCoordinate method to modify the points. Here is an example, you can simply add this method and pass your PointArray to it:
private static void moveOnePointOf(final PointArray pa)
{
pa.setCapability(PointArray.ALLOW_COORDINATE_WRITE);
Thread t = new Thread(new Runnable()
{
Point3f p = new Point3f();
#Override
public void run()
{
while (true)
{
pa.getCoordinate(0, p);
p.x = (float)Math.sin(System.currentTimeMillis()/1000.0);;
pa.setCoordinate(0, p);
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
}
});
t.setDaemon(true);
t.start();
}
Further notes and hints:
Don not use one thread for each point. This is just an example ;-)
Don't forget to set the capability for writing coordinates:
pointArray.setCapability(PointArray.ALLOW_COORDINATE_WRITE);
You might even consider to not use your Point3f array at all, and set the coordinates directly in the PointArray instead
On some systems, the native rendering components are somewhat odd. For Java3D or other OpenGL-based windows, this means that the window initially is gray, unless you resize or repaint it. You can avoid this by adding
System.setProperty("sun.awt.noerasebackground", "true");
as the first line of your main method.

Problems with JScrollPane -- Trying to Update it on Model Changes

I'm writing a fairly complex program, so I'll try to explain it only in terms of where the problem is occurring.
In my view, I create a JScrollPane to display a list of courses that a student is registered for:
registeredPane = new JScrollPane(); registeredPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
registeredPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
c.gridx = 2;
c.gridwidth = 1;
c.gridheight = 2;
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
layout.setConstraints(registeredPane, c);
Then I, in my controller, change the model to reflect the courses the currently active student is registered in by calling this function in my model:
public void updateCurrentStudentCourses() {
ArrayList<String> courseNames = new ArrayList<String>();
for (Course c: currentStudent.getRegCourses()) {
courseNames.add("" + c.getDepartment().getId() + c.getCode());
}
System.out.println(courseNames);
}
Then I, again in my controller, update the view to reflect these changes by adding the
ArrayList to the JScrollPane:
public void updateView() {
view.getNameField().setText(model.getCurrentStudent().getName());
view.getRegisteredPane().removeAll();
view.getRegisteredPane().getViewport().add(model.getCurrentStudentCourses());
view.getRegisteredPane().repaint();
}
The scrollbars disappear, but that's it. The list items (which I know are in the ArrayList) are not displayed. What am I doing wrong?
EDIT
If model.getCurrentStudentCourses() is returning an ArrayList then you can put the contents of ArrayList within JTextArea and then set the viewport of JScrollPane to be that JTextArea. You can proceed as follows:
your updateView() method should be like this:
JTextArea ta = new JTextArea(30,100);
public void updateView() {
ta.setText("");
for (String course : model.getCurrentStudentCourses())
ta.append(course+"\n");
view.getNameField().setText(model.getCurrentStudent().getName());
view.getRegisteredPane().setViewportView(ta);
}
To set the view of a scrollpane, use setViewportView(). Manipulating the child components of the scrollpane directly will cause problems (for example, you're removing the scroll bars as well).
Scrollpanes have their own layout manager which only knows about the components created by the scrollpane (the various viewports, the scrollbars, the corners). So, any component you add will not appear unless you manually set its position.

How to create dynamically JButton value in DesignGridLayout library?

i create grid layout using DesignGridLayout java library (here).
in the sampe if create 3 column layout. using this code :
layout.row().add(new JButton("Button 1")).add(new JButton("Button 2")).add(new JButton("Button 3"));
or using method that return object :
layout.row().add(button()).add(button()).add(button());
...
...
public JButton button() {
return new JButton("Button");
}
The question is, how to create dynamically JButton value? May be name,icon or anything?
I already try my own code like this :
for (int i=0; i<4; i++) {
JButton button = new JButton();
layout.row().add(button).add(button).add(button);
}
it return :
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Do not add the same component twice
My purpose for different value in each component which added in panel is, i want to create gallery that populate
different image, and i load that images using looping, like this :
for(int i=0; i<files.length; i++) {
...
ImageIcon imgSource = new ImageIcon(new File(myPath));
JLabel labelGallery = new JLabel(imgSource);
...
}
Any solution?
Thanks before :)
In your example,
layout.row().add(button).add(button).add(button);
has the effect of attempting to add the same JButton instance to the row repeatedly.
In the example cited,
layout.row().grid().add(button()).add(button());
invokes an auxiliary method, button(), to create a new instance each time it appears:
public static JButton button() {
return new JButton("Button");
}
As mentioned by #trashgod, Swing does not allow to add the same component twice to a panel.
If you want to add several components, created within a loop, to the same row, you can do it as follows:
IRow row = layout.row().grid();
for (int i = 0; i < n; i++) {
JButton button = createButton(i);
row.add(button);
}
That will create only one row with n buttons inside.

Categories