I have a SortedListModel called comandaDescriptionListModel:
private SortedListModel comandaDescriptionListModel;
I have other SortedListModels within my application, but this one fails to add items after 1 element. Just 1 element gets added, and it makes no sense.
btnAddComanda.addActionListener(new ActionListener() {
#SuppressWarnings("unchecked")
#Override
public void actionPerformed(ActionEvent arg0) {
JPanel addPanel = new JPanel();
addPanel.add(new JLabel("Descrição:"));
JTextField comandaDescriptionField = new JTextField();
comandaDescriptionField.setPreferredSize(new Dimension(200, 24));
addPanel.add(comandaDescriptionField);
comandaDescriptionField.requestFocusInWindow();
String comandaName = "C" + Integer.toString(comandaListModel.getSize()+1);
int result = JOptionPane.showConfirmDialog(null, addPanel, "Adicionar comanda",
JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
if (comandaListModel.getSize() == 0) {
productComboBox.setEnabled(true);
btnAddProduct.setEnabled(true);
}
String comandaDescription = comandaDescriptionField.getText();
getCurrentCashRegister().addComanda(comandaName, comandaDescription);
// Comanda description model not adding items,
// Need to fix it
comandaListModel.addElement(comandaName);
comandaDescriptionListModel.addElement(comandaDescription); // HERE <<<
comandaList.setSelectedIndex(comandaList.getLastVisibleIndex());
clearProductComboBox();
updateProductComboBox();
}
}
});
Here's a screenshot:
Under "descrição", it should continue to "b" and "c". I can only think it's a bug. Is there some swing bug that causes problems when appending to more than one list at the same time?
When I deal with multi JList components, I do it in own way and also play with all given facilities.
why not, I use this below source code?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MultiListExample extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField textField;
private JButton addBtn, removeBtn;
private JList<String> list1, list2, list3;
private DefaultListModel<String> dlm1, dlm2, dlm3;
public MultiListExample() {
init();
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException ex) {
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MultiListExample();
}
});
}
private void init() {
setTitle("Multi List Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(450, 100, 300, 300);
textField = new JTextField();
textField.setFont(new Font("Dialog", Font.PLAIN, 15));
add(textField, BorderLayout.PAGE_START);
JPanel panel = new JPanel(new BorderLayout());
add(panel, BorderLayout.CENTER);
addBtn = new JButton("Add Element");
addBtn.setFocusPainted(false);
addBtn.setFont(textField.getFont());
panel.add(addBtn, BorderLayout.PAGE_START);
JPanel innerPanel = new JPanel(new GridLayout(1, 3));
panel.add(innerPanel, BorderLayout.CENTER);
dlm1 = new DefaultListModel<String>();
dlm1.addElement("Apple");
dlm1.addElement("Avocado");
dlm1.addElement("Banana");
dlm1.addElement("Jambul");
list1 = new JList<String>(dlm1);
list1.setFont(textField.getFont());
innerPanel.add(list1);
dlm2 = new DefaultListModel<String>();
dlm2.addElement("Currant");
dlm2.addElement("Cherry");
dlm2.addElement("Cloudberry");
dlm2.addElement("Raisin");
list2 = new JList<String>(dlm2);
list2.setFont(textField.getFont());
list2.setBorder(BorderFactory.createMatteBorder(0, 1, 0, 1, Color.BLACK));
innerPanel.add(list2);
dlm3 = new DefaultListModel<String>();
dlm3.addElement("Dragonfruit");
dlm3.addElement("Durian");
dlm3.addElement("Feijoa");
dlm3.addElement("Fig");
dlm3.addElement("Grape");
list3 = new JList<String>(dlm3);
list3.setFont(textField.getFont());
innerPanel.add(list3);
removeBtn = new JButton("Remove Element");
removeBtn.setFocusPainted(false);
removeBtn.setFont(textField.getFont());
add(removeBtn, BorderLayout.PAGE_END);
list1.setSelectedIndex(dlm1.getSize() - 1);
list2.setSelectedIndex(dlm2.getSize() - 1);
list3.setSelectedIndex(dlm3.getSize() - 1);
textField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
addElementListener();
}
});
addBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
addElementListener();
}
});
removeBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (dlm1.getSize() > 0)
dlm1.remove(list1.getSelectedIndex());
if (dlm2.getSize() > 0)
dlm2.remove(list2.getSelectedIndex());
if (dlm3.getSize() > 0)
dlm3.remove(list3.getSelectedIndex());
if (dlm1.getSize() > 0)
list1.setSelectedIndex(0);
if (dlm2.getSize() > 0)
list2.setSelectedIndex(0);
if (dlm3.getSize() > 0)
list3.setSelectedIndex(0);
}
});
setVisible(true);
}
private void addElementListener() {
if (textField.getText().length() > 2) {
addSortAndRemoveDuplicates(firstLetterCapWord(textField.getText()), list1, dlm1);
addSortAndRemoveDuplicates(firstLetterCapWord(textField.getText()), list2, dlm2);
addSortAndRemoveDuplicates(firstLetterCapWord(textField.getText()), list3, dlm3);
}
}
private void addSortAndRemoveDuplicates(String element, JList<String> list, DefaultListModel<String> model) {
// Here doing all DefaultListModel operations explicitly.
if (!model.contains(element)) {
model.addElement(element);
int size = model.getSize();
String[] elements = new String[size];
for (int i = 0; i < size; i++)
elements[i] = (String) model.getElementAt(i);
Arrays.sort(elements);
model.removeAllElements();
for (int i = 0; i < size; i++)
model.addElement(elements[i]);
list.setSelectedIndex(model.getSize() - 1);
}
}
private String firstLetterCapWord(String str) {
return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
}
}
Related
I am trying to create a JList with a small arrow next to it. When clicked, I want some content associated with the list item shown in the same List/Panel. The picture, I hope, gives a clear idea of what I am trying to achieve.
How do I do this ? Also, what is the small triangle feature to the left known as (for future search tags) ?
I hope this is what you meant. The arrowButton is a JToggleButton which, when activated, displays a JWindow containing information about the selected value of the JList. This JWindow will remain visible until the JToggleButtons state is set back to unselected again. The ListPanel class should be reusable in your code.
Code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JToggleButton;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Example {
public Example() {
JFrame frame = new JFrame();
ArrayList<Object> elements = new ArrayList<Object>();
ArrayList<String> texts = new ArrayList<String>();
ListPanel listPanel = new ListPanel(elements, texts);
JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JTextField elementField = new JTextField(5);
JTextArea textArea = new JTextArea(5, 10);
JPanel panel = new JPanel();
panel.add(new JLabel("Element:"));
panel.add(elementField);
panel.add(Box.createHorizontalStrut(15));
panel.add(new JLabel("Text:"));
panel.add(new JScrollPane(textArea));
int result = JOptionPane.showConfirmDialog(frame, panel, "Element & Text",
JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
listPanel.addElementToList(elementField.getText(), textArea.getText());
}
}
});
JButton deleteButton = new JButton("Remove");
deleteButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (listPanel.getList().getSelectedValue() != null) {
listPanel.removeElementFromList(listPanel.getList().getSelectedValue());
}
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
frame.add(listPanel);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Example();
}
});
}
}
class ListPanel extends JPanel {
private JList<Object> list;
private JToggleButton arrowButton;
private ArrayList<String> texts;
private JWindow popup;
public ListPanel(ArrayList<Object> elements, ArrayList<String> texts) {
this.texts = texts;
popup = new JWindow();
arrowButton = new JToggleButton("\u25B6");
arrowButton.setMargin(new Insets(0, 0, 0, 0));
arrowButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (arrowButton.isSelected()) {
Object value = list.getSelectedValue();
if (value != null) {
JLabel titleLabel = new JLabel(value.toString());
titleLabel.setBackground(Color.WHITE);
titleLabel.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14));
titleLabel.setHorizontalAlignment(JLabel.LEFT);
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
titlePanel.setBackground(Color.WHITE);
titlePanel.add(titleLabel);
JTextPane textPane = new JTextPane();
textPane.setEditable(false);
textPane.setText(texts.get(list.getSelectedIndex()));
JPanel contentPanel = new JPanel(new BorderLayout());
contentPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
contentPanel.add(titlePanel, BorderLayout.NORTH);
contentPanel.add(textPane);
popup.setLocation(arrowButton.getLocationOnScreen().x + arrowButton.getWidth(),
arrowButton.getLocationOnScreen().y);
popup.setContentPane(contentPanel);
popup.revalidate();
popup.pack();
popup.setVisible(true);
}
} else {
if (popup.isVisible()) {
popup.setVisible(false);
}
}
}
});
Timer timer = new Timer(100, null);
timer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (((JFrame) SwingUtilities.getWindowAncestor(ListPanel.this)) != null) {
activateComponentListener();
timer.stop();
}
}
});
timer.start();
list = new JList<Object>(new DefaultListModel<Object>());
for (Object element : elements) {
((DefaultListModel<Object>) list.getModel()).addElement(element);
}
JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.setBackground(Color.WHITE);
buttonPanel.add(arrowButton, BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane(list);
scrollPane.setBorder(null);
setLayout(new BorderLayout());
setBorder(BorderFactory.createLineBorder(Color.BLACK));
add(scrollPane);
add(buttonPanel, BorderLayout.WEST);
}
private void activateComponentListener() {
((JFrame) SwingUtilities.getWindowAncestor(this)).addComponentListener(new ComponentAdapter() {
#Override
public void componentMoved(ComponentEvent arg0) {
if (popup.isVisible()) {
popup.setLocation(arrowButton.getLocationOnScreen().x + arrowButton.getWidth(),
arrowButton.getLocationOnScreen().y);
}
}
});
}
public void removeElementFromList(Object element) {
int index = getElementIndex(element);
if (((DefaultListModel<Object>) getList().getModel()).getElementAt(getElementIndex(element)) != null) {
((DefaultListModel<Object>) getList().getModel()).removeElementAt(index);
getTexts().remove(index);
}
}
public void removeElementFromList(int index) {
if (((DefaultListModel<Object>) getList().getModel()).getElementAt(index) != null) {
((DefaultListModel<Object>) getList().getModel()).removeElementAt(index);
getTexts().remove(index);
}
}
private Integer getElementIndex(Object element) {
for (int i = 0; i < ((DefaultListModel<Object>) getList().getModel()).getSize(); i++) {
if (((DefaultListModel<Object>) getList().getModel()).getElementAt(i).equals(element)) {
return i;
}
}
return null;
}
public void addElementToList(Object element, String text) {
((DefaultListModel<Object>) list.getModel()).addElement(element);
getTexts().add(text);
}
public JList<Object> getList() {
return list;
}
public JToggleButton getArrowButton() {
return arrowButton;
}
public ArrayList<String> getTexts() {
return texts;
}
}
I got 5 JTextareas that stand for output for the sorting I need help regarding displaying or appending iteration in each JTextArea to show the algorithm of sorting.
I have got values of { 5,3,9,7,1,8 }
JTextArea1 |3, 5, 7, 1, 8, 9|
JTextArea2 |3, 5, 1, 7, 8, 9|
JTextArea3 |3, 5, 1, 7, 8, 9|
JTextArea4 |1, 3, 5, 7, 8, 9|
JTextArea5 |1, 3, 5, 7, 8, 9|
My problem is how can I append those values in each textarea.
My code is too long, I'm sorry for that.
My code is not finished yet. I just ended on the button of ascbubble but it can run.
//importing needed packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Sorting extends JPanel
{
// String needed to contain the values then convert into int
int int1,int2,int3,int4,int5,temp;
String str1,str2,str3,str4,str5;
//Buttons needed
JButton ascbubble,descbubble,
ascballoon,descballoon,
clear;
//Output Area of the result sorting
JTextArea output1,output2,
output3,output4,
output5;
//Text Field for user to input numbers
JTextField input1,input2,
input3,input4,
input5;
Sorting()
{
//set color of the background
setBackground(Color.black);
//initialize JButton,JTextArea and JTextField
//JButton
ascbubble = new JButton("Ascending Bubble");
descbubble = new JButton("Descending Bubble");
ascballoon = new JButton("Ascending Balloon");
descballoon = new JButton("Descending Balloon");
clear = new JButton("Clear");
//JTextArea
output1 = new JTextArea(" ");
output2 = new JTextArea(" ");
output3 = new JTextArea(" ");
output4 = new JTextArea(" ");
output5 = new JTextArea(" ");
//JTextField
input1 = new JTextField("00");
input2 = new JTextField("00");
input3 = new JTextField("00");
input4 = new JTextField("00");
input5 = new JTextField("00");
//SetBounds
setLayout(null);
input1.setBounds(120, 50, 30, 20);
input2.setBounds(170, 50, 30, 20);
input3.setBounds(220, 50, 30, 20);
input4.setBounds(270, 50, 30, 20);
input5.setBounds(320, 50, 30, 20);
ascbubble.setBounds(50, 120, 150, 40);
descbubble.setBounds(50, 180, 150, 40);
clear.setBounds(210, 140, 100, 50);
ascballoon.setBounds(320, 120, 150, 40);
descballoon.setBounds(320, 180, 150, 40);
output1.setBounds(20, 300, 80, 100);
output2.setBounds(120, 300, 80, 100);
output3.setBounds(220, 300, 80, 100);
output4.setBounds(320, 300, 80, 100);
output5.setBounds(420, 300, 80, 100);
//add function to the buttons
thehandler handler = new thehandler();
ascbubble.addActionListener(handler);
descbubble.addActionListener(handler);
ascballoon.addActionListener(handler);
descballoon.addActionListener(handler);
//add to the frame
add(input1);
add(input2);
add(input3);
add(input4);
add(input5);
add(output1);
add(output2);
add(output3);
add(output4);
add(output5);
add(ascbubble);
add(descbubble);
add(ascballoon);
add(descballoon);
add(clear);
}
private class thehandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==ascbubble)
{
//input1
str1=input1.getText();
int1=Integer.parseInt(str1);
//input2
str2=input2.getText();
int2=Integer.parseInt(str2);
//input3
str3=input3.getText();
int3=Integer.parseInt(str3);
//input4
str4=input4.getText();
int4=Integer.parseInt(str4);
//input5
str5=input5.getText();
int5=Integer.parseInt(str5);
int contain[]={int1,int2,int3,int4,int5};
//formula for Buble Sort Ascending Order
for ( int pass = 1; pass < contain.length; pass++ )
{
for ( int i = 0; i < contain.length - pass; i++ )
{
if ( contain[ i ] > contain[ i + 1 ] )
{
temp = contain[ i ];
contain[ i ] = contain[ i + 1 ];
contain[ i + 1 ] = temp;
}
}
}
}
}
}
public static void main(String[]args)
{
JFrame frame = new JFrame("Sorting");
frame.add(new Sorting());
frame.setSize(550, 500);
frame.setVisible(true);
}
}
First of all, JTextArea has a simple append method, so you only need one. On each pass, you simply need to generate a new String which represents the current state of the array
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.StringJoiner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Sort {
public static void main(String[] args) {
new Sort();
}
public Sort() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField fieldValues;
private JTextArea fieldResults;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(2, 2, 2, 2);
fieldValues = new JTextField(20);
fieldResults = new JTextArea(10, 20);
add(fieldValues, gbc);
JButton btn = new JButton("Sort");
add(btn, gbc);
add(new JScrollPane(fieldResults), gbc);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String[] values = fieldValues.getText().split(",");
int[] contain = new int[values.length];
for (int index = 0; index < values.length; index++) {
contain[index] = Integer.parseInt(values[index].trim());
}
for (int pass = 1; pass < contain.length; pass++) {
for (int i = 0; i < contain.length - pass; i++) {
if (contain[i] > contain[i + 1]) {
int temp = contain[i];
contain[i] = contain[i + 1];
contain[i + 1] = temp;
StringJoiner sj = new StringJoiner(", ", "", "\n");
for (int value : contain) {
sj.add(Integer.toString(value));
}
fieldResults.append(sj.toString());
}
}
}
}
});
}
}
}
Now, the problem with this is, the larger the dataset, the more time it will take to sort, this will mean the UI will pause until the sort is completed
One solution would be to use a SwingWorker, for example...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import java.util.StringJoiner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Sort {
public static void main(String[] args) {
new Sort();
}
public Sort() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField fieldValues;
private JTextArea fieldResults;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(2, 2, 2, 2);
fieldValues = new JTextField(20);
fieldResults = new JTextArea(10, 20);
add(fieldValues, gbc);
JButton btn = new JButton("Sort");
add(btn, gbc);
add(new JScrollPane(fieldResults), gbc);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
btn.setEnabled(false);
String text = fieldValues.getText();
SortWorker worker = new SortWorker(text);
worker.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
String name = evt.getPropertyName();
if ("state".equals(name)) {
if (worker.getState() == SwingWorker.StateValue.DONE) {
btn.setEnabled(true);
}
}
}
});
worker.execute();
}
});
}
public class SortWorker extends SwingWorker<int[], String> {
private String text;
public SortWorker(String text) {
this.text = text;
}
#Override
protected void process(List<String> chunks) {
for (String value : chunks) {
fieldResults.append(value);
}
}
#Override
protected int[] doInBackground() throws Exception {
String[] values = text.split(",");
int[] contain = new int[values.length];
for (int index = 0; index < values.length; index++) {
contain[index] = Integer.parseInt(values[index].trim());
}
for (int pass = 1; pass < contain.length; pass++) {
for (int i = 0; i < contain.length - pass; i++) {
if (contain[i] > contain[i + 1]) {
int temp = contain[i];
contain[i] = contain[i + 1];
contain[i + 1] = temp;
StringJoiner sj = new StringJoiner(", ", "", "\n");
for (int value : contain) {
sj.add(Integer.toString(value));
}
publish(sj.toString());
}
}
}
return contain;
}
}
}
}
I want to display a list of strings in a window and i tried to use a JPanel surounded by JScrollPane because the size of the strings list is unknown. The problem is that the window is displaying the text Horizontally and i want to be displayed line after line. How to fix this? This is the code i've written so far.
package interface_classes;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
public class ErrorMessageW {
private JFrame errorMessageW;
private ArrayList<String> errors;
private JPanel panel;
private JScrollPane scrollPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
final ArrayList<String> err = new ArrayList<>();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ErrorMessageW window = new ErrorMessageW(err);
window.errorMessageW.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ErrorMessageW(ArrayList<String> err) {
errors = err;
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
errorMessageW = new JFrame();
errorMessageW.setTitle("Unfilled forms");
errorMessageW.setBounds(100, 100, 367, 300);
errorMessageW.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnOk = new JButton("OK");
btnOk.setBounds(239, 208, 89, 23);
btnOk.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
errorMessageW.dispose();
}
});
errorMessageW.getContentPane().setLayout(null);
errorMessageW.getContentPane().add(btnOk);
scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBounds(10, 10, 330, 175);
errorMessageW.getContentPane().add(scrollPane);
panel = new JPanel();
for(String s : errors){
JTextArea text = new JTextArea(1,20);
text.setText(s);
text.setFont(new Font("Verdana",1,10));
text.setForeground(Color.RED);
panel.add(text);
}
scrollPane.setViewportView(panel);
}
public JFrame getErrorMessageW() {
return errorMessageW;
}
public void setErrorMessageW(JFrame errorMessageW) {
this.errorMessageW = errorMessageW;
}
}
This is what i get
This is what i want, but using the JScrollPane:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.ArrayList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class ErrorMessageW {
private JFrame errorMessageW;
private ArrayList<String> errors;
private JPanel panel;
private JScrollPane scrollPane;
private JTextArea errorMessage = new JTextArea(3, 30);
/**
* Launch the application.
*/
public static void main(String[] args) {
final ArrayList<String> err = new ArrayList<String>();
err.add("Short String");
err.add("A very very very very very very very very very very very "
+ "very very very very very very very very very very very "
+ "very very very very very very very very long String");
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ErrorMessageW window = new ErrorMessageW(err);
window.errorMessageW.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ErrorMessageW(ArrayList<String> err) {
errors = err;
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
errorMessageW = new JFrame();
JPanel contentPane = new JPanel(new BorderLayout(5, 15));
contentPane.setBorder(new EmptyBorder(10, 10, 10, 10));
errorMessage.setLineWrap(true);
errorMessage.setWrapStyleWord(true);
JScrollPane jsp = new JScrollPane(
errorMessage,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
);
contentPane.add(jsp, BorderLayout.PAGE_START);
errorMessageW.add(contentPane);
errorMessageW.setTitle("Unfilled forms");
errorMessageW.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JButton btnOk = new JButton("OK");
btnOk.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
errorMessageW.dispose();
}
});
JPanel btnConstrain = new JPanel(new FlowLayout(FlowLayout.TRAILING));
btnConstrain.add(btnOk);
contentPane.add(btnConstrain, BorderLayout.PAGE_END);
scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
contentPane.add(scrollPane, BorderLayout.CENTER);
DefaultListModel<String> listModel = new DefaultListModel<String>();
for (String s : errors) {
listModel.addElement(s);
}
final JList<String> errorList = new JList<String>(listModel);
Dimension preferredSize = new Dimension(errorMessage.getPreferredSize().width,200);
errorList.setPreferredSize(preferredSize);
ListSelectionListener errorSelect = new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
errorMessage.setText(errorList.getSelectedValue());
}
};
errorList.addListSelectionListener(errorSelect);
scrollPane.setViewportView(errorList);
errorMessageW.pack();
}
public JFrame getErrorMessageW() {
return errorMessageW;
}
public void setErrorMessageW(JFrame errorMessageW) {
this.errorMessageW = errorMessageW;
}
}
First of all, you could try, instead of creating multiple instances of JTextArea, using only one and appending each error to it like this:
JTextArea text = new JTextArea(1, 20);
text.setFont(new Font("Verdana",1,10));
text.setForeground(Color.RED);
for(String s : errors) {
text.append(s + "\n");
}
panel.add(text);
However, if you do need to create more than one JTextArea, you can use a BoxLayout like this:
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
You just need to write a function that adds a new line character as an element of your ArrayList after every other element in your ArrayList of errors. Below i did a test program that shows how that can be done. I also checked the oputput. Just paste the code and understand the working of code. All the best!
import java.util.ArrayList;
public class TestingArraylist {
static ArrayList<String> errors = new ArrayList<String>();
static final String[] warnings = new String[]{"Error 0 occured","Error 1 occured","Error 2 occured","Error 3 occured","Error 4 occured"};;
public static void addNewLineToArrayList(String[] elementofarraylist){
for(int i =0;i<elementofarraylist.length;i++){
errors.add(elementofarraylist[i]);
errors.add("\n"); //this is what you need to do!
}
}
public static void main(String[] args) {
addNewLineToArrayList(warnings);
//checking below if our work has really succeded or not!!
for(int j =0;j<errors.size();j++){
System.out.print(errors.get(j));
}
}
}
So, I have a program with JTextArea with DocumentFilter. It should (among other things) filter out tab characters and prevent them to be entered in the JTextArea completely.
Well, it works well when I type, but I can still paste it in. i shouldn't be able to, according to the code...
Below is kind of a SSCCE. Just run it, press ctrl+n and enter. All the colored fileds are JTextAreas with same DocumentFilter. The filter itself is the first class (DefaultDocFilter), only thing you need to look into.
package core;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.border.Border;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.JTextComponent;
class DefaultDocFilter extends DocumentFilter
{
public void insertString(FilterBypass fb, int offs,String str, AttributeSet a) throws BadLocationException
{
if ((fb.getDocument().getLength() + str.length()) <= 200)
{
str.replaceAll("\n", " ");
str.replaceAll("\t", " ");
System.out.print(str);
fb.insertString(offs, str, a);
}
else
{
int spaceLeft = 200 - fb.getDocument().getLength();
if (spaceLeft <= 0)
return;
str.substring(0, spaceLeft);
str.replaceAll("\n", " ");
str.replaceAll("\t", " ");
fb.insertString(offs, str, a);
}
}
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException
{
if (str.equals("\n") || str.equals("\t"))
{
str = "";
}
if ((fb.getDocument().getLength() + str.length() - length) <= 200)
{
str.replaceAll("\n", " ");
str.replaceAll("\t", " ");
fb.replace(offs, length, str, a);
}
else
{
int spaceLeft = 200 - fb.getDocument().getLength() + length;
if (spaceLeft <= 0)
return;
fb.replace(offs, length, str.substring(0,spaceLeft).replaceAll("\n", " "), a);
}
}
}
#SuppressWarnings("serial")
class DefaultFont extends Font
{
public DefaultFont()
{
super("Arial", PLAIN, 20);
}
}
#SuppressWarnings("serial")
class Page extends JPanel
{
public JPanel largePage;
public int content;
public Page(JPanel panel, int index)
{
largePage = new JPanel();
largePage.setLayout(new BoxLayout(largePage, BoxLayout.Y_AXIS));
largePage.setMaximumSize(new Dimension(794, 1123));
largePage.setPreferredSize(new Dimension(794, 1123));
largePage.setAlignmentX(Component.CENTER_ALIGNMENT);
largePage.setBackground(Color.WHITE);
largePage.add(new Box.Filler(new Dimension(0, 96), new Dimension(0, 96), new Dimension(0, 96)));
setMaximumSize(new Dimension(556, 931));
setBackground(Color.LIGHT_GRAY);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(new Box.Filler(new Dimension(556, 0), new Dimension(556, 931), new Dimension(556, 931)));
largePage.add(this);
largePage.add(new Box.Filler(new Dimension(0, 96), new Dimension(0, 96), new Dimension(0, 96)));
panel.add(largePage, index);
panel.add(new Box.Filler(new Dimension(0, 40), new Dimension(0, 40), new Dimension(0, 40)));
content = 0;
Main.pages.add(this);
}
}
#SuppressWarnings("serial")
class Heading extends JTextArea
{
public boolean type;
public AbstractDocument doc;
public ArrayList<JPanel/*Question*/> questions;
public ArrayList<JPanel/*List*/> list;
public Heading(boolean segment, Page page)
{
type = segment;
setBackground(Color.RED);
setFont(new Font("Arial", Font.BOLD, 20));
Border in = BorderFactory.createDashedBorder(Color.BLACK);
Border out = BorderFactory.createMatteBorder(0, 0, 10, 0, Color.WHITE);
setBorder(BorderFactory.createCompoundBorder(out, in));
setLineWrap(true);
setWrapStyleWord(true);
setText("Heading 1 Heading 1 Heading 1 Heading 1");
doc = (AbstractDocument)this.getDocument();
doc.setDocumentFilter(new DefaultDocFilter());
page.add(this, 0);
page.content++;
if (type)
{
questions = new ArrayList<JPanel>();
}
else
{
list = new ArrayList<JPanel>();
}
}
}
#SuppressWarnings("serial")
class Question extends JPanel
{
public JPanel questionArea, numberArea, answerArea;
public JLabel number;
public JTextArea question;
public AbstractDocument doc;
public Question(Page page, int pageNum, int index)
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.WHITE));
questionArea = new JPanel();
questionArea.setLayout(new BoxLayout(questionArea, BoxLayout.X_AXIS));
questionArea.setBorder(BorderFactory.createMatteBorder(0, 0, 8, 0, Color.WHITE));
numberArea = new JPanel();
numberArea.setLayout(new BorderLayout());
numberArea.setBackground(Color.WHITE);
number = new JLabel(pageNum+". ", JLabel.RIGHT);
number.setMinimumSize(new Dimension(100, 20));
number.setPreferredSize(new Dimension(100, 20));
number.setMaximumSize(new Dimension(100, 20));
number.setFont(new Font("Arial", Font.PLAIN, 17));
numberArea.add(number, BorderLayout.NORTH);
questionArea.add(numberArea);
question = new JTextArea();
question.setFont(new Font("Arial", Font.PLAIN, 17));
question.setBorder(BorderFactory.createDashedBorder(Color.BLACK));
question.setLineWrap(true);
question.setWrapStyleWord(true);
question.setBackground(Color.GREEN);
question.setText("Is this the first question?");
doc = (AbstractDocument)question.getDocument();
doc.setDocumentFilter(new DefaultDocFilter());
questionArea.add(question);
add(questionArea);
answerArea = new JPanel();
answerArea.setLayout(new BoxLayout(answerArea, BoxLayout.Y_AXIS));
add(answerArea);
page.add(this, index);
page.content++;
}
}
#SuppressWarnings("serial")
class Answer extends JPanel
{
public JPanel letterArea;
public JLabel letter;
public JTextArea answer;
public AbstractDocument doc;
public Answer(Question q, int index)
{
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
letterArea = new JPanel();
letterArea.setLayout(new BorderLayout());
letterArea.setBackground(Color.WHITE);
letter = new JLabel((char)(index+96)+") ", JLabel.RIGHT);
letter.setMinimumSize(new Dimension(150, 20));
letter.setPreferredSize(new Dimension(150, 20));
letter.setMaximumSize(new Dimension(150, 20));
letter.setFont(new Font("Arial", Font.PLAIN, 17));
letterArea.add(letter, BorderLayout.NORTH);
add(letterArea);
answer = new JTextArea();
answer.setFont(new Font("Arial", Font.PLAIN, 17));
Border in = BorderFactory.createDashedBorder(Color.BLACK);
Border out = BorderFactory.createMatteBorder(0, 0, 5, 0, Color.WHITE);
answer.setBorder(BorderFactory.createCompoundBorder(out, in));
answer.setLineWrap(true);
answer.setWrapStyleWord(true);
answer.addKeyListener(new KeyListener()
{
#Override
public void keyPressed(KeyEvent arg0)
{
System.out.print(((JTextComponent) arg0.getSource()).getText());
if (arg0.getKeyCode() == KeyEvent.VK_ENTER)
{
String JLabelText = ((JLabel) ((JPanel) ((JPanel) ((Component) arg0.getSource()).getParent()).getComponent(0)).getComponent(0)).getText();
int ansNum = (int)JLabelText.charAt(0)-95;
if (ansNum < 6)
{
Answer k = new Answer((Question) ((JTextArea) arg0.getSource()).getParent().getParent().getParent(), ansNum);
k.answer.grabFocus();
Main.mWindow.repaint();
Main.mWindow.validate();
}
}
}
public void keyReleased(KeyEvent arg0) {}
public void keyTyped(KeyEvent arg0) {}
});
doc = (AbstractDocument)answer.getDocument();
doc.setDocumentFilter(new DefaultDocFilter());
answer.setBackground(Color.PINK);
add(answer);
q.answerArea.add(this, index-1);
}
}
public class Main
{
public static Properties config;
public static Locale currentLocale;
public static ResourceBundle lang;
public static JFrame mWindow;
public static JMenuBar menu;
public static JMenu menuFile, menuEdit;
public static JMenuItem itmNew, itmClose, itmLoad, itmSave, itmSaveAs, itmExit, itmCut, itmCopy, itmPaste, itmProperties;
public static JDialog newDoc;
public static JLabel newDocText1, newDocText2;
public static JRadioButton questions, list;
public static ButtonGroup newDocButtons;
public static JButton newDocOk;
public static Boolean firstSegment;
public static JPanel workspace;
public static JScrollPane scroll;
public static ArrayList<Page> pages;
public static void newDocumentForm()
{
//new document dialog
mWindow.setEnabled(false);
newDoc = new JDialog(mWindow, "newDoc");
newDoc.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
newDoc.addWindowListener(new WindowListener ()
{
public void windowActivated(WindowEvent arg0) {}
public void windowClosing(WindowEvent arg0)
{
mWindow.toFront();
newDocText1 = null;
newDocText2 = null;
questions = null;
list = null;
newDocButtons = null;
newDocOk = null;
newDoc.dispose();
mWindow.setEnabled(true);
}
public void windowClosed(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
});
newDoc.setSize(400, 200);
newDoc.setLocationRelativeTo(null);
newDoc.setResizable(false);
newDoc.setLayout(null);
newDoc.setVisible(true);
newDocText1 = new JLabel("newDocText1");
newDocText1.setBounds(5, 0, 400, 20);
newDocText2 = new JLabel("newDocText2");
newDocText2.setBounds(5, 20, 400, 20);
newDoc.add(newDocText1);
newDoc.add(newDocText2);
firstSegment = true;
questions = new JRadioButton("questions");
questions.setSelected(true);
questions.setFocusPainted(false);
questions.setBounds(10, 60, 400, 20);
questions.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
firstSegment = true;
}
});
list = new JRadioButton("list");
list.setFocusPainted(false);
list.setBounds(10, 80, 400, 20);
list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
firstSegment = false;
}
});
newDoc.add(questions);
newDoc.add(list);
newDocButtons = new ButtonGroup();
newDocButtons.add(questions);
newDocButtons.add(list);
newDocOk = new JButton("ok");
newDocOk.addKeyListener(new KeyListener()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
newDocOk.doClick();
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
});
newDocOk.setFocusPainted(false);
newDocOk.setBounds(160, 120, 80, 40);
newDocOk.setMnemonic(KeyEvent.VK_ACCEPT);
newDocOk.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
createNewDocument();
}
});
newDoc.add(newDocOk);
newDocOk.requestFocus();
}
public static void createNewDocument()
{
//dispose of new document dialog
mWindow.toFront();
newDocText1 = null;
newDocText2 = null;
questions = null;
list = null;
newDocButtons = null;
newDocOk = null;
newDoc.dispose();
mWindow.setEnabled(true);
//create document display
workspace = new JPanel();
workspace.setLayout(new BoxLayout(workspace, BoxLayout.PAGE_AXIS));
workspace.add(new Box.Filler(new Dimension(0, 40), new Dimension(0, 40), new Dimension(0, 40)));
workspace.setBackground(Color.BLACK);
scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.getVerticalScrollBar().setUnitIncrement(20);
scroll.setViewportView(workspace);
pages = new ArrayList<Page>();
Page p = new Page(workspace, 1);
new Heading(true, p);
Question q = new Question(p, 1, 1);
new Answer(q, 1);
mWindow.add(scroll, BorderLayout.CENTER);
mWindow.repaint();
mWindow.validate();
}
public static void main(String[] args) throws FileNotFoundException, IOException
{
//create main window
mWindow = new JFrame("title");
mWindow.setSize(1000, 800);
mWindow.setMinimumSize(new Dimension(1000, 800));
mWindow.setLocationRelativeTo(null);
mWindow.setLayout(new BorderLayout());
mWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mWindow.setVisible(true);
//create menu bar
menu = new JMenuBar();
menuFile = new JMenu("file");
menuEdit = new JMenu("edit");
itmNew = new JMenuItem("new");
itmNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
itmNew.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
newDocumentForm();
}
});
itmClose = new JMenuItem("close");
itmClose.setActionCommand("Close");
itmClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
itmLoad = new JMenuItem("load");
itmLoad.setActionCommand("Load");
itmLoad.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
itmSave = new JMenuItem("save");
itmSave.setActionCommand("Save");
itmSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
itmSaveAs = new JMenuItem("saveAs");
itmSaveAs.setActionCommand("SaveAs");
itmExit = new JMenuItem("exit");
itmExit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Add confirmation window!
System.exit(0);
}
});
itmCut = new JMenuItem("cut");
itmCut.setActionCommand("Cut");
itmCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));
itmCopy = new JMenuItem("copy");
itmCopy.setActionCommand("Copy");
itmCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
itmPaste = new JMenuItem("paste");
itmPaste.setActionCommand("Paste");
itmPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));
itmProperties = new JMenuItem("properties");
itmProperties.setActionCommand("properties");
itmProperties.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
menuFile.add(itmNew);
menuFile.add(itmClose);
menuFile.addSeparator();
menuFile.add(itmLoad);
menuFile.addSeparator();
menuFile.add(itmSave);
menuFile.add(itmSaveAs);
menuFile.addSeparator();
menuFile.add(itmExit);
menuEdit.add(itmCut);
menuEdit.add(itmCopy);
menuEdit.add(itmPaste);
menuEdit.addSeparator();
menuEdit.add(itmProperties);
menu.add(menuFile);
menu.add(menuEdit);
//create actionListener for menus
mWindow.add(menu, BorderLayout.NORTH);
mWindow.repaint();
mWindow.validate();
}
}
Why don't you assign String into DocumentFilter
str = str.replaceAll()?
I am trying to make one column from JTable, invisible by setting width to zero but it could not happen and it remain visible to width = 15. Here is code -
public void restoreColumnWithWidth(int column, int width) {
try {
TableColumn tableColumn = table.getColumnModel().getColumn(column);
table.getTableHeader().setResizingColumn(tableColumn);
tableColumn.setWidth(width);
tableColumn.setMaxWidth(width);
tableColumn.setMinWidth(width);
tableColumn.setPreferredWidth(width);
} catch (Exception ex) {
}
}
What is wrong with the code ?
not, never to remove TableColumn from TableModel, this is wrong suggestion, instead of to use built-in method JTable#removeColumn(TableColumn aColumn),
notice, this method remove column only from View, in the model is removed column still presents, and you can revert that, visible the removed column by using JTable#addColumn(TableColumn aColumn)
EDIT
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Stack;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
public class TableRowHeight {
private static final long serialVersionUID = 1L;
private JFrame frame = new JFrame("p*s*s*s*s*t*t");
private String[] columnNames = {"one", "two", "Playing with", "four", "five",};
private String[][] data = {
{"aaaaaa", "bbbbbb", "cccccc", "dddddd", "eeeeeee",},
{"bbbbbb", "cccccc", "dddddd", "eeeeeee", "aaaaaa",},
{"cccccc", "dddddd", "eeeeeee", "aaaaaa", "bbbbbb",},
{"dddddd", "eeeeeee", "aaaaaa", "bbbbbb", "cccccc",},
{"eeeeeee", "aaaaaa", "bbbbbb", "cccccc", "dddddd",}};
private JTable table = new JTable(new DefaultTableModel(data, columnNames));
private TableColumnModel tcm = table.getColumnModel();
private Stack<TableColumn> colDeleted = new Stack<TableColumn>();
private JButton restoreButton = new JButton("Restore Column Size");
private JButton hideButton = new JButton("Set Column Size to Zero");
private JButton deleteButton = new JButton("Delete Column");
private JButton addButton = new JButton("Restore Column");
public TableRowHeight() {
table.setRowMargin(4);
table.setRowHeight(30);
table.setFont(new Font("SansSerif", Font.BOLD + Font.PLAIN, 20));
JScrollPane scrollPane = new JScrollPane(table);
for (int i = 0; i < (tcm.getColumnCount()); i++) {
tcm.getColumn(i).setPreferredWidth(100);
}
table.setPreferredScrollableViewportSize(table.getPreferredSize());
restoreButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tcm.getColumn(2).setPreferredWidth(100);
}
});
hideButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tcm.getColumn(2).setPreferredWidth(000);
}
});
deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (table.getColumnCount() > 0) {
TableColumn colToDelete = table.getColumnModel().getColumn(table.getColumnCount() - 1);
table.removeColumn(colToDelete);
table.validate();
colDeleted.push(colToDelete);
addButton.setEnabled(true);
} else {
deleteButton.setEnabled(false);
}
}
});
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (colDeleted.size() > 0) {
table.addColumn(colDeleted.pop());
table.validate();
deleteButton.setEnabled(true);
} else {
addButton.setEnabled(false);
}
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(hideButton);
btnPanel.add(restoreButton);
btnPanel.add(deleteButton);
btnPanel.add(addButton);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(btnPanel, BorderLayout.SOUTH);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
TableRowHeight frame = new TableRowHeight();
}
});
}
}
EDIT2
you have to check too
JTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JTable.getTableHeader().setReorderingAllowed(false);
If it should be removed, and not just hidden: Remove it from the table-model.
If it only should be hidden and later shown, you can remove the TableColumn from the TableColumnModel
Making the column height 0 is a bit bogus.