How set size of specified String to JTextField? - java

JTextField in JPanel which in turn in JDialog doesn't take specified size. I tried to use BoxLayout and FlowLayout, but still have not achieved the desired size. I.E. I measure the size of String example and set this size to width of JTextField inputCat, but inputCat doesn't take this size, then I call it. How correctly set size of specified String to JTextField? Here is my code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.util.Calendar;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JDesktopPane;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DemoJDialog {
static private JInternalFrame internal;
public static void main(String[] args) {
new DemoJDialog();
}
public DemoJDialog() {
EventQueue.invokeLater(new Runnable() {
#SuppressWarnings({ "rawtypes", "unchecked" })
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
internal = new JInternalFrame("Example", true, true, false, true);
internal.setLayout(new BorderLayout());
internal.setVisible(true);
JDesktopPane dp = new JDesktopPane();
dp.add(internal);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(dp);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
JTextField inputCat = new JTextField();
String example = new String("Some very-very-very-"
+ "very-very-very-very-very-very long string (really long )");
int heightInputCat = inputCat.getSize().height;
FontMetrics FN = internal.getFontMetrics(internal.getFont());
int widthInputCat = SwingUtilities.computeStringWidth(FN, example);
inputCat.setSize(widthInputCat, heightInputCat);
String[] comboString = { "Telecast", "Radiocast" };
JComboBox comboBox = new JComboBox(comboString);
Calendar now = Calendar.getInstance();
SpinnerModel modelSpinner = new SpinnerDateModel(now.getTime(),
null, null, Calendar.MONTH);
final JSpinner spinner = new JSpinner(modelSpinner);
spinner.setEditor(new JSpinner.DefaultEditor(spinner));
JPanel listPane = new JPanel();
listPane.setLayout(new BoxLayout(listPane, BoxLayout.X_AXIS));
listPane.add(comboBox);
listPane.add(Box.createHorizontalStrut(10));
listPane.add(inputCat);
listPane.add(Box.createHorizontalStrut(10));
listPane.add(spinner);
Object[] array = {
new JLabel ("Enter a new category:"),
listPane
};
JOptionPane pane = new JOptionPane(array, JOptionPane.PLAIN_MESSAGE,
JOptionPane.OK_CANCEL_OPTION);
JDialog dialog = pane.createDialog(internal, "Enter a new category:");
dialog.setVisible(true);
}
});
}
}

This works just fine here:
import java.awt.EventQueue;
import java.util.Calendar;
import javax.swing.*;
public class DemoJDialog {
public static void main(String[] args) {
new DemoJDialog();
}
public DemoJDialog() {
EventQueue.invokeLater(new Runnable() {
#SuppressWarnings({"rawtypes", "unchecked"})
#Override
public void run() {
String example = new String("Some very-very-very-"
+ "very-very-very-very-very-very "
+ "long string (really long)");
// create a textfield the size of the string!
JTextField inputCat = new JTextField(example);
inputCat.setCaretPosition(0);
String[] comboString = {"Telecast", "Radiocast"};
JComboBox comboBox = new JComboBox(comboString);
Calendar now = Calendar.getInstance();
SpinnerModel modelSpinner = new SpinnerDateModel(now.getTime(),
null, null, Calendar.MONTH);
final JSpinner spinner = new JSpinner(modelSpinner);
spinner.setEditor(new JSpinner.DefaultEditor(spinner));
JPanel listPane = new JPanel();
listPane.setLayout(new BoxLayout(listPane, BoxLayout.X_AXIS));
listPane.add(comboBox);
listPane.add(Box.createHorizontalStrut(10));
listPane.add(inputCat);
listPane.add(Box.createHorizontalStrut(10));
listPane.add(spinner);
Object[] array = {
new JLabel("Enter a new category:"),
listPane
};
JOptionPane pane = new JOptionPane(array, JOptionPane.PLAIN_MESSAGE,
JOptionPane.OK_CANCEL_OPTION);
JDialog dialog = pane.createDialog(listPane, "Enter a new category:");
dialog.setVisible(true);
}
});
}
}

But JTextField is filled by the example String. And I need empty JTextField with this width
Just use constructor which specifies desired colums Count:
JTextField inputCat = new JTextField(example.length());

Related

How to create an unknown number of Swing components?

I need to display a user-inputted number of tabs (JTabbedPane) (with the same initial content, but the ability to individually change the content), is there a way to create these components procedurally so I don't have to know how many there will be before the user input?
Here is an example of change number of tabse depended on user input:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TabbedPaneTest3 implements Runnable {
private final JTabbedPane tabber = new JTabbedPane();
public static void main(String[] args) {
SwingUtilities.invokeLater(new TabbedPaneTest3());
}
#Override
public void run() {
final JSpinner spinner = new JSpinner(new SpinnerNumberModel(3, 1, 10, 1));
spinner.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
Object val = spinner.getValue();
if (val instanceof Number) {
updateTabsNumber((Number) val);
}
}
});
updateTabsNumber(3);
JFrame frm = new JFrame("Tab Pane");
JPanel panel = new JPanel();
panel.add(new JLabel("Number of tabs: "));
panel.add(spinner);
frm.add(panel, BorderLayout.NORTH);
frm.add(tabber);
frm.setSize(600, 400);
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
private void updateTabsNumber(Number val) {
int count = val.intValue();
tabber.removeAll();
for (int i = 0; i < count; i++) {
String text = "Tab " + (i + 1);
JTextArea area = new JTextArea(10, 30);
area.setText("Initial text for tab: " + (i + 1));
tabber.addTab(text, new JScrollPane(area));
}
}
}

How can add image and text both in combo box in java

Actually I want to add image and text both in combo box . I have use JLabel for that but it doesn't work so how can I achieve this.
Here is my code :
package swing;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ComboBox {
public ComboBox() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("ComboBOx");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = frame.getContentPane();
JLabel ar[] = new JLabel[5];
ar[0] = new JLabel("ganesh",new ImageIcon("/images/g.jpg"),JLabel.HORIZONTAL);
ar[1] = new JLabel("ganes",new ImageIcon("/images/g.jpg"),JLabel.HORIZONTAL);
ar[2] = new JLabel("gane",new ImageIcon("/images/g.jpg"),JLabel.HORIZONTAL);
ar[3] = new JLabel("gan",new ImageIcon("/images/g.jpg"),JLabel.HORIZONTAL);
ar[4] = new JLabel("ga",new ImageIcon("/images/g.jpg"),JLabel.HORIZONTAL);
JComboBox<JLabel> box = new JComboBox<JLabel>(ar);
con.add(box);
con.setBackground(Color.white);
con.setLayout(new FlowLayout());
frame.setVisible(true);
frame.pack();
}
public static void main(String args[]) {
new ComboBox();
}
}
#MadProgrammer Thanks, I find my answer
package swing;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
public class ComboBox {
ImageIcon imageIcon[] = { new ImageIcon("/images/g.jpg"), new ImageIcon("/images/g.jpg"),
new ImageIcon("/images/g.jpg"), new ImageIcon("/images/g.jpg"), new ImageIcon("/images/g.jpg") };
Integer array[] = {1,2,3,4,5};
String names[] = {"img1","img2","img3","img4","img5"};
public ComboBox() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("ComboBOx");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = frame.getContentPane();
ComboBoxRenderar rendrar = new ComboBoxRenderar();
JComboBox box = new JComboBox(array);
box.setRenderer(rendrar);
con.add(box);
con.setLayout(new FlowLayout());
frame.setVisible(true);
frame.pack();
}
public class ComboBoxRenderar extends JLabel implements ListCellRenderer {
#Override
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
int offset = ((Integer)value).intValue() - 1 ;
ImageIcon icon = imageIcon[offset];
String name = names[offset];
setIcon(icon);
setText(name);
return this;
}
}
public static void main(String args[]) {
new ComboBox();
}
}

Java Swing ComboBox not editabl *with MCVE*

I've come across a very weird problem. I had a JPanel which contains JTextFields and JComboBoxes. I can change the JComboBox's when the JPanel loads but as soon as I touch or edit one of the JTextFields it doesn't let me change any of the combobox's...
Here is an MCVE that works. You can use it straight away and you'll see the error.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Main extends JFrame{
private static JTextField s;
private static JTabbedPane tabbedPane;
private static JPanel config;
private static JComboBox<Object> dns;
private static JComboBox<Object> dnsmm;
private static JButton save;
private static String interval;
private static String dnsen;
private static String dnsm;
private static JPanel server;
static JPanel contentPane;
public static void main(String[] args) throws InterruptedException {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Main() throws IOException {
setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 655, 470);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(1, 1));
setContentPane(contentPane);
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
contentPane.add(tabbedPane, BorderLayout.CENTER);
setResizable(false);
server = new JPanel();
server.setLayout(new BorderLayout(0, 0));
ServerPanel();
}
public static void ServerPanel() throws IOException{
tabbedPane.addTab("Manage Server", server);
InputStream in = new FileInputStream("config.dedserver");
Properties p = new Properties();
p.load(in);
in.close();
String saveInt = p.getProperty("saveInterval");
String dnse = p.getProperty("enableDns");
String dnsmo = p.getProperty("serverMode");
config = new JPanel();
server.add(config, BorderLayout.CENTER);
config.setLayout(new BoxLayout(config, BoxLayout.PAGE_AXIS));
//saveint
Panel panel_6 = new Panel();
config.add(panel_6);
JLabel sl = new JLabel("Save Interval (milliseconds): ");
panel_6.add(sl);
s = new JTextField(saveInt);
panel_6.add(s);
s.setColumns(10);
//dnsenabled
Panel panel_9 = new Panel();
config.add(panel_9);
JLabel dnsl = new JLabel("DNS Enabled: ");
panel_9.add(dnsl);
String[] dnsS = { "true", "false" };
dns = new JComboBox<Object>(dnsS);
dns.setSelectedItem(dnse);
dns.addActionListener(dns);
panel_9.add(dns);
//dnsmode
Panel panel_10 = new Panel();
config.add(panel_10);
JLabel dnsml = new JLabel("DNS Server Mode: ");
panel_10.add(dnsml);
String[] dnsm = { "local", "remote" };
dnsmm = new JComboBox<Object>(dnsm);
dnsmm.setSelectedItem(dnsmo);
dnsmm.addActionListener(dnsmm);
panel_10.add(dnsmm);
JPanel panel_7= new JPanel();
config.add(panel_7);
save = new JButton("Save");
panel_7.add(save);
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
errorCheck();
}
});
}
public static void errorCheck(){
interval = s.getText();
dnsen = (String) dns.getSelectedItem();
dnsm = (String) dnsmm.getSelectedItem();
interval = checkValues(interval, "60000", "save interval");
saveValues();
}
public static String checkValues(String value, String def, String name){
String val;
try{
Long.parseLong(value);
val = ""+value+"";
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "You did not enter a valid number for the "+ name + " field! It has been set to the default.");
val = def;
}
return val;
}
public static void saveValues(){
try {
Properties props = new Properties();
props.setProperty("saveInterval", interval);
props.setProperty("serverMode", dnsm);
props.setProperty("enableDns", dnsen);
File f = new File("config.dedserver");
OutputStream out = new FileOutputStream(f);
props.store(out, "");
JOptionPane.showMessageDialog(null, "Saved Config Values!");
}
catch (Exception e ) {
e.printStackTrace();
}
}
}
For it to work you will also need to make a config.dedserver in the root of the project and add the following stuff into it:
#
#Thu Jul 09 08:29:33 BST 2015
saveMethod=h2
startingGems=9999999999
enableDns=true
startingGold=9999999999
startingDarkElixir=9999999999
startingElixir=9999999999
serverMode=remote
saveInterval=30000
maxNameChanges=100
For the entire ServerPanel.java code it is here: http://pastebin.com/tvBENHQa
I'm not sure why this isn't working. Does anyone have any ideas?
Thank you!
A real MVCE would have been stripped down a lot further. It would also have included the properties instead of relying on an external file, e.g.
Properties p = new Properties();
p.put("saveMethod","h2");
p.put("startingGems","9999999999");
p.put("enableDns","true");
p.put("startingGold","9999999999");
p.put("startingDarkElixir","9999999999");
p.put("startingElixir","9999999999");
p.put("serverMode","remote");
p.put("saveInterval","30000");
p.put("maxNameChanges","100");
But apart from that, the code provided at least allowed us to reproduce the problem.
The problem is that you are mixing Swing components with AWT components. You have lines like
Panel panel_10 = new Panel();
in your program. Switch from a java.awt.Panel to a javax.swing.JPanel
JPanel panel_10 = new JPanel();
and your problem will be solved.

Create JInternalFrame with 3 JPanels with variable size and TextFields

I'm trying to make a window with an internal window, using a JSpinner to set integer values, a button to generate the JInternalFrame, passing JSpinner value as parameter.
This JInternalFrame will contain 3 JPannels, where they must have colmuns and rows equals to the value of JSpinner.
So, I thought of using an ArrayList of JFormatedTextFields, and a for to add TextFields to the ArrayList, with a class I've create previously to create JFormatedTextFields with one line, but I don't know how to use the for to add values.
There's the code:
JDialog:
package br.edu.faculdadedosguararapes;
import java.awt.EventQueue;
import javax.swing.JDialog;
import javax.swing.JSpinner;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import java.awt.FlowLayout;
import java.beans.PropertyVetoException;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.JButton;
import javax.swing.SpinnerNumberModel;
import javax.swing.JScrollPane;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Soma extends JDialog {
private JSpinner spinner;
private JPanel panelLinhasEColunas;
private JPanel panelTop;
private JScrollPane scrollPanePrincipal;
private JButton btnGerarMatrizes;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Soma dialog = new Soma();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the dialog.
* #throws PropertyVetoException
*/
public Soma() throws PropertyVetoException {
setTitle("Soma de Matrizes");
setModalityType(ModalityType.APPLICATION_MODAL);
setBounds(100, 100, 573, 447);
panelTop = new JPanel();
getContentPane().add(panelTop, BorderLayout.NORTH);
panelTop.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
panelLinhasEColunas = new JPanel();
panelLinhasEColunas.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Numero de Colunas e Linhas", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(51, 51, 51)));
panelTop.add(panelLinhasEColunas);
spinner = new JSpinner();
spinner.setModel(new SpinnerNumberModel(2, 2, 10, 1));
panelLinhasEColunas.add(spinner);
btnGerarMatrizes = new JButton("Gerar Matrizes");
btnGerarMatrizes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int valor = (Integer) spinner.getValue();
GerarMatrizes soma = new GerarMatrizes();
soma.GerarSoma(valor, scrollPanePrincipal, btnGerarMatrizes);
btnGerarMatrizes.setEnabled(false);
}
});
panelLinhasEColunas.add(btnGerarMatrizes);
scrollPanePrincipal = new JScrollPane();
getContentPane().add(scrollPanePrincipal, BorderLayout.CENTER);
}
}
Class to create JInternalFrame:
package br.edu.faculdadedosguararapes;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.ArrayList;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
public class GerarMatrizes {
public void GerarSoma(int valor, JScrollPane pane, final JButton botao){
ArrayList<JFormattedTextField> campos = new ArrayList<JFormattedTextField>();
JInternalFrame internalFrame = new JInternalFrame("");
internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
#Override
public void internalFrameClosed(InternalFrameEvent arg0) {
botao.setEnabled(true);
}
});
internalFrame.setClosable(true);
internalFrame.setBorder(null);
internalFrame.setVisible(true);
pane.setViewportView(internalFrame);
Component rigidArea = Box.createRigidArea(new Dimension(20, 20));
internalFrame.getContentPane().add(rigidArea, BorderLayout.NORTH);
Component rigidArea_1 = Box.createRigidArea(new Dimension(20, 20));
internalFrame.getContentPane().add(rigidArea_1, BorderLayout.SOUTH);
JPanel panel = new JPanel();
internalFrame.getContentPane().add(panel, BorderLayout.CENTER);
JPanel panelMatrizA = new JPanel();
panelMatrizA.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Matriz A", TitledBorder.CENTER, TitledBorder.TOP, null, null));
panel.add(panelMatrizA);
panelMatrizA.setLayout(new GridLayout(valor, valor, 5, 5));
Component horizontalStrut = Box.createHorizontalStrut(20);
panel.add(horizontalStrut);
JPanel panelMatrizB = new JPanel();
panelMatrizB.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Matriz B", TitledBorder.CENTER, TitledBorder.TOP, null, null));
panel.add(panelMatrizB);
panelMatrizB.setLayout(new GridLayout(valor, valor, 5, 5));
Component horizontalStrut_1 = Box.createHorizontalStrut(20);
panel.add(horizontalStrut_1);
JButton btnSomar = new JButton("Somar");
panel.add(btnSomar);
JPanel panelMatrizRes = new JPanel();
panelMatrizRes.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Matriz Resultante", TitledBorder.CENTER, TitledBorder.TOP, null, null));
panel.add(panelMatrizRes);
panelMatrizRes.setLayout(new GridLayout(valor, valor, 5, 5));
/*for (int i=1; i < valor; i++){
campos.add(i);
}*/
}
}
And class to create JFormattedTextFields:
package br.edu.faculdadedosguararapes;
import javax.swing.JFormattedTextField;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.text.AbstractDocument;
import javax.swing.text.DocumentFilter;
public class GeraObjeto {
public JFormattedTextField novoFtf(JFormattedTextField nome, JPanel panel){
nome = new JFormattedTextField();
nome.setHorizontalAlignment(SwingConstants.CENTER);
nome.setColumns(2);
DocumentFilter filtro = new FiltroNumero();
((AbstractDocument) nome.getDocument()).setDocumentFilter(filtro);
panel.add(nome);
return nome;
}
}
Well, I've changed
ArrayList<JFormattedTextField> campos = new ArrayList<JFormattedTextField>();
to
JFormattedTextField[] camposA = new JFormattedTextField[valor*valor];
GeraObjeto textField = new GeraObjeto();
so with a simple for using the class to create JFormattedTextFields (GeraObjeto) like
for (int i=0; i < valor*valor; i++){
camposA[i] = textField.novoFtf(camposA[i], panelMatrizA);
}
it's working well.

how to insert more than one jComponents into a cell in a jTable

I have a jTable which is populating according to my requirement . I want to add two comboboxes into all the cells in one column. So can anyone help me on this... ![here is my table ][1]
[1]: http://i.stack.imgur.com/nC9RL.jpg I need to add two comboboxes into all the rows of 1 st column. I did my coding into CREATE TABLE button which u can see in the image. here is my code so far : | |
int row=0;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
row=Integer.parseInt(jTextField2.getText());
row=row-1;
DefaultTableModel dtm =(DefaultTableModel) jTable1.getModel();
TableColumn sportColumn = jTable1.getColumnModel().getColumn(1);
JComboBox subject= new JComboBox();
box.addItem("DDD");
box.addItem("CCC");
JComboBox teacher= new JComboBox();
box1.addItem("AAA");
box1.addItem("FFF");
JPanel jPanel = new JPanel();
GroupLayout gl= new GroupLayout(jPanel);
jPanel.setLayout(gl);
jPanel.add(box);
jPanel.add(box1);
dtm.setRowCount(0);
dtm.setRowCount(Integer.parseInt(jTextField1.getText()));
for (int i = 0; i < dtm.getRowCount(); i++) {
row++;
dtm.setValueAt(String.valueOf(row), i, 0);
sportColumn.setCellRenderer(
(TableCellRenderer) new DefaultTableCellRenderer()
.getTableCellRendererComponent(
jTable1, jPanel, true, true, i, 1));
}
}
jButton1===> create table Button / jTextField2===> number starts with / jTextField1===>number of rows
Caverts:
I think this is a crazy idea, personally. If your cell represents a compound object, then I'd be thinking about using a dialog or some other means, but that's me.
Personally, I think this is going to blow up in your face...
Example
The concepts presented are all based on the information from How to use Tables
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.AbstractCellEditor;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumnModel;
public class Enrolement {
public static void main(String[] args) {
new Enrolement();
}
public Enrolement() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
DefaultTableModel model = new DefaultTableModel(new Object[]{"Subject"}, 10);
JTable tbl = new JTable(model);
TableColumnModel columnModel = tbl.getColumnModel();
columnModel.getColumn(0).setCellEditor(new SubjectTableCellEditor());
tbl.setRowHeight(columnModel.getColumn(0).getCellEditor().getTableCellEditorComponent(tbl, "Astronomy/Aurora Sinistra", true, 0, 0).getPreferredSize().height);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(tbl));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class SubjectTableCellEditor extends AbstractCellEditor implements TableCellEditor {
private JComboBox subject;
private JComboBox teacher;
private JPanel editor;
private Map<String, String[]> subjectTeachers = new HashMap<>(25);
public SubjectTableCellEditor() {
subjectTeachers.put("Astronomy", new String[]{"Aurora Sinistra"});
subjectTeachers.put("Charms", new String[]{"Filius Flitwick"});
subjectTeachers.put("Dark Arts", new String[]{"Igor Karkaroff", "Amycus Carrow"});
subjectTeachers.put("Defence Against the Dark Arts", new String[]{"Defence Against the Dark Arts",
"Quirinus Quirrell",
"Gilderoy Lockhart",
"Remus Lupin",
"Bartemius Crouch Jr.",
"Dolores Umbridge",
"Severus Snape",
"Amycus Carrow"});
subjectTeachers.put("Flying", new String[]{"Rolanda Hooch"});
subjectTeachers.put("Herbology", new String[]{"Herbert Beery",
"Pomona Sprout",
"Neville Longbottom"});
subjectTeachers.put("History of Magic", new String[]{"Professor Cuthbert Binns"});
subjectTeachers.put("Potions", new String[]{"Severus Snape",
"Horace Slughorn"});
subjectTeachers.put("Transfiguration", new String[]{"Minerva McGonagall",
"Albus Dumbledore"});
subject = new JComboBox(new String[]{
"Astronomy",
"Charms",
"Dark Arts",
"Defence Against the Dark Arts",
"Flying",
"Herbology",
"History of Magic",
"Potions",
"Transfiguration"
});
teacher = new JComboBox();
editor = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
editor.add(subject, gbc);
editor.add(teacher, gbc);
subject.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
teacher.setModel(new DefaultComboBoxModel(subjectTeachers.get(subject.getSelectedItem())));
}
});
}
#Override
public Object getCellEditorValue() {
return subject.getSelectedItem() + "/" + teacher.getSelectedItem();
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if (value instanceof String) {
String parts[] = value.toString().split("/");
subject.setSelectedItem(parts[0]);
teacher.setSelectedItem(parts[1]);
}
editor.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
return editor;
}
}
}

Categories

Resources