Placing the JPanel in JScrollPane [duplicate] - java

I've got a probelm with my swing ui lately. Everything works fine,untill i trigger a tooltip from a JButton.After that moving the mouse over the rest of the ui is causing weird artifacts and glitching.
Bugged:
I can't show the whole code because its too much but here im initialising the button :
GridBagConstraints bottompane_gbc = new GridBagConstraints();
toggleTorConnectionButton = new JButton();
toggleTorConnectionButton.setToolTipText("Toggles Tor Connection.");
toggleTorConnectionButton.setIcon(new ImageIcon(ResourceHandler.Menueicon3_1));
toggleTorConnectionButton.setMinimumSize(new Dimension(removeFinishedDownloads.getMinimumSize().width, toggleTorConnectionButton.getIcon().getIconHeight()+5));
toggleTorConnectionButton.addActionListener(); // unimportant
bottompane_gbc.gridy = 1;
bottompane_gbc.fill = GridBagConstraints.BOTH;
bottompane_gbc.insets = new Insets(0,15,10,5);
bottompane.add(ToggleTorConnectionButton,bottompane_gbc);
this.add(bottompane,BorderLayout.PAGE_END);
If anybody needs more information to help me pls feel free to ask.Im kind of desperated. XD
EDIT:
After some tinkering im guessing that the problem is related to swing and my use of it.Currently im using alot of Eventlisteners (is this bad?), that might slow down the awt thread ?
Here is a brief extract from HPROF:
http://www.pastebucket.com/96444
EDIT 2:
I was able to recreate the error in a handy and simple example. When you move over the button,wait for the tooltip and then over the ui.You will see ghosting :(.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
public class Main_frame {
public static void main(String[] args) {
new Main_frame();
}
public Main_frame() {
JFrame frame = new JFrame("LOL");
frame.setFocusable(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(400, 500));
frame.setLocationRelativeTo(null);
Download_window download_window = new Download_window();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Download", null, download_window, "Main Download Window.");
for (int i = 0; i < 5; i++) {
JPanel pane = new JPanel();
Dimension dim = new Dimension(370, 60);
pane.setPreferredSize(dim);
pane.setMaximumSize(dim);
pane.setBackground(Color.blue);
pane.setMinimumSize(dim);
download_window.jobpanel.add(pane);
}
download_window.jobpanel.repaint();
download_window.jobpanel.revalidate();
frame.add(tabbedPane);
frame.setVisible(true);
}
public class Download_window extends JPanel {
JPanel jobpanel;
public Download_window() {
this.setLayout(new BorderLayout());
jobpanel = new JPanel();
jobpanel.setLayout(new BoxLayout(jobpanel, BoxLayout.Y_AXIS));
JPanel bottompane = new JPanel();
bottompane.setPreferredSize(new Dimension(385, 40));
JButton toggleTorConnectionButton = new JButton();
toggleTorConnectionButton.setPreferredSize(new Dimension(100, 50));
toggleTorConnectionButton.setToolTipText("Toggles Tor Connection.");
bottompane.add(toggleTorConnectionButton);
this.add(bottompane, BorderLayout.PAGE_END);
JScrollPane jobScrollPane = new JScrollPane(jobpanel);
jobScrollPane.getVerticalScrollBar().setUnitIncrement(16);
this.add(jobScrollPane, BorderLayout.CENTER);
}
}
}
Edit 3: Concerning trashgods ideas, I used the EventDispatchThread, I modified the setter to override the getter for size and i crossed out incompatibility by using trashgods code and it was working fine.... So where is the actual difference?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
public class Main_frame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Main_frame();
}
});
}
public Main_frame() {
JFrame frame = new JFrame("LOL");
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(400, 500));
Download_window download_window = new Download_window();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Download", null, download_window, "Main Download Window.");
frame.add(tabbedPane);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class Download_window extends JPanel {
JPanel jobpanel;
public Download_window() {
this.setLayout(new BorderLayout());
jobpanel = new JPanel();
jobpanel.setLayout(new BoxLayout(jobpanel, BoxLayout.Y_AXIS));
for (int i = 0; i < 5; i++) {
JPanel pane = new JPanel(){
#Override
public Dimension getPreferredSize() {
return new Dimension(370, 60);
}
#Override
public Dimension getMaximumSize() {
return new Dimension(370, 60);
}
#Override
public Dimension getMinimumSize() {
return new Dimension(370, 60);
}
};
pane.setBackground(Color.blue);
jobpanel.add(pane);
}
JPanel bottompane = new JPanel(){
#Override
public Dimension getPreferredSize() {
return new Dimension(385, 40);
}
};
JButton toggleTorConnectionButton = new JButton("Button"){
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 30);
}
};
toggleTorConnectionButton.setToolTipText("Toggles Tor Connection.");
bottompane.add(toggleTorConnectionButton);
this.add(bottompane, BorderLayout.PAGE_END);
JScrollPane jobScrollPane = new JScrollPane(jobpanel);
jobScrollPane.getVerticalScrollBar().setUnitIncrement(16);
this.add(jobScrollPane, BorderLayout.CENTER);
}
}
}
Could anyone please verify that strange behavior himself? You just need to copy&paste the code from above in Edit3.

Your code exhibits none of the glitches shown above when run on my platform.
Verify that you have no painting problems e.g. neglecting super.paintComponent() as discussed here.
Verify that you have no driver incompatibilities, as discussed here.
Construct and modify all GUI objects on the event dispatch thread.
Don't use set[Preferred|Maximum|Minimum]Size() when you really mean to override get[Preferred|Maximum|Minimum]Size(), as discussed here. The example below overrides getPreferredSize() on the scroll pane, but you can implement Scrollable, as discussed here.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
/** #see https://stackoverflow.com/a/34319260/230513 */
public class MainFrame {
private static final int H = 64;
public static void main(String[] args) {
EventQueue.invokeLater(() -> new MainFrame());
}
public MainFrame() {
JFrame frame = new JFrame("LOL");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panel = new JPanel(new GridLayout(0, 1, 5, 5));
for (int i = 0; i < 8; i++) {
panel.add(new DownloadPanel());
}
JScrollPane jsp = new JScrollPane(panel) {
#Override
public Dimension getPreferredSize() {
return new Dimension(6 * H, 4 * H);
}
};
tabbedPane.addTab("Download", null, jsp, "Main Download Window.");
tabbedPane.addTab("Options", null, null, "Options");
frame.add(tabbedPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static class DownloadPanel extends JPanel {
JPanel jobPanel = new JPanel();
public DownloadPanel() {
this.setLayout(new BorderLayout());
this.setBackground(Color.lightGray);
JProgressBar jpb = new JProgressBar();
jpb.setIndeterminate(true);
this.add(jpb);
JPanel buttonPane = new JPanel();
JButton toggleTorConnectionButton = new JButton("Button");
toggleTorConnectionButton.setToolTipText("Toggles Tor Connection.");
buttonPane.add(toggleTorConnectionButton);
this.add(buttonPane, BorderLayout.WEST);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(4 * H, H);
}
}
}

Related

How to wait until JDialog is fully created

I need to calculate window decorations somehow. So I override JDialog's constructor. But when I call get_decoration_size() it sometimes returns wrong values. And my thought was: window creates later than get_decoration_size() executes(strange, because both in same thread and in same constructor). So I decided to sleep for a second, and it worked, and now decorations always valid.
My question is: is there a way to "join" to the creating process(wait until window is shown by setVisible(true))? If so, it must be something to replace unsafe_sleep(1000).
package swing.window;
import db.db;
import javax.swing.*;
import java.awt.*;
import static swing.util.*;
import static util.util.unsafe_sleep;
public class calc_decor extends JDialog {
{
//some initializations
setLayout(null);
setResizable(false);
JLabel label = new JLabel("Loading...");
add(label);
setxy(label, 3, 3);
fit(label);
setsize(this, label.getWidth() + 100, label.getHeight() + 100);
window_to_center(this);
setVisible(true);//trying to draw
unsafe_sleep(1000);//without that it looks like get_decoratoin_size()
//is called before setVisible(true)
db.sysdecor = get_decoration_size();//trying to get decorations
dispose();
}
private Dimension get_decoration_size() {
Rectangle window = getBounds();
Rectangle content = getContentPane().getBounds();
int width = window.width - content.width;
int height = window.height - content.height;
return new Dimension(width, height);
}
}
I had to assume a lot to create a runnable example.
Here's the result of your getDecorationSize method. The line didn't print until I closed the JDialog.
java.awt.Dimension[width=16,height=39]
And here's the code I used.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JDialogTest implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JDialogTest());
}
private JFrame frame;
#Override
public void run() {
frame = new JFrame("JDialog Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(
150, 100, 150, 100));
panel.setPreferredSize(new Dimension(400, 400));
JButton button = new JButton("Open JDialog");
button.addActionListener(new ButtonListener());
panel.add(button);
return panel;
}
public class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
new CalculateDecor(frame, "Spash Screen");
}
}
public class CalculateDecor extends JDialog {
private static final long serialVersionUID = 1L;
public CalculateDecor(JFrame frame, String title) {
super(frame, true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setTitle(title);
JPanel panel = new JPanel(new BorderLayout());
panel.setPreferredSize(new Dimension(200, 200));
JLabel label = new JLabel("Loading...");
label.setHorizontalAlignment(JLabel.CENTER);
panel.add(label);
add(panel);
pack();
setLocationRelativeTo(frame);
setVisible(true);
System.out.println(getDecorationSize());
}
private Dimension getDecorationSize() {
Rectangle window = getBounds();
Rectangle content = getContentPane().getBounds();
int width = window.width - content.width;
int height = window.height - content.height;
return new Dimension(width, height);
}
}
}

Automatically Resizing with BorderLayout in Java

This is my jFrame Form with BorderLayout where buttons will be placed in Navigation Bar Panel and jDesktopPane will be placed in Content Panel. The DesktopPane with CardLayout will be displaying different sizes of jPanel Form. I want Content Panel(including whole form) resize based on the different sizes of jPanel Form displayed. Is it possible to do this? If not then I've tried resizing the panel and even the whole form with codes, but it's not working.
I've trying playing with these few codes, but it's not working.
Main_Menu form = new Main_Menu();
form.pack();
form.setSize(900, 548);
form.setPreferredSize(new Dimension(900, 548));
form.validate();
So, based on the limited information available, I wrote a quick test which seems to work just fine
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
CardLayout layout = new CardLayout();
JDesktopPane pane = new JDesktopPane();
Navigator navigator = new Navigator(pane, layout);
pane.setLayout(layout);
pane.setBackground(Color.GREEN);
frame.add(new TopPane(), BorderLayout.NORTH);
frame.add(new NavigationPane(navigator), BorderLayout.WEST);
for (int index = 0; index < 5; index++) {
pane.add(new ContentPane(index), Integer.toString(index));
}
JLabel initial = new JLabel("All your content belong to us");
initial.setBorder(new EmptyBorder(20, 20, 20, 20));
pane.add(initial, "initial");
layout.show(pane, "initial");
frame.add(pane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Navigator {
private JComponent parent;
private CardLayout layout;
public Navigator(JComponent parent, CardLayout layout) {
this.parent = parent;
this.layout = layout;
}
public void show(String name) {
layout.show(parent, name);
}
}
public class TopPane extends JPanel {
public TopPane() {
setLayout(new GridBagLayout());
setBorder(new EmptyBorder(20, 20, 20, 20));
setBackground(Color.BLUE);
JLabel title = new JLabel("Top Panel");
title.setForeground(Color.WHITE);
add(title);
}
}
public class NavigationPane extends JPanel {
private Navigator navigator;
public NavigationPane(Navigator navigator) {
setLayout(new GridBagLayout());
setBorder(new EmptyBorder(20, 20, 20, 20));
setBackground(Color.ORANGE);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.BOTH;
for (int index = 0; index < 5; index++) {
JButton btn = new JButton("Test " + index);
btn.setActionCommand(Integer.toString(index));
add(btn, gbc);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String name = e.getActionCommand();
navigator.show(name);
}
});
}
}
}
public class ContentPane extends JPanel {
public ContentPane(int value) {
setLayout(new GridBagLayout());
setBorder(new EmptyBorder(20, 20, 20, 20));
setBackground(Color.MAGENTA);
add(new JLabel("Hello from " + Integer.toString(value)));
}
}
}
Avoid setPreferred/Minimum/MaximumSize, you're overriding the work which the components and the layout managers do in order to provide dynamic sizing hints
If this fails to solve your issue, then consider providing a Minimal, Complete, and Verifiable example
Try to use pack(); not form.pack();. Or setLayout or use CardLayout

Can't add JPanel to BorderLayout.CENTER

I am just Starting out with JAVA.
I have say a JPanel x, a JPanel y and a BorderLayout JPanel z.
When I try to change the contents of the center of z from default x t y, it works but it doesn't go back to x. I AM calling revalidate() after each. Help please.
The class below is where the problem is.
Main Class Below
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.LayoutManager;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
#SuppressWarnings({ "serial", "unused" })
public class Manager extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Manager frame = new Manager();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Manager() {
setTitle("Popper");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
height = height/5.1;
setSize((int)width, (int)height);
setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(0,0,0,0));
setContentPane(contentPane);
contentPane.setBackground(new Color(14,99,165));
contentPane.setLayout(new BorderLayout(0, 0));
ImageIcon image = new ImageIcon("D:/popper26.png");
setIconImage(image.getImage());
JPanel pane = new JPanel();
calcu cal = new calcu();
curr nup = new curr();
stopc newst = new stopc();
pane.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel mainpanel = new JPanel();
BorderLayout x =new BorderLayout(0,0);
mainpanel.setLayout(x);
mainpanel.setBackground(Color.WHITE);
JLabel madeby = new JLabel("Project By Anant Bhasin");
madeby.setHorizontalAlignment(SwingConstants.RIGHT);
mainpanel.add(madeby, BorderLayout.SOUTH);
JPanel logo = new JPanel();
logo.setLayout(new FlowLayout(FlowLayout.CENTER));
JLabel jk = new JLabel(new ImageIcon("D:/popper2.png"));
logo.add(jk, BorderLayout.NORTH);
logo.setBackground(Color.decode("#1abc9c"));
mainpanel.add(logo, BorderLayout.NORTH);
mainpanel.add(cal, BorderLayout.CENTER);
contentPane.add(mainpanel, BorderLayout.CENTER);
JPanel newj = new JPanel();
BoxLayout bxl = new BoxLayout(newj, BoxLayout.PAGE_AXIS);
newj.setLayout(bxl);
newj.setBackground(new Color(58,115,144));
contentPane.add(newj, BorderLayout.WEST);
Border emptyBorder = BorderFactory.createEmptyBorder();
JButton calc = new JButton(new ImageIcon("D:/calc.png"));
newj.add(calc);
calc.setBorder(emptyBorder);
calc.setFocusPainted(false);
calc.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
mainpanel.add(BorderLayout.CENTER, cal);
mainpanel.revalidate();
}
});
JButton currb = new JButton(new ImageIcon("D:/curr.png"));
currb.setBorder(emptyBorder);
newj.add(currb);
currb.setFocusPainted(false);
currb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
mainpanel.add(BorderLayout.CENTER, nup);
mainpanel.revalidate();
}
});
JButton stop = new JButton(new ImageIcon("D:/stop.png"));
stop.setBorder(emptyBorder);
newj.add(stop);
stop.setFocusPainted(false);
stop.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
mainpanel.add(BorderLayout.CENTER, newst);
mainpanel.revalidate();
}
});
JButton timer = new JButton(new ImageIcon("D:/timer.png"));
timer.setBorder(emptyBorder);
newj.add(timer);
timer.setFocusPainted(false);
JButton memo = new JButton(new ImageIcon("D:/memo.png"));
memo.setBorder(emptyBorder);
newj.add(memo);
memo.setFocusPainted(false);
}
}
A BorderLayout is not designed to display multiple components with the same constraint because of the way ZOrder painting works in Swing.
If you need the ability to swap panels, then you should be using a CardLayout.
A CardLayout lets you specify the name of the panel that you want to display. Read the section from the Swing tutorial on How to Use CardLayout for more information and working examples.
You set up the layout with code like:
JPanel main = new JPanel( new CardLayout() );
main.add(panelx, "X");
main.add(panely, "Y");
Then to swap a panel you use code like:
CardLayout cl = (CardLayout)(main.getLayout());
cl.show(main, "X");

GridBagLayout and drawing

I'm making a small game and at the beginning i want to have JCheckBox for choosing the language(after that they are few more of them for setting the game) and above that a jlabel with picture with name of the game OR draw an image there, the problem is that i dont know any other way how to center the panel with checkboxes then to use GridBagLayout and when i use this, i cannot draw anything to the frame, id like to also remove those grey lines around the checkboxes if its possible, appreciate any help, thanks.
This is my second question here and i cant add images yet so here is a link to the picture :
here is code for the frame
private GamePlan plan;
private JFrame frame;
private String language;
private JPanel panel;
private JCheckBox englishBox;
private JCheckBox germanBox;
public Settings(GamePlan plan){
this.plan = plan;
frame = new JFrame();
frame.setSize(600, 500);
frame.setLocation(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.setResizable(false);
frame.setVisible(true);
panel = new JPanel(new GridLayout(2, 1));
englishBox = new JCheckBox("English", false);
germanBox = new JCheckBox("German", false);
englishBox.addActionListener(new EnglishLanguage());
germanBox.addActionListener(new GermanLanguage());
panel.add(englishBox);
panel.add(germanBox);
englishBox.setOpaque(false);
germanBox.setOpaque(false);
panel.setOpaque(false);
frame.add(panel);
frame.getContentPane().setBackground(new Color(216,252,202));
}
" the problem is that i dont know any other way how to center the panel with checkboxes then to use GridBagLayout and when i use this, i cannot draw anything to the frame"
I can't really tell what you're doing wrong without a complete example. I don't even see where you're trying to add the image. But don't try and draw on the frame. Draw on a JPanel instead.
Here is an example you may be able to gain some insight from.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;
public class ImageByDrawing {
public ImageByDrawing() {
ImagePanel imagePanel = new ImagePanel();
imagePanel.setBorder(new TitledBorder("Drawn Image onto JPanel"));
JCheckBox germanBox = new JCheckBox("German");
germanBox.setOpaque(false);
JCheckBox englishBox = new JCheckBox("English");
englishBox.setOpaque(false);
JPanel boxPanel = new JPanel();
boxPanel.setBorder(new TitledBorder("JPanel with default FlowLayout"));
boxPanel.setOpaque(false);
boxPanel.add(germanBox);
boxPanel.add(englishBox);
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(imagePanel, BorderLayout.CENTER);
centerPanel.add(boxPanel, BorderLayout.SOUTH);
centerPanel.setBorder(new TitledBorder("JPanel with BorderLayout"));
centerPanel.setOpaque(false);
JPanel mainPanel = new JPanel(new GridBagLayout());
mainPanel.add(centerPanel);
mainPanel.setBorder(new TitledBorder("JPanel with GridBagLayout"));
mainPanel.setBackground(new Color(216,252,202));
JFrame frame = new JFrame();
frame.add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class ImagePanel extends JPanel {
BufferedImage img;
int dWidth;
int dHeight;
public ImagePanel() {
try {
img = ImageIO.read(getClass().getResource("/resources/stackblack.jpg"));
dWidth = img.getWidth();
dHeight = img.getHeight();
} catch (IOException ex) {
Logger.getLogger(ImageByDrawing.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
return (img == null) ? new Dimension(300, 300) : new Dimension(dWidth, dHeight);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new ImageByDrawing();
}
});
}
}
Also I don't know why you prefer to draw the image. The same can be easily done with a JLabel and ImageIcon
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagLayout;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;
public class ImageByDrawing {
public ImageByDrawing() {
ImageIcon icon = new ImageIcon(getClass().getResource("/resources/stackblack.jpg"));
JLabel label = new JLabel(icon);
label.setBorder(new TitledBorder("JLabel with ImageIcon"));
JCheckBox germanBox = new JCheckBox("German");
germanBox.setOpaque(false);
JCheckBox englishBox = new JCheckBox("English");
englishBox.setOpaque(false);
JPanel boxPanel = new JPanel();
boxPanel.setBorder(new TitledBorder("JPanel with default FlowLayout"));
boxPanel.setOpaque(false);
boxPanel.add(germanBox);
boxPanel.add(englishBox);
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(label, BorderLayout.CENTER);
centerPanel.add(boxPanel, BorderLayout.SOUTH);
centerPanel.setBorder(new TitledBorder("JPanel with BorderLayout"));
centerPanel.setOpaque(false);
JPanel mainPanel = new JPanel(new GridBagLayout());
mainPanel.add(centerPanel);
mainPanel.setBorder(new TitledBorder("JPanel with GridBagLayout"));
mainPanel.setBackground(new Color(216, 252, 202));
JFrame frame = new JFrame();
frame.add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ImageByDrawing();
}
});
}
}
The last part of your question, as #Jere pointed out you can use setFocusPainted for the check box germanBox.setFocusPainted(false);

JScrollPane with JPanel nothing see

I wnat add to JFrame JSrollPane. ScrollPane contains a JPanels. But I have problem when I add first JPanel to ScrollPane i see nothing when I add JPanel to JFrame I see JPanels. So where I make mistake? Here code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
public class AddingJPanels {
public static void main(String... args) {
JFrame jF = new JFrame();
PanelMain pM = new PanelMain();
Panel p = new Panel("sas");
JPanel jp = makeJPanel(10);
p.setPreferredSize(new Dimension(600,600));
JScrollPane scroll = new JScrollPane();
scroll.add(jp);
JScrollBar verticalPane = scroll.getVerticalScrollBar();
verticalPane.setValue(verticalPane.getMinimum());
verticalPane.setValue(20);
//scroll.setPreferredSize(new Dimension(570, 300));
scroll.setPreferredSize(new Dimension(400,500));
pM.add(scroll);
//JTabbedPane tB = new JTabbedPane();
//tB.addTab(":]", null, pM, "Tab 3");
jF.add(jp);
jF.setSize(new Dimension(500,500));
jF.setVisible(true);
}
static JPanel makeJPanel(int i){
JPanel jPl = new JPanel();
jPl.setLayout(new GridLayout(i,0));
JLabel lebel;
for(int j=0;j<i;++j){
JPanel p = new JPanel();
p.setLayout(new GridLayout(2,2));
JButton b = new JButton("asa");
p.add(b);
p.setBorder(BorderFactory.createLineBorder(Color.black));
p.setPreferredSize(new Dimension(400,400));
lebel = new JLabel("Napis: "+j);
p.add(lebel);
JTextField jTF = new JTextField("Nic",20);
p.add(jTF);
jPl.add(p);
}
return jPl;
}
}
class Frame extends JFrame {
public Frame() {
super("Frame");
this.setPreferredSize(new Dimension(200, 200));
}
public void see() {
this.setVisible(true);
}
}
class PanelMain extends JPanel {
JButton b = new JButton("press me");
public PanelMain() {
this.add(b);
b.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("Pressed");
}
});
}
}
class Panel extends JPanel {
JLabel l;
public Panel(String s) {
l = new JLabel(s);
this.add(l);
}
}
When I make jF.add(scroll) is no effect.
add() doesn't work on a JScrollPane. You need to use setViewport() or else pass a component in the contstructor.
JScrollPane scroll = new JScrollPane(jp);
or
JScrollPane scroll = new JScrollPane();
scroll.setViewport(jp);
JScrollPane scroll = new JScrollPane(jp);
use:
scroll.setViewportView(jp);

Categories