Add a JScrollPane to a JList - java

I have the following code:
Main:
package PackageMain;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class Main {
public static JFrame frame = new JFrame("Window");
public static PanelOne p1;
public static PanelTwo p2;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 800, 600);
p1 = new PanelOne();
p2 = new PanelTwo();
frame.setVisible(true);
} catch(Exception e){
}
}
});
}
And class 2:
package PackageMain;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class PanelOne{
public PanelOne(){
loadScreen();
}
public void loadScreen(){
JPanel p1 = new JPanel();
DefaultListModel model = new DefaultListModel<String>();
JList list = new JList<String>(model);
//
JScrollPane scroll = new JScrollPane(list);
list.setPreferredSize(null);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
scroll.setViewportView(list);
//
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
System.out.println("You selected " + list.getSelectedValue());
}
});
p1.add(list);
Main.frame.add(p1);
Main.frame.revalidate();
Main.frame.repaint();
for (int i = 0; i < 100; i++){
model.addElement("test");
}
}
I've tried a bunch of stuff to get the JScrollPane to appear on the JList, but it doesn't want to. My best guess is that the model is screwing things up, but this is a simplified version, and the model needs to be there.

JScrollPane scroll = new JScrollPane(list);
You add the JList to the JScrollPane which is correct.
p1.add(list);
But then you add the JList to the JPanel, which is incorrect. A component can only have a single parent, so theJListis removed from theJScrollPane`.
You need to add the JScrollPane to the JPanel:
p1.add( scroll );

You're adding the list to too many components: to the JScrollPane's viewport -- OK, but also to the p1 JPanel -- not OK. Add it only to the viewport, and then add the JScrollPane to the GUI (p1 if need be).
Also:
There's no need to add the JList to the JScrollPane twice, in the constructor and in the viewport view as you're doing, once is enough.
list.setPreferredSize(null);????

Just add Scroll Pane to the frame rather than the List.
change your line with the below code:
Main.frame.add(scroll);

Related

Display PopMenu with java Swing

I have a problem with popapMenu with java swing can you help me
there is my code
package com.bar.menu;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
#SuppressWarnings("serial")
public class PopMenuSample extends JFrame {
public PopMenuSample() {
super("Pop menu exemple");
this.setSize(600, 400);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
JPanel panel = (JPanel) getContentPane();
// the content of the window
JScrollPane LeftjScrollPane = new JScrollPane(new JTree());
LeftjScrollPane.setPreferredSize(new Dimension(200, 0));
JTextArea textArea = new JTextArea();
JScrollPane rightjScrollPane = new JScrollPane(textArea);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
LeftjScrollPane, rightjScrollPane);
panel.add(splitPane);
JPopupMenu popupMenu = this.createPopupMenu();
textArea.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent event) {
if (event.isPopupTrigger()) {
popupMenu.show(event.getComponent(), event.getX(),
event.getY());
}
}
});
}
private JPopupMenu createPopupMenu() {
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem menuNew = new JMenuItem("New File");
popupMenu.add(menuNew);
return popupMenu;
}
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(new NimbusLookAndFeel());
PopMenuSample menuSample = new PopMenuSample();
menuSample.setVisible(true);
}
}
this exemple is very easy (a window is contains two zones on the left is the Jtree() and on the right is textArea in this place i want to activate my problem when is of the right mouse i want to display New File) but i can't to show the popmenu New File in the textArea by the left boton of my mouse
I used java 8
Can you help me and thanks :)
public void mousePressed(MouseEvent event) {
You are only checking the mousePressed event.
The popup trigger can be different for different LAF's.
You also need to check the mouseReleased event.
See the section from the Swing tutorial on Bringing Up a Popup Menu for more information.

Java selectable JLabel

I have made a GUI with a gallery panel which shows images held in JLabels. I need to make JLabel highlightable and then remove it if the user clicks remove. Is there a way or should I change my approach?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class GalleryPanel extends JPanel
{
private static final long serialVersionUID = 1L;
private int currentImage;
private JLabel[] images;
private final int MAX_IMAGES = 12;
private JScrollPane scrollPane;
private JList<JLabel> imageGallery;
private DefaultListModel<JLabel> listModel;
private JPanel imageHolder;
public void init()
{
setLayout(new BorderLayout());
imageHolder = new JPanel();
imageHolder.setLayout(new BoxLayout(imageHolder, BoxLayout.PAGE_AXIS));
imageHolder.setSize(getWidth(), getHeight());
images = new JLabel[MAX_IMAGES];
listModel = new DefaultListModel<JLabel>();
listModel.addElement(new JLabel(new ImageIcon("Untitled.png")));
imageGallery = new JList<JLabel>(listModel);
imageGallery.setBackground(Color.GRAY);
imageGallery.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
imageGallery.setLayoutOrientation(JList.VERTICAL);
imageGallery.setFixedCellHeight(50);
imageGallery.setFixedCellWidth(100);
scrollPane = new JScrollPane(imageHolder);
scrollPane.setBackground(Color.RED);
add(scrollPane, BorderLayout.CENTER);
}
public void addImageToGallery(File file)
{
if ( currentImage <= images.length - 1)
{
BufferedImage bufImage = null;
try
{
bufImage = ImageIO.read(file); //tries to load the image
}
catch (Exception e)
{
System.out.println("Unable to load file " + file.toString());
}
Image resizedImage = bufImage.getScaledInstance(bufImage.getWidth()/5, bufImage.getHeight()/5, Image.SCALE_SMOOTH);
ImageIcon icon = new ImageIcon(resizedImage);
images[currentImage] = new JLabel(icon, JLabel.CENTER);
//images[currentImage].setSize(resized);
//images[currentImage
images[currentImage].setBorder(new TitledBorder(new LineBorder(Color.GRAY,5), file.toString()));
imageHolder.add(images[currentImage]);
revalidate();
repaint();
currentImage++;
}
else
{
throw new ArrayIndexOutOfBoundsException("The gallery is full");
}
}
public final int getMaxImages()
{
return MAX_IMAGES;
}
public Dimension getPreferredSize()
{
return new Dimension(300, 700);
}
}
So you first of call should be the tutorals
How to use Lists
Selecting items in a list
Adding items to and removing items from a list
Which will give you the basic information you need to proceeded.
Based on your available code, you should not be adding a JLabel to the ListModel, you should never add components to data models, as more often than not, Swing components have there own concept of how they will render them.
In your case, you're actually lucky, as the default ListCellRenderer is based on a JLabel and will render Icon's automatically, for example
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
DefaultListModel model = new DefaultListModel();
model.addElement(new ImageIcon("mt01.jpg"));
model.addElement(new ImageIcon("mt02.jpg"));
model.addElement(new ImageIcon("mt03.jpg"));
JList list = new JList(model);
list.setVisibleRowCount(3);
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
System.out.println(list.getSelectedIndex());
}
}
});
JFrame frame = new JFrame("Test");
frame.add(new JScrollPane(list));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

JList position resets to default whenever update occurs

list is to accept input from Action1 this works, however, whenever a new element is added to the list, the list's position moves back to the default top-middle position.
This also occurs when the frame is resized, so as a temporary fix I the line frame.setResizable(false) but I do not want that to be permanent.
How would I fix both of these issues?
import static java.lang.String.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
public class lists
{
static String newUrl;
static DefaultListModel<String> model = new DefaultListModel<String>();
static int listXCoord = 650;
static int listYCoord = 10;
public static void createGUI()
{
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(800,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
JPanel panel = new JPanel();
frame.add(panel);
JButton addurl = new JButton("Add URL");
panel.add(addurl);
addurl.addActionListener(new Action1());
JButton remurl = new JButton("Remove URL");
panel.add(remurl);
//model.addElement("one");
//model.addElement("two");
//model.addElement("three");
JList list = new JList<String>(model);
list.setCellRenderer(new DefaultListCellRenderer());
list.setVisible(true);
list.setLocation(listXCoord, listYCoord);
list.setBackground(new Color(186, 203, 250));
//list.setLocation(650, 10);
panel.add(list);
list.setSize(130, 540);
}
static class Action1 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
newUrl = JOptionPane.showInputDialog("Enter the URL to be Launched");
model.addElement(newUrl);
}
}
public static void main(String[] args)
{
createGUI();
}
}
Basically, you're fighting the layout manager (Flowlayout) and losing. When you add a new element to the JList, the container hierarchy is been revalidated which is causing the layout managers to re-layout the contents of their containers
The basic solution would be to use a different layout, but, JFrame uses a BorderLayout, so instead of adding the JList to the JPanel, you could simply add it to the EAST position of the frame instead
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Lists {
static String newUrl;
static DefaultListModel<String> model = new DefaultListModel<String>();
static int listXCoord = 650;
static int listYCoord = 10;
public static void createGUI() {
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton addurl = new JButton("Add URL");
panel.add(addurl);
addurl.addActionListener(new Action1());
JButton remurl = new JButton("Remove URL");
panel.add(remurl);
//model.addElement("one");
//model.addElement("two");
//model.addElement("three");
JList list = new JList<String>(model);
list.setCellRenderer(new DefaultListCellRenderer());
list.setVisible(true);
list.setLocation(listXCoord, listYCoord);
list.setBackground(new Color(186, 203, 250));
//list.setLocation(650, 10);
frame.add(new JScrollPane(list), BorderLayout.EAST);
frame.setVisible(true);
}
static class Action1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
newUrl = JOptionPane.showInputDialog("Enter the URL to be Launched");
model.addElement(newUrl);
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
createGUI();
}
});
}
}
See Laying Out Components Within a Container, How to Use BorderLayout and How to use FlowLayout for more details.
You should also be calling setVisible last, after all the components have been added to the frame, this reduces the possibilities that some of your components won't be displayed when you think they should be.
JList will also benefit from been contained within a JScrollPane. See How to Use Lists and How to Use Scroll Panes for more details

How can we put value on text field on output screen?

I want to put value in txtf1 at output screen and get it. How can we put value on text field on output screen?
import java.awt.Color;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class demog extends JPanel implements ActionListener{
private TextField textf, txtf1;
public void jhand(){
textf = new TextField();
textf.setSize(40, 40);
textf.setText("20");
textf.setEditable(false);
textf.setBackground(Color.WHITE);
textf.setForeground(Color.BLACK);
//textf.setHorizontalAlignment(SwingConstants.CENTER);
textf.setLocation(15, 15);
//textf.addActionListener(this);
txtf1 = new TextField();
txtf1.setSize(40, 40);
txtf1.getText();
txtf1.setEditable(false);
txtf1.setBackground(Color.WHITE);
txtf1.setForeground(Color.BLACK);
//txtf1.setHorizontalAlignment(SwingConstants.CENTER);
txtf1.setLocation(50, 50);
JFrame frame = new JFrame("demo");
JPanel p = new JPanel();
p.setOpaque(true);
p.setBackground(Color.WHITE);
p.setLayout(null);
frame.setContentPane(p);
frame.setSize(500,500);
frame.setVisible(true);
p.add(textf);
p.add(txtf1);
}
public void actionPerformed(ActionEvent evt) {
String text = textf.getText();
System.out.println(text);
}
public static void main(String... args){
demog g = new demog();
g.jhand();
}
}
You have to change some of your code in order to work. You had some problem in your code which I resolved them for you in the following code. See the comments to learn some in swing ;-)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
// Use upper Case in the start of you class names:
public class Demog extends JPanel implements ActionListener {
private JTextField textf, txtf1;
public Demog() {
jhand();
}
public void jhand() {
setLayout(new FlowLayout()); // Always set the layout before you add components
// you can use null layout, but you have to use setBounds() method
// for placing the components. For an advanced layout see the
// tutorials for GridBagLayout and mixing layouts with each other.
textf = new JTextField(); // Do not mix AWT component with
// Swing (J components. See the packages)
//textf.setSize(40, 40); // Use setPreferredSize instead
textf.setPreferredSize(new Dimension(40, 40));
textf.setText("20");
textf.setEditable(false); // Text fields are for getting data from user
// If you need to show something to user
// use JLabel instead.
textf.setBackground(Color.WHITE);
textf.setForeground(Color.BLACK);
add(textf);
txtf1 = new JTextField();
//txtf1.setSize(40, 40); Use setPreferredSize instead
txtf1.setPreferredSize(new Dimension(40, 40));
txtf1.getText();
txtf1.setEditable(false);
txtf1.setBackground(Color.WHITE);
txtf1.setForeground(Color.BLACK);
add(txtf1);
JButton b = new JButton("Click ME!");
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent evt) {
String text = textf.getText();
JOptionPane.showMessageDialog(Demog.this, "\"textf\" text is: "+text);
}
public static void main(String[] args) {
JFrame frame = new JFrame("demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Demog p = new Demog();
p.setBackground(Color.WHITE);
frame.setContentPane(p);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
Good Luck.

Java Swings Select Tab

I have 4 JPanels. In one of the panel I have a combo Box.Upon selecting "Value A" in combo box Panel2 should be displayed.Similarly if I select "Value B" Panel3 should be selected....
Though action Listener should be used in this context.How to make a call to another tab with in that action listener.
public class SearchComponent
{
....
.
public SearchAddComponent(....)
{
panel = addDropDown(panelList(), "panel", gridbag, h6Box);
panel.addComponentListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ItemSelectable is = (ItemSelectable)actionEvent.getSource();
Object name=selectedString(is);
}
});
}
public static final Vector<String> panelList(){
List<String> panelList = new ArrayList<String>();
panelList.add("A");
panelList.add("B");
panelList.add("C");
panelList.add("D");
panelList.add("E");
panelList.add("F);
Vector<String> panelVector = null;
Collections.copy(panelVector, panelList);
return panelVector;
}
public Object selectedString(ItemSelectable is) {
Object selected[] = is.getSelectedObjects();
return ((selected.length == 0) ? "null" : (ComboItem)selected[0]);
}
}
Use a Card Layout. See the Swing tutorial on How to Use a Card Layout for a working example.
Try This code:
import java.awt.EventQueue;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Container;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class CardLayoutExample {
JFrame guiFrame;
CardLayout cards;
JPanel cardPanel;
public static void main(String[] args) {
//Use the event dispatch thread for Swing components
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new CardLayoutExample();
}
});
}
public CardLayoutExample()
{
guiFrame = new JFrame();
//make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("CardLayout Example");
guiFrame.setSize(400,300);
//This will center the JFrame in the middle of the screen
guiFrame.setLocationRelativeTo(null);
guiFrame.setLayout(new BorderLayout());
//creating a border to highlight the JPanel areas
Border outline = BorderFactory.createLineBorder(Color.black);
JPanel tabsPanel = new JPanel();
tabsPanel.setBorder(outline);
JButton switchCards = new JButton("Switch Card");
switchCards.setActionCommand("Switch Card");
switchCards.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
cards.next(cardPanel);
}
});
tabsPanel.add(switchCards);
guiFrame.add(tabsPanel,BorderLayout.NORTH);
cards = new CardLayout();
cardPanel = new JPanel();
cardPanel.setLayout(cards);
cards.show(cardPanel, "Fruits");
JPanel firstCard = new JPanel();
firstCard.setBackground(Color.GREEN);
addButton(firstCard, "APPLES");
addButton(firstCard, "ORANGES");
addButton(firstCard, "BANANAS");
JPanel secondCard = new JPanel();
secondCard.setBackground(Color.BLUE);
addButton(secondCard, "LEEKS");
addButton(secondCard, "TOMATOES");
addButton(secondCard, "PEAS");
cardPanel.add(firstCard, "Fruits");
cardPanel.add(secondCard, "Veggies");
guiFrame.add(tabsPanel,BorderLayout.NORTH);
guiFrame.add(cardPanel,BorderLayout.CENTER);
guiFrame.setVisible(true);
}
//All the buttons are following the same pattern
//so create them all in one place.
private void addButton(Container parent, String name)
{
JButton but = new JButton(name);
but.setActionCommand(name);
parent.add(but);
}
}

Categories