Show scrollbars only when mouse is over - java

I want to show scrollbars in a JScrollPane only when the mouse is over it. I tried adding a MouseAdapter to the JScrollbar as MouseListener with the methods shown below, but it didn't work very well. The scrollbars blinked when the mouse moved above them.
Any suggestions?
#Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
Runnable runner = new Runnable()
{
public void run() {
JScrollPane sp = (JScrollPane) evt.getSource();
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
}
};
Thread t = new Thread(runner, "Enter Thread");
t.start();
}
#Override
public void mouseExited(java.awt.event.MouseEvent evt) {
Runnable runner = new Runnable()
{
public void run() {
JScrollPane sp = (JScrollPane) evt.getSource();
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
}
};
Thread t = new Thread(runner, "Exit Thread");
t.start();}

In this case, the way to use the MouseListener is troublesome so I can not recommend it much.
For example, the mouse cursor flickers over the JScrollBar.
You might be able to use a JLayer:
Responding to Events - How to Decorate Components with the JLayer Class (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)
import java.awt.*;
import java.awt.event.*;
import java.util.Collections;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
public class ScrollPaneMouseOverTest {
public JComponent makeUI() {
String text = String.join("\n", Collections.nCopies(100, "aaaaa"));
JTextArea ta = new JTextArea(
"Mouse cursor flickers over the JScrollBar.\n" + text);
ta.addMouseListener(new MouseAdapter() {
#Override public void mouseEntered(MouseEvent e) {
JScrollPane sp = (JScrollPane) SwingUtilities.getAncestorOfClass(
JScrollPane.class, (Component) e.getSource());
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
}
#Override public void mouseExited(MouseEvent e) {
JScrollPane sp = (JScrollPane) SwingUtilities.getAncestorOfClass(
JScrollPane.class, (Component) e.getSource());
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
}
});
JScrollPane scroll = new JScrollPane(new JTextArea(text));
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
JPanel p = new JPanel(new GridLayout(2, 1));
p.add(new JScrollPane(ta));
p.add(new JLayer<>(scroll, new LayerUI<JScrollPane>() {
#Override public void installUI(JComponent c) {
super.installUI(c);
if (c instanceof JLayer) {
((JLayer) c).setLayerEventMask(AWTEvent.MOUSE_EVENT_MASK);
}
}
#Override public void uninstallUI(JComponent c) {
if (c instanceof JLayer) {
((JLayer) c).setLayerEventMask(0);
}
super.uninstallUI(c);
}
#Override protected void processMouseEvent(
MouseEvent e, JLayer<? extends JScrollPane> l) {
JScrollPane sp = l.getView();
switch (e.getID()) {
case MouseEvent.MOUSE_ENTERED:
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
break;
case MouseEvent.MOUSE_EXITED:
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
break;
default:
break;
}
//super.processMouseEvent(e, l);
}
}));
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new ScrollPaneMouseOverTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}

I have edited my answer to include the comment below.
JScrollPane scrollPane = new JScrollPane();
scrollPane.setPreferredSize(new Dimension(600, 600));
scrollPane.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(final java.awt.event.MouseEvent evt) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JScrollPane sp = (JScrollPane) evt.getSource();
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
}
});
}
#Override
public void mouseExited(final java.awt.event.MouseEvent evt) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JScrollPane sp = (JScrollPane) evt.getSource();
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
}
});
}
});
JPanel panel = new JPanel(new BorderLayout());
add(panel);
JTextArea ta = new JTextArea();
ta.setPreferredSize(new Dimension(500, 500));
scrollPane.add(ta);
panel.add(scrollPane);

Related

Keybinding not calling AbstractAction

I am making a game where the user has to press keys to move around. I am using keybindings but they are not working. The keybindings are supposed to call the Wp class and print "W pressed", but nothing happens. Here's the code:
public class SO extends JFrame {
public static void main(String[] args) {
new SO();
}
C c;
public SO(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500);
c=new C();
c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("W"), "wp");
c.getActionMap().put("wp", new Wp());
this.setVisible(true);
}
private class C extends JComponent {
public void paint(Graphics g){}
}
private class Wp extends AbstractAction {
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("W pressed");
}
}
}
Use Action to call like component.getActionMap().put("doSomething", anAction);
Refer Key Binding for more information. Below is a sample code I have referred in another Stackoverflow Question reference link SO Ref link
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonBinding {
private JPanel contentPane;
private JTextField tField;
private JButton button;
private KeyStroke keyStroke = KeyStroke.getKeyStroke("ENTER");
private Action action = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Action Performed");
contentPane.setBackground(Color.BLUE);
}
};
private MouseAdapter mouseActions = new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent me) {
System.out.println("Mouse Entered");
JButton button = (JButton) me.getSource();
button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "enter");
button.getActionMap().put("enter", action);
}
#Override
public void mouseExited(MouseEvent me) {
System.out.println("Mouse Exited");
JButton button = (JButton) me.getSource();
button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "none");
contentPane.setBackground(Color.RED);
}
};
private void displayGUI() {
JFrame frame = new JFrame("Button Binding Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new JPanel();
contentPane.setOpaque(true);
tField = new JTextField(10);
button = new JButton("Click Me");
button.addMouseListener(mouseActions);
contentPane.add(tField);
contentPane.add(button);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new ButtonBinding().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}

Dynamic GridLayout with fixed size

Guidance required..
Would like to achieve something like the image below whereby the child panel stays the same size but contains up to 4 components. I realize I can achieve this by changing the number of columns in my gridlayout below but in order to keep the child panel the same size I would have to change the border sizes which is something I don't mind doing but it seems a bit cumbersome and am wondering if there is a smart way to go about this. The code I have provided is based on sample code provided to me here
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class DynamicGridLayout {
private JPanel ui = null;
DynamicGridLayout() {
initUI();
}
public final void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridBagLayout());
ui.setBorder(new TitledBorder("Parent Panel"));
JPanel controls = new JPanel(new GridLayout(2,0,10,10));
ui.add(controls);
controls.setBackground(Color.RED);
controls.setBorder(new TitledBorder("Child Panel"));
for (int ii=1; ii<5; ii++) {
addLabel(controls, "String " + ii);
}
}
public JComponent getUI() {
return ui;
}
private void addLabel(JPanel panel, String text) {
JPanel controls1 = new JPanel(new GridLayout(3,0,3,3));
controls1.setBackground(Color.green);
controls1.setBorder(new EmptyBorder(75,75,75,75));
panel.add(controls1);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("Three Button/Text Field Combo");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
DynamicGridLayout dgl = new DynamicGridLayout();
f.setContentPane(dgl.getUI());
f.setSize(1050, 720);
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
just for my enjoy, fun,
note have to notify (deepest child required override for min/max/preferredsize from) parent JPanel after LayoutManager is switched back from GridLayout to BorderLayout (unwanted output to see in figure 5th.)
.
.
.
.
.
.
from
.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class DynamicGridLayout {
private JFrame f = new JFrame("Three Button/Text Field Combo");
private JPanel ui = new JPanel(new GridBagLayout()) {
#Override
public Dimension getMinimumSize() {
return new Dimension(400, 300);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
#Override
public Dimension getMaximumSize() {
return new Dimension(800, 600);
}
};
private JPanel controls = new JPanel() {
#Override
public Dimension getMinimumSize() {
return new Dimension(400, 300);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
#Override
public Dimension getMaximumSize() {
return new Dimension(1050, 720);
}
};
private JCheckBox checkValidate, checkReValidate, checkRepaint, checkPack;
DynamicGridLayout() {
initUI();
}
public final void initUI() {
ui.setBorder(new TitledBorder("Parent Panel"));
ui.add(controls);
controls.setBackground(Color.RED);
controls.setBorder(new TitledBorder("Child Panel"));
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.add(ui);
f.add(getCheckBoxPanel(), "South");
f.setMinimumSize(ui.getPreferredSize());
f.setVisible(true);
}
public JComponent getUI() {
return ui;
}
private void addLabel() {
JPanel controls1 = new JPanel(new GridLayout(3, 0, 3, 3));
controls1.setBackground(Color.green);
controls1.setBorder(new EmptyBorder(75, 75, 75, 75));
controls.add(controls1);
}
private JPanel getCheckBoxPanel() {
checkValidate = new JCheckBox("validate");
checkValidate.setSelected(false);
checkReValidate = new JCheckBox("revalidate");
checkReValidate.setSelected(true);
checkRepaint = new JCheckBox("repaint");
checkRepaint.setSelected(true);
checkPack = new JCheckBox("pack");
checkPack.setSelected(false);
JButton addComp = new JButton("Add New One");
addComp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (controls.getComponentCount() < 1) {
controls.setLayout(new BorderLayout());
addLabel();
makeChange();
} else if (controls.getComponentCount() == 1) {
controls.setLayout(new GridLayout(0, 2, 10, 10));
addLabel();
makeChange();
} else {
controls.setLayout(new GridLayout(2, 0, 10, 10));
addLabel();
makeChange();
}
System.out.println(" Components Count after Adds :" + controls.getComponentCount());
}
});
JButton removeComp = new JButton("Remove One");
removeComp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int count = controls.getComponentCount();
if (count > 0) {
if (controls.getComponentCount() == 2) {
controls.setLayout(new BorderLayout());
controls.remove(0);
} else if (controls.getComponentCount() == 3) {
controls.setLayout(new GridLayout(0, 2, 10, 10));
controls.remove(0);
} else {
controls.remove(0);
}
}
makeChange();
System.out.println(" Components Count after Removes :" + controls.getComponentCount());
}
});
JPanel panel2 = new JPanel();
panel2.add(checkValidate);
panel2.add(checkReValidate);
panel2.add(checkRepaint);
panel2.add(checkPack);
panel2.add(addComp);
panel2.add(removeComp);
return panel2;
}
private void makeChange() {
if (checkValidate.isSelected()) {
ui.validate();
}
if (checkReValidate.isSelected()) {
ui.revalidate();
}
if (checkRepaint.isSelected()) {
ui.repaint();
}
if (checkPack.isSelected()) {
f.pack();
}
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
DynamicGridLayout dgl = new DynamicGridLayout();
}
};
SwingUtilities.invokeLater(r);
}
}

Java JTextArea KeyListener

When I pressed the ENTER my JTextArea starts a new row and I only want do to the doClick() method nothing else.
How should I do that?
textarea.addKeyListener(new KeyListener(){
#Override
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_ENTER){
button.doClick();
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
});
Use .consume():
Consumes this event so that it will not be processed in the default
manner by the source which originated it.
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_ENTER){
e.consume();
button.doClick();
}
}
Documentation
You should use KeyBindings with any JTextComponent in question. KeyListeners are way too low level from Swing's perspective. You are using the concept which was related to AWT, Swing uses KeyBindings to do the same task with more efficiency and provides desired results :-)
A small program for your help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyBindingExample {
private static final String key = "ENTER";
private KeyStroke keyStroke;
private JButton button;
private JTextArea textArea;
private Action wrapper = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
button.doClick();
}
};
private void displayGUI() {
JFrame frame = new JFrame("Key Binding Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel(new BorderLayout(5, 5));
textArea = new JTextArea(10, 10);
keyStroke = KeyStroke.getKeyStroke(key);
Object actionKey = textArea.getInputMap(
JComponent.WHEN_FOCUSED).get(keyStroke);
textArea.getActionMap().put(actionKey, wrapper);
button = new JButton("Click Me!");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.out.format("Button Clicked :-)%n");
}
});
contentPane.add(textArea, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new KeyBindingExample().displayGUI();
}
};
EventQueue.invokeLater(r);
}
}

JEditorPane focus problems after setText()

There is a problem in my application when trying to set focus on a JEditorPane using the tab key. I did not understand why at first, but I manage to make a small test case that demonstrates the issue.
public class JEditorPaneFocusTest
{
public static void main(String... args) throws Exception
{
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = jFrame.getContentPane();
container.setLayout(new BorderLayout());
container.add(new JTextField(), BorderLayout.NORTH);
JEditorPane editorPane = new JEditorPane();
editorPane.setEditorKit(new HTMLEditorKit());
editorPane.setText("<html><body>Hello World</body></html>");
container.add(editorPane, BorderLayout.CENTER);
jFrame.setSize(new Dimension(400, 400));
jFrame.setVisible(true);
}
}
(Tested on Windows 7 and Mac OS X Lion.) The application will start with focus on the JTextField. Using the tab key won't set focus to the JEditorPane. But if you comment the setText line, it seems to work...
Any idea?
short answer
delay this event by wraping to the invokeLater()
longer answer
Focus / Focus Subsystem is asynchronous, in most cases hard to manage/timing this/these even(s), for better understanding about this issue you have to read linked tutorials,
example about Focus issue
import java.awt.*;
import java.awt.event.*;
import java.awt.font.TextAttribute;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.Map;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;
public class TextAttributeSTRIKETHROUGH {
private JFrame frame = new JFrame();
private JPanel pnl = new JPanel();
private JLabel focusLabel = new JLabel(" focusLost Handle ");
private JFormattedTextField formTextField;
private JLabel docLabel = new JLabel(" document Handle ");
private JFormattedTextField formTextField1;
private NumberFormat formTextFieldFormat;
private double amount = 10000.00;
private Map attributes;
#SuppressWarnings("unchecked")
public TextAttributeSTRIKETHROUGH() {
formTextFieldFormat = NumberFormat.getNumberInstance();
formTextFieldFormat.setMinimumFractionDigits(2);
formTextFieldFormat.setMaximumFractionDigits(2);
formTextFieldFormat.setRoundingMode(RoundingMode.HALF_UP);
focusLabel.setFont(new Font("Serif", Font.BOLD, 14));
focusLabel.setForeground(Color.blue);
focusLabel.setPreferredSize(new Dimension(120, 27));
formTextField = new JFormattedTextField(formTextFieldFormat);
formTextField.setValue(amount);
formTextField.setFont(new Font("Serif", Font.BOLD, 22));
formTextField.setForeground(Color.black);
formTextField.setBackground(Color.yellow);
formTextField.setPreferredSize(new Dimension(120, 27));
formTextField.setHorizontalAlignment(SwingConstants.RIGHT);
formTextField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
formTextField.requestFocus();
formTextField.setText(formTextField.getText());
formTextField.selectAll();
}
public void focusLost(FocusEvent e) {
//Runnable doRun = new Runnable() {
//#Override
//public void run() {
double t1a1 = (((Number) formTextField.getValue()).doubleValue());
if (t1a1 < 1000) {
formTextField.setValue(amount);
}
//}
// };
//SwingUtilities.invokeLater(doRun);
}
});
docLabel.setFont(new Font("Serif", Font.BOLD, 14));
docLabel.setForeground(Color.blue);
docLabel.setPreferredSize(new Dimension(120, 27));
formTextField1 = new JFormattedTextField(formTextFieldFormat);
formTextField1.setValue(amount);
formTextField1.setFont(new Font("Serif", Font.BOLD, 22));
formTextField1.setForeground(Color.black);
formTextField1.setBackground(Color.yellow);
formTextField1.setPreferredSize(new Dimension(120, 27));
formTextField1.setHorizontalAlignment(SwingConstants.RIGHT);
formTextField1.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
formTextField1.requestFocus();
formTextField1.setText(formTextField1.getText());
formTextField1.selectAll();
}
#Override
public void focusLost(FocusEvent e) {
}
});
formTextField1.getDocument().addDocumentListener(docListener);
attributes = (new Font("Serif", Font.BOLD, 24)).getAttributes();
attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
pnl = new JPanel();
pnl.setBorder(new EmptyBorder(2, 2, 2, 2));
pnl.setLayout(new GridLayout(2, 2));
pnl.add(focusLabel);
pnl.add(formTextField);
pnl.add(docLabel);
pnl.add(formTextField1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pnl, BorderLayout.CENTER);
frame.setLocation(200, 200);
frame.pack();
frame.setVisible(true);
formTextFieldFocus1();
}
//
private DocumentListener docListener = new DocumentListener() {
#Override
public void changedUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
#Override
public void insertUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
#Override
public void removeUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
private void printIt(DocumentEvent documentEvent) {
DocumentEvent.EventType type = documentEvent.getType();
double t1a1 = (((Number) formTextField1.getValue()).doubleValue());
if (t1a1 < 1000) {
Runnable doRun = new Runnable() {
#Override
public void run() {
formTextField1.setFont(new Font(attributes));
}
};
SwingUtilities.invokeLater(doRun);
} else {
Runnable doRun = new Runnable() {
#Override
public void run() {
formTextField1.setFont(new Font("Serif", Font.BOLD, 22));
}
};
SwingUtilities.invokeLater(doRun);
}
}
};
private void formTextFieldFocus1() {
Runnable doRun = new Runnable() {
#Override
public void run() {
formTextField1.grabFocus();
formTextField1.requestFocus();
formTextField1.setText(formTextField1.getText());
formTextField1.selectAll();
}
};
SwingUtilities.invokeLater(doRun);
}
private void formTextFieldFocus() {
Runnable doRun = new Runnable() {
#Override
public void run() {
formTextField.grabFocus();
formTextField.requestFocus();
formTextField.setText(formTextField.getText());
formTextField.selectAll();
formTextFieldFocus1();
}
};
SwingUtilities.invokeLater(doRun);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
TextAttributeSTRIKETHROUGH fl = new TextAttributeSTRIKETHROUGH();
}
});
}
}
All GUI related code should be executed on the EDT. See Concurrency in Swing for more details.
import java.awt.*;
import javax.swing.*;
import javax.swing.text.html.*;
public class JEditorPaneFocusTest
{
public static void main(String... args) throws Exception
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = jFrame.getContentPane();
container.setLayout(new BorderLayout());
container.add(new JTextField(), BorderLayout.NORTH);
JEditorPane editorPane = new JEditorPane();
editorPane.setEditorKit(new HTMLEditorKit());
editorPane.setText("<html><body>Hello World</body></html>");
container.add(editorPane, BorderLayout.CENTER);
jFrame.setSize(new Dimension(400, 400));
jFrame.setVisible(true);
}
});
}
}

How to set BackGround color to a divider in JSplitPane

I have created a divider in JSplitPane. I am unable to set the color of divider. I want to set the color of divider. Please help me how to set color of that divider.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SplitPaneDemo {
JFrame frame;
JPanel left, right;
JSplitPane pane;
int lastDividerLocation = -1;
public static void main(String[] args) {
SplitPaneDemo demo = new SplitPaneDemo();
demo.makeFrame();
demo.frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
demo.frame.show();
}
public JFrame makeFrame() {
frame = new JFrame();
// Create a horizontal split pane.
pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
left = new JPanel();
left.setBackground(Color.red);
pane.setLeftComponent(left);
right = new JPanel();
right.setBackground(Color.green);
pane.setRightComponent(right);
JButton showleft = new JButton("Left");
showleft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Container c = frame.getContentPane();
if (pane.isShowing()) {
lastDividerLocation = pane.getDividerLocation();
}
c.remove(pane);
c.remove(left);
c.remove(right);
c.add(left, BorderLayout.CENTER);
c.validate();
c.repaint();
}
});
JButton showright = new JButton("Right");
showright.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Container c = frame.getContentPane();
if (pane.isShowing()) {
lastDividerLocation = pane.getDividerLocation();
}
c.remove(pane);
c.remove(left);
c.remove(right);
c.add(right, BorderLayout.CENTER);
c.validate();
c.repaint();
}
});
JButton showboth = new JButton("Both");
showboth.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Container c = frame.getContentPane();
c.remove(pane);
c.remove(left);
c.remove(right);
pane.setLeftComponent(left);
pane.setRightComponent(right);
c.add(pane, BorderLayout.CENTER);
if (lastDividerLocation >= 0) {
pane.setDividerLocation(lastDividerLocation);
}
c.validate();
c.repaint();
}
});
JPanel buttons = new JPanel();
buttons.setLayout(new GridBagLayout());
buttons.add(showleft);
buttons.add(showright);
buttons.add(showboth);
frame.getContentPane().add(buttons, BorderLayout.NORTH);
pane.setPreferredSize(new Dimension(400, 300));
frame.getContentPane().add(pane, BorderLayout.CENTER);
frame.pack();
pane.setDividerLocation(0.5);
return frame;
}
}
Thanks
Sunil kumar Sahoo
Or, since the divider is a container, you can do the following:
dividerContainer = (BasicSplitPaneDivider) splitPane.getComponent(2);
Component leftBtn = dividerContainer.getComponent(0);
Component rightBtn = dividerContainer.getComponent(1);
dividerContainer.setBackground(Color.white);
dividerContainer.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 4));
dividerContainer.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
dividerContainer.add(toolbar);
dividerContainer.setDividerSize(toolbar.getPreferredSize().height);
This code works for me:
splitPane.setUI(new BasicSplitPaneUI() {
public BasicSplitPaneDivider createDefaultDivider() {
return new BasicSplitPaneDivider(this) {
public void setBorder(Border b) {
}
#Override
public void paint(Graphics g) {
g.setColor(Color.GREEN);
g.fillRect(0, 0, getSize().width, getSize().height);
super.paint(g);
}
};
}
});
splitPane.setBorder(null);
You can change divider color "g.setColor(new Color(R,G,B))".
This worked for me fine.First you are creating JFrame with it's normal methods such as setDefaultCloseOperation(), setBounds(), getContentPane(). Then create an object from your class then use that to call all the other methods through out the program, in this case I created object called app. One thing you have to keep in mind is that don't forget to use ActionListener e.
Also color changes must go with setBackground() function, while you getting the values from getSource() for the color change.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Main implements ActionListener {
private static void createAndShowGUI() {
Main app=new Main();
// make frame..
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("I am a JFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(20,30,300,120);
frame.setLayout(null);
//Create a split pane
JSplitPane myPane = new JSplitPane();
myPane.setOpaque(true);
myPane.setDividerLocation(150);
app.right = new JPanel();
app.right.setBackground(new Color(255,0,0));
app.left = new JPanel();
app.left.setBackground(new Color(0,255,0));
app.left.setLayout(null);
myPane.setRightComponent(app.right);
myPane.setLeftComponent(app.left);
// make buttons
app.butt1=new JButton("Red");
app.butt2=new JButton("Blue");
app.butt3=new JButton("Green");
// add and size buttons
app.left.add(app.butt1);
app.butt1.setBounds(10,10, 100,20);
app.left.add(app.butt2);
app.butt2.setBounds(10,30, 100,20);
app.left.add(app.butt3);
app.butt3.setBounds(10,50, 100,20);
// set up listener
app.butt1.addActionListener(app);
app.butt2.addActionListener(app);
app.butt3.addActionListener(app);
frame.setContentPane(myPane);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
// check which button and act accordingly
if (e.getSource()==butt1)
right.setBackground(new Color(255,0,0));
if (e.getSource()==butt2)
right.setBackground(new Color(0,0,255));
if (e.getSource()==butt3)
right.setBackground(new Color(0,255,0));
}
public static void main(String[] args) {
// start off..
try {
UIManager.setLookAndFeel(
"javax.swing.plaf.metal.MetalLookAndFeel" );
}
catch (Exception e)
{
System.out.println("Cant get laf");
}
Object a[]= UIManager.getInstalledLookAndFeels();
for (int i=0; i<a.length; i++)
System.out.println(a[i]);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
// application object fields
int clickCount=0;
JLabel label;
JButton butt1;
JButton butt2;
JButton butt3;
JPanel left;
JPanel right;
}

Categories