I have JTextPane, where are inserted 2 JLabels. If any of the labels are clicked, they change content from AAA to clicked.
This code iterates over the elements in the JTextPane:
for(int i = 0; i < tp.getDocument().getLength(); i++) {
System.out.println(((StyledDocument) tp.getDocument()).getCharacterElement(i));
}
How can I access the labels to print "clicked" "AAAA" to the std out?
package texteditor;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.border.BevelBorder;
import javax.swing.border.TitledBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyledDocument;
import javax.swing.JButton;
public class JTextPaneExample extends JPanel {
private JTextPane tp;
public JTextPaneExample() {
setLayout(new BorderLayout(0, 0));
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(null, "Text Content", TitledBorder.LEADING, TitledBorder.TOP, null, null));
add(panel, BorderLayout.CENTER);
panel.setLayout(new BorderLayout(0, 0));
JScrollPane scrollPane = new JScrollPane();
panel.add(scrollPane, BorderLayout.CENTER);
tp = new JTextPane();
tp.setEditable(false);
scrollPane.setViewportView(tp);
JLabel lbl = new JLabel("AAAA ");
lbl.setOpaque(true);
lbl.setBorder(BorderFactory.createLineBorder(Color.black, 1));
lbl.addMouseListener(new LabelAdapter2(lbl));
tp.insertComponent(lbl);
lbl = new JLabel("BBBB ");
lbl.setOpaque(true);
lbl.setBorder(BorderFactory.createLineBorder(Color.black, 1));
lbl.addMouseListener(new LabelAdapter2(lbl));
tp.insertComponent(lbl);
JButton btnNewButton = new JButton("Write content");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
iterateOverContent(tp);
}
});
panel.add(btnNewButton, BorderLayout.SOUTH);
}
private void iterateOverContent(JTextPane tp2) {
for(int i = 0; i < tp.getDocument().getLength(); i++) {
System.out.println(((StyledDocument) tp.getDocument()).getCharacterElement(i));
}
}
private class LabelAdapter2 extends MouseAdapter {
private JLabel lblNewLabel;
public LabelAdapter2(JLabel lbl) {
this.lblNewLabel = lbl;
}
public void mouseClicked(MouseEvent evt) {
lblNewLabel.setText("clicked");
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("GoBoard");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new JTextPaneExample());
frame.setPreferredSize(new Dimension(400, 400));
frame.pack();
frame.setVisible(true);
}
}
i looked into your Question and found a Solution:
just replace your method to iterate the elements of the TextPane with this:
private void iterateOverContent(JTextPane tp2) {
for(int i = 0; i < tp.getDocument().getLength(); i++) {
Element elem = ((StyledDocument) tp.getDocument()).getCharacterElement(i);
AttributeSet as = elem.getAttributes();
if (as.containsAttribute(AbstractDocument.ElementNameAttribute, StyleConstants.ComponentElementName)) {
if(StyleConstants.getComponent(as) instanceof JLabel) {
JLabel myLabel = (JLabel)StyleConstants.getComponent(as);
System.out.println(myLabel.getText());
}
}
System.out.println(((StyledDocument) tp.getDocument()).getCharacterElement(i));
}
}
as you can see, i first save the element into a new variable and then read out all the attributes (yes, the code could be alot shorter, but this way it is more clear - i hope :-) )
After that, we check if the attributes say, that this element is a component.
then the important part: we can get a Component from the attribute set via the StyleConstants.getComponent Method.
Finally just some sanity checks, to see if we can really typecast it to a JLabel.
Best regards,
David
Related
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);
}
});
}
}
I want to wrap a 'Tab' inside a JTabbedPane with JScrollPane.But i can't find a way to do it.This is my code so far ...
"HomeDelivery.java"
import java.sql.*;
import java.util.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.LineBorder;
class HomeDelivery extends JFrame
{
JTabbedPane menu;
JPanel pizza,pastry,drinks;
public HomeDelivery()
{
setSize(800,800);
setVisible(true);
setLayout(new BorderLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
menu = new JTabbedPane();
menu.addTab("Burger",new Burger());
pizza = new JPanel();
menu.addTab("Pizza",pizza);
pastry = new JPanel();
menu.addTab("Pastry",pastry);
drinks = new JPanel();
menu.addTab("Drinks",drinks);
add(menu);
}
public static void main(String args[])
{
HomeDelivery h = new HomeDelivery();
}
}
"Burger.java"
import java.sql.*;
import java.util.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.LineBorder;
class Burger extends JPanel
{
JFrame f;
//JPanel s;
JPanel p[];
JLabel image[];
JLabel name[];
JLabel price[];
JButton b[];
JScrollPane scroll;
int row;
public Burger()
{
p = new JPanel[40];
image = new JLabel[40];
name = new JLabel[40];
price = new JLabel[40];
b = new JButton[40];
for(int i=0;i<40;i++)
{
p[i] = new JPanel();
p[i].setLayout(new BoxLayout(p[i],BoxLayout.LINE_AXIS));
p[i].add(Box.createRigidArea(new Dimension(100,50)));
image[i] = new JLabel("Image");
b[i] = new JButton("ADD");
name[i] = new JLabel("Burger");
price[i] = new JLabel("150");
p[i].add(image[i]);
p[i].add(name[i]);
p[i].add(price[i]);
p[i].add(b[i]);
add(p[i]);
}
scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setPreferredSize(new Dimension(100,50));
add(scroll);
}
}
At the last of the portion of "Burger.java",i tried to add a JScrollPane,though i know it is not the right way i did it . If i was not extending JPanel in "Burger.java" , i'll able to add a scrollpane by doing this :
"JScrollPane scroll = new JScrollPane(JPanel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);"
But,how can i do it in "Burger.java" now ? How can i add a JScrollPane in my "Burger" 'Tab' ? ...
First stop for problems like this is the public Java API documentation. There you would find another constructor of JScrollPane:
http://docs.oracle.com/javase/8/docs/api/javax/swing/JScrollPane.html#JScrollPane-java.awt.Component-int-int-
According to this your problem could be solved by:
scroll = new JScrollPane(p, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
Edit: Don't extend JScrollPane, it is not necessary here.
You can:
Extend JPanel
Add JPanel to JScrollPane through
JScrollPane(Component view, int vsbPolicy, int hsbPolicy)
Add JScrollPane to JTabbedPane
For example:
import java.awt.EventQueue;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
public class TabExample {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
final JFrame frame = new JFrame("Example");
final JTabbedPane tp = new JTabbedPane();
final BurgerTab burgerTab = new BurgerTab();
final JScrollPane scrollPane = new JScrollPane(burgerTab,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
tp.addTab("Burgers", scrollPane);
frame.getContentPane().add(tp);
frame.pack();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setVisible(true);
});
}
private static class BurgerTab extends JPanel {
BurgerTab() {
setLayout(new BoxLayout(this, SwingConstants.VERTICAL));
final JPanel[] burgers = new JPanel[40];
for(int i = 0; i < burgers.length; i++) {
burgers[i] = new JPanel();
burgers[i].add(new JLabel("Burger #" + (i + 1)));
add(burgers[i]);
}
}
}
}
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.
Like this!
And the setOpaque(false); in JTabbedPane didn't work.
Would someone help me please?
part of my code:
for (int x=1; x<6; x++){
newsPanel[x]=new JPanel();
newsPanel[x].add(newspicLabel[x]);
NewsTab.addTab("", Controlbtn, newsPanel[x]);
}
NewsTab.setTabPlacement(JTabbedPane.RIGHT);
NewsTab.setOpaque(false);
thank you very much!!!
I have done the JTabbedPane, but i wanna the tab button placed in the JTabbedPane(Panel) like this ---enter link description here
Here is a sample code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
public class SidePane extends JPanel {
Color c[] = {Color.RED, Color.CYAN, Color.BLACK, Color.BLUE, Color.YELLOW};
public SidePane() {
setLayout(new BorderLayout(10, 10));
ButtonGroup group = new ButtonGroup();
JToggleButton[] buttons = new JToggleButton[5];
JPanel leftTop = new JPanel(new GridLayout(buttons.length, 1, 10, 10));
leftTop.setOpaque(false);
JPanel left = new JPanel();
left.setOpaque(false);
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JToggleButton(i + "");
group.add(buttons[i]);
leftTop.add(buttons[i]);
buttons[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(SidePane.this, ((JToggleButton)e.getSource()).getText()); // Write whatever you like.
}
});
}
buttons[0].setSelected(true);
left.add(leftTop);
add(left, "East");
setBackground(Color.red);
}
public static void main(String[] args) {
JFrame frame = new JFrame("My Side Pane");
frame.add(new SidePane());
frame.setSize(600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
How can I set the font size of the selected text in a JEditorPane (pane) Using a JComboBox?
previously i used:
toolbar.add(new StyledEditorKit.FontSizeAction("12", 12));
But you cant simply have hundreds of buttons.
I don't know the canonical way to do this, but on experimentation, this works:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Document;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyledEditorKit;
public class EditorPaneFun extends JPanel {
private static final Integer[] ITEMS = { 9, 10, 11, 12, 14, 16, 18, 20, 24,
32 };
private JEditorPane editorPane = new JEditorPane();
private JComboBox<Integer> fontBox = new JComboBox<Integer>(ITEMS);
private StyledDocument doc = new DefaultStyledDocument();
private StyledEditorKit styledEditorKit = new StyledEditorKit();
public EditorPaneFun() {
editorPane.setDocument(doc);
editorPane.setEditorKit(styledEditorKit);
JScrollPane scrollpane = new JScrollPane(editorPane);
scrollpane.setPreferredSize(new Dimension(500, 400));
JPanel comboPanel = new JPanel();
comboPanel.add(fontBox);
setLayout(new BorderLayout());
add(scrollpane, BorderLayout.CENTER);
add(comboPanel, BorderLayout.SOUTH);
Document doc = editorPane.getDocument();
for (int i = 0; i < 20; i++) {
int offset = doc.getLength();
String str = "This is line number: " + i + "\n";
try {
doc.insertString(offset, str, null);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
fontBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int size = (Integer) fontBox.getSelectedItem();
Action fontAction = new StyledEditorKit.FontSizeAction(String
.valueOf(size), size);
fontAction.actionPerformed(e);
}
});
}
private static void createAndShowGui() {
JFrame frame = new JFrame("EditorPaneFun");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new EditorPaneFun());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Note that this only works if the Document is a DefaultStyledDocument and if the EditorKit is a StyledEditorKit.