repaint JPanel with every click at JList - java

everytime i click on a JList item, i need to clear + refresh my current panel & load another panel, returned via method 'populateWithButtons()'. temp is an int variable that stores what was clicked at the JList. How do i rectify the following?
list_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent evt) {
//refresh + populate JPanel
Food food = new Food();
JPanel panel2 = new JPanel();
JPanel pane11 = new JPanel();
panel2.add(panel1);
panel1.validate();
panel1.repaint();
panel1.setBounds(153, 74, 281, 269);
panel1.add(food.populateWithButtons(temp));
contentPane.add(panel2);
}

don't to use NullLayout
add ListSelectionListener to JList instead of MouseListener, otherwise you would need to convert point from mouse to Item in JList
use CardLayout instead of add, remove JPanels on runtime, then selection from ListSelectionListener (ListSelectionModel to SINGLE...) to switch prepared card (JPanel with some contents)
EDIT
.
.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class CardlayoutTest {
private Color[] colors = new Color[]{Color.BLACK, Color.RED, Color.GREEN, Color.BLUE};
private JFrame frame = new JFrame();
private JList list = new JList();
private JPanel panel = new JPanel();
private CardLayout card = new CardLayout();
public CardlayoutTest() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setLayout(card);
Vector<String> items = new Vector<String>();
for (int x = 0; x < colors.length; x++) {
JPanel pnl = new JPanel(new BorderLayout());
pnl.setBackground(colors[x]);
panel.add(pnl, colors[x].toString());
items.add(colors[x].toString());
}
list = new JList(items);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
String card = list.getSelectedValue().toString();
CardLayout cL = (CardLayout) (panel.getLayout());
cL.show(panel, card);
}
}
});
frame.add(new JScrollPane(list), BorderLayout.WEST);
frame.add(panel);
frame.setPreferredSize(new Dimension(400, 150));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new CardlayoutTest();
}
});
}
}

move validate() and repaint() after adding to contentPane as in that point it will be redrawed.

Related

How do I get focus for a keypress in a CardLayout?

I had a CardLayout example working correctly with a button, then tried to convert it to work with keypress. I think the problem is that I don't have focus, but I can't set the focus to frame or panel successfully. Thanks!
I tried requestFocusInWindow from the frame and from the first panel shown, and that didn't help. I asked frame.getFocusOwner() and it returned null.
I thought that CardLayout would give the focus to the top element automatically, but while that worked when I had a button, it is not working now.
public class MyCardLayoutExample3 {
public static void main(String[] args){
MyCardLayoutExample3 game = new MyCardLayoutExample3();
game.display();
}
void display() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(300, 200);
CardLayout cardLayout = new CardLayout();
frame.getContentPane().setLayout(cardLayout);
MyGamePanel3 mgp3 = new MyGamePanel3("minigame A", Color.red);
frame.getContentPane().add(mgp3);
frame.getContentPane().add(new MyGamePanel3("minigame B", Color.green));
frame.getContentPane().add(new MyGamePanel3("minigame C", Color.blue));
frame.setVisible(true);
System.out.println("owner: " + frame.getFocusOwner()); //this prints null
}
}
class MyGamePanel3 extends JPanel implements KeyListener{
MyGamePanel3(String text, Color bg){
JLabel textLabel = new JLabel(text);
this.setBackground(bg);
this.add(textLabel);
}
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("keyPressed worked");
}
#Override
public void keyReleased(KeyEvent e) {}
}
Changing to key bindings made the example work easily, thanks Abra. I never got the keyListener to work, despite trying the links above and many other links.
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.WindowConstants;
class MyGamePanel extends JPanel{
MyGamePanel(ActionListener alNext, String text, Color bg){
JButton buttonNext = new JButton("next");
buttonNext.addActionListener(alNext);
JLabel textLabel = new JLabel(text);
this.setBackground(bg);
this.add(textLabel);
this.add(buttonNext);
}
}
public class MyCardLayoutKeyBindingExample {
public static void main(String[] args){
MyCardLayoutKeyBindingExample game = new MyCardLayoutKeyBindingExample();
game.display();
}
void display() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(300, 200);
CardLayout cardLayout = new CardLayout();
//frame.getContentPane().setLayout(cardLayout);
JPanel mainPanel = new JPanel(cardLayout);
frame.add(mainPanel);
ActionListener al1 = e -> cardLayout.next(mainPanel);
mainPanel.add(new MyGamePanel(al1, "minigame A", Color.red));
mainPanel.add(new MyGamePanel(al1, "minigame B", Color.green));
mainPanel.add(new MyGamePanel(al1, "minigame C", Color.blue));
mainPanel.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "space");
Action kp = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
System.out.println("key pressed");
}
};
mainPanel.getActionMap().put("space", kp);
frame.setVisible(true);
}
}

Placing the JPanel in JScrollPane [duplicate]

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);
}
}
}

Update JTable from DefaultTableModel

so what i want to do is update a JTable when a button is pressed. Im using a DefaultTableModel as a source.
Table class:
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.awt.Dimension;
public class TableDemo extends JPanel {
String[] columnNames = {"Tipo","Cantidad"};
DefaultTableModel dtm = new DefaultTableModel(null,columnNames);
final JTable table = new JTable(dtm);
public TableDemo() {
table.setPreferredScrollableViewportSize(new Dimension(500, 700));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
public void addRow(Object [] row)
{
dtm.addRow(row);
}
}
the form class:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
public class MyForm extends JFrame {
JPanel panel;
JLabel label;
JTextField txtName;
JTextField txtSurname;
JButton btnAccept;
TableDemo tb = new TableDemo();
public MyForm(){
initControls();
}
private void initControls() {
setTitle("Form Example");
setSize(600, 400);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(null);
label = new JLabel("Welcome to Swing");
label.setBounds(50, 10, 200, 30);
txtName = new JTextField();
txtName.setBounds(50, 50, 200, 30);
txtSurname = new JTextField();
txtSurname.setBounds(270, 50, 200, 30);
btnAccept = new JButton("Add");
btnAccept.setBounds(120, 100, 150, 30);
onAcceptClick();
TableDemo tablePanel = new TableDemo();
panel.add(label);
panel.add(txtName);
panel.add(txtSurname);
panel.add(btnAccept);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
tablePanel,panel );
splitPane.setDividerLocation(205);
splitPane.setEnabled(false);
getContentPane().add(splitPane);
}
private void onAcceptClick() {
btnAccept.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
tb.addRow(new Object[]{"taza",txtName.getText()});
}
});
public static void main(String[] args) {
//Initilizer init = new Initilizer();
Runnable init = new Runnable() {
#Override
public void run() {
MyForm form = new MyForm();
form.setVisible(true);
}
};
SwingUtilities.invokeLater(init);
}
}
As you can see i call the addRow function but in never updates in the JTable, what am i missing? Thnx
You're creating two TableDemo objects -- one you add to the GUI, tablePanel, the other you add a row to, tb;
// ...
TableDemo tb = new TableDemo(); // TableDemo #1. Never displayed
private void initControls() {
// ...
TableDemo tablePanel = new TableDemo(); // TableDemo #2
// ...
// TableDemo #2 is here added to the GUI
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, tablePanel,panel );
// ...
}
btnAccept.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// here you add a row to the non-displayed TableDemo #1
tb.addRow(new Object[]{"taza",txtName.getText()});
}
});
Solution: Don't do this (obviously)! Use only one TableDemo instance, display it and make changes to it. So get rid of the tablePanel variable and only use the tb variable.
Other problems:
You're using null layouts. While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.

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");

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