Display a Data From JTable into TextArea - swing

How can i display a data from a 'specific column' of JTable when a row is selected (table.getvalue(table.getValueAt(table.getSelectedRow(),'specific column'))into a Textarea.
is there any Listener to make this work ?i mean in every selection the textarea must be updated and take the value of specific column where the row is selected .

Add a MouseListener to the table. When ever user selects the cell then just get the data and set the text to the TextField. You can see the demo by running the following code.
private void createUI() {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
Object[][] data = {{"a", "b"}, {"c", "d"}, {"e", "f"}};
Object[] columnNames = {"Col-1", "Col-2"};
final JTable table = new JTable(data, columnNames);
JPanel btnPnl = new JPanel(new FlowLayout(FlowLayout.LEFT));
btnPnl.add(new JLabel("Selected Value: "));
final JTextField text = new JTextField(10);
btnPnl.add(text);
table.getTableHeader().setReorderingAllowed(false);
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if(table.getSelectedRow() != -1 && table.getSelectedColumn() != -1) {
String selData = table.getValueAt(table.getSelectedRow(), table.getSelectedColumn()).toString();
text.setText(selData);
}
}
});
frame.add(table.getTableHeader(), BorderLayout.NORTH);
frame.add(table, BorderLayout.CENTER);
frame.add(btnPnl, BorderLayout.SOUTH);
frame.setTitle("Table to TextField Example.");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}

Related

Swing UI Delay adding and removing elements

I have a form stored in both the inputWidget and the outputWidget. The buttons addInput and addOutput will show two different forms in the secondaryInOutPanel.
However there is a significant delay when moving between the form by clicking the buttons. In fact it changes when I attempting to click on the form. And there is still some visible drawings from the pervious form.
I tried using SwingUtilities but that caused the delay to be worst.
secondaryInOutPanel = new JPanel(new BorderLayout());
secondaryInOutPanel.setMinimumSize(new Dimension(200,400));
JPanel btnPanel = new JPanel();
outinPanel.add(btnPanel, BorderLayout.NORTH);
JButton addInput = new JButton("Add Input");
btnPanel.add(addInput);
addInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
secondaryInOutPanel.removeAll();
secondaryInOutPanel.add(inputWidget, BorderLayout.NORTH);
JButton addBtn = new JButton("Save Input");
secondaryInOutPanel.add(addBtn, BorderLayout.SOUTH);
addBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
});
}
});
JButton addOutput = new JButton("Add Output");
btnPanel.add(addOutput);
addOutput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
secondaryInOutPanel.removeAll();
secondaryInOutPanel.add(outputWidget, BorderLayout.NORTH);
JButton addBtn = new JButton("Save Output");
secondaryInOutPanel.add(addBtn, BorderLayout.SOUTH);
addBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
});
}
});
A better design is to use a Card Layout to hold your input and output panels. Then you can just swap panels as required. The CardLayout will then manage the revalidating and repainting of the panel for you.
You need to make a call to revalidate() and or repaint() on the secondaryInOutPanel after you make changes.

Swing change JScrollPane content

Hi I am trying to change JScrollPane content like
scrollPanel = new JScrollPane(new Welcome().display());
for(final JMenuItem i : items) {
i.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String txt = i.getText();
if(txt.equals("Open")) {
scrollPanel = new JScrollPane(new Open().display());
} else if(txt.equals("Save")) {
scrollPanel = new JScrollPane(new Save().display());
} else if(txt.equals("Save as")) {
scrollPanel = new JScrollPane(new SaveAs().display());
} else if(txt.equals("Close")) {
new Close().ask();
scrollPanel = new JScrollPane();
}
scrollPanel.revalidate();
scrollPanel.repaint();
}
});
}
scrollPanel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
menuBar.add(menu);
frame.setJMenuBar(menuBar);
frame.add(scrollPanel);
frame.pack();
frame.setSize(640, 480);
frame.setVisible(true);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
But its not working.
Each class Open, Save, SaveAs return JPane with JLabel inside.
Ex.
public class Open {
public JPanel display() {
JPanel panel = new JPanel();
panel.add(new JLabel("Open"));
return panel;
}
}
You're not changing the scrollpane content. You're assigning a new JScrollPane instance to the scrollPanel field. The scroll pane you have added to the frame and which is displayed stays exactly as it is.
If you want to change the scroll pane contents, you should use
scrollPanel.setViewportView(new Open().display());

Firefox 'Open new tab' on JTabbedPane

I want to add a button to JTabbedPane's title bar (similar to the 'open new tab' ('+') button in Firefox)
I have tried to add to the glass pane of JTabbedPane's container. but since my tabbedpane contains within a JPanel seems it doesn't work for me.
Any suggestion will be a great help for me.
Thank you.
Instead of adding a button I have tried it in a different way and worked for me... I have added a JLabel (with '+') as a hidden tab and when user tries to select that tab i'll be adding a new tab.
public class AddTabButtonDemo extends JFrame{
private JTabbedPane tabbedPane = new JTabbedPane();
public AddTabButtonDemo() {
JLabel tab1Label = new JLabel("tab1");
JPanel tab1 = new JPanel();
tab1.add(tab1Label);
tabbedPane.addTab("tab1", tab1);
tabbedPane.addTab("+", new JLabel());
tabbedPane.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (tabbedPane.getSelectedComponent() instanceof JLabel) {
int count = tabbedPane.getTabCount();
JLabel newTabLabel = new JLabel("tab" + count);
JPanel newTab = new JPanel();
newTab.add(newTabLabel);
tabbedPane.add(newTab, count - 1);
tabbedPane.setTitleAt(count - 1, "tab" + count);
tabbedPane.setSelectedComponent(newTab);
}
}
});
this.add(tabbedPane, BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setMinimumSize(new Dimension(300, 300));
this.setVisible(true);
}
public static void main(String[] args) {
new AddTabButtonDemo();
}
}

Reloading component Frame

I'm Working on time schedule booking application , when I run the project it shows component(total frame) , however i want that when the button is pressed to reload ,component should be spitted.(two frames with one below other by spilt) ???
Based on your description I think you need to either add splitpane in frame on click of a button or you already have a splitpane in frame and want to add panel in it on click of button.
For first option you can do something like this:
final JFrame frame = new JFrame("Split test");
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel jPanel2 = new JPanel();
JLabel jLabel = new JLabel("I am added by click on button");
jPanel2.add(jLabel);
final JPanel jPanel = new JPanel();
JButton button = new JButton("Click me to add pane in split");
jPanel.add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JSplitPane pane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
pane.add(jPanel);
pane.add(jPanel2);
pane.setDividerLocation(frame.getHeight()/2); // set Divider location.
frame.remove(jPanel);
frame.add(pane);
frame.validate();
}
});
frame.add(jPanel);
frame.setVisible(true);
If you are stuck in later one then try this:
final JFrame frame = new JFrame("Split test");
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JSplitPane pane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
frame.add(pane);
pane.setEnabled(false); // stop user from clicking on divider of split pane.
final JPanel jPanel2 = new JPanel();
JLabel jLabel = new JLabel("I am added by click on button");
jPanel2.add(jLabel);
final JPanel jPanel = new JPanel();
JButton button = new JButton("Click me to add pane in split");
jPanel.add(button);
pane.add(jPanel);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
pane.add(jPanel2);
pane.setDividerLocation(frame.getHeight()/2); // set Divider location.
pane.setEnabled(true); // let user change divider location.
}
});
frame.setVisible(true);

Why do the JButton in my dialog look weird

I'm fairly new to Java Swing/AWT et al and hence the question. I have a simple dialog with some text and a couple JButton. I am using the GridbagLayout for this dialog.
But when I look at the dialog, the JButtons are kind of having a weird shape and I cannot seem to right justify the text either.
Is this a limitation of the Layout I am using. Is there much simpler and elegant solution for my problem with either the buttons or the textlayout?
A screenshot of the dialog is attached below.
The code for my dialog Class is:
public class UpgradePopupWindow extends JPanel implements ActionListener {
static final long serialVersionUID = 0;
final String upgrade = " Continue Upgrade ";
final String restore = "Restore Previous Version";
JPanel panels;
JButton upgradeButton;
JButton restoreButton;
JTextArea Message;
JFrame newFrame;
FlasherThread flash;
protected JTextArea addText(String text, boolean visible, int fontStyle) {
JTextArea textArea = new JTextArea(text);
textArea.setFont(new Font("SansSerif", fontStyle, 12)); //$NON-NLS-1$
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
textArea.setBackground(Color.DARK_GRAY);
textArea.setForeground(Color.WHITE);
textArea.setOpaque(false);
textArea.setVisible(visible);
textArea.setAlignmentX(Component.CENTER_ALIGNMENT);
add(textArea);
return textArea;
}
protected JTextArea addMultiLineLabel(String text, int fontStyle, int fontSize, Object constraints) {
JTextArea textArea = new JTextArea(text);
textArea.setFont(new Font("SansSerif", fontStyle, fontSize));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
textArea.setBackground(new Color(0, 0, 0, 0)); // Zero alpha = transparent background
textArea.setOpaque(false);
textArea.setBorder(new TitledBorder(""));
textArea.setAlignmentX(Component.CENTER_ALIGNMENT);
add(textArea, constraints);
return textArea;
}
private UpgradePopupWindow(JFrame frame, Object ft) {
super(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
flash = (FlasherThread)ft;
String text = "An error occurred during the attempt to update your device's software. We recommend the following: (1) Restore your device to its previous version, (2) back up important data, and then (3) try updating your device again. If you continue with the current update, only your previously backed-up data will be available.";
//addFiller(5);
//addLabel(text, Font.PLAIN, 12);
gbc.gridy = 0;
gbc.gridx = 0;
gbc.gridwidth = 2;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
addMultiLineLabel(text, Font.PLAIN, 12, gbc);
//addText(text, true, Font.PLAIN);
addFiller(20);
newFrame = frame;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
upgradeButton = new JButton(upgrade);
upgradeButton.setActionCommand("upgrade");
upgradeButton.addActionListener(this);
upgradeButton.setEnabled(true);
upgradeButton.setBackground(Color.WHITE);
upgradeButton.setForeground(Color.GRAY);
add(upgradeButton,gbc);
++ gbc.gridx;
restoreButton = new JButton(restore);
restoreButton.setActionCommand("restore");
restoreButton.addActionListener(this);
restoreButton.setEnabled(true);
//restoreButton.setForeground(Color.DARK_GRAY);
restoreButton.setBackground(Color.DARK_GRAY);
add(restoreButton,gbc);
setOpaque(true);
newFrame.setContentPane(this);
//newFrame.getContentPane().setBackground(Color.LIGHT_GRAY);
}
protected void addFiller(int size) {
Dimension diminsion = new Dimension(size, size);
Filler filler = new Filler(diminsion, diminsion, diminsion);
filler.setAlignmentX(Component.CENTER_ALIGNMENT);
add(filler);
}
public static void createGUI(Object obj) {
//Create and set up the frame.
JFrame frame = new JFrame("PopUp Dialog");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(440, 180));
//create and setup the content pane
UpgradePopupWindow popUpContentPane = new UpgradePopupWindow(frame, obj);
popUpContentPane.setOpaque(true);
frame.setContentPane(popUpContentPane);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if("restore".equals(e.getActionCommand())) {
System.out.println("restore button selected");
flash.setUpgradeRestoreChoice("restore");
newFrame.dispose();
} else if ("upgrade".equals(e.getActionCommand())) {
System.out.println("upgrade button selected");
flash.setUpgradeRestoreChoice("upgrade");
newFrame.dispose();
}
}
}
![alt text][1]
As #Javaguru said - use MigLayout. For the text DO NOT use JTextArea. This component is mostly for text editing. JLabel is enough for your purpose - you can even use HTML inside of it.
You don't have to create this kind of dialog from scratch. There are many options. One of them is my Swing TaskDialog framework ;)
But if you still insist on implementing it yourself here a simple implementation using MigLayout ( even with MigLayout it can be done using several differnt ways):
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import net.miginfocom.swing.MigLayout;
public class TestDialog extends JDialog {
private static final long serialVersionUID = 1L;
private final JLabel label = new JLabel("Your text here");
private final JButton restoreButton = new JButton("Restore Previous Version");
private final JButton ugradeButton = new JButton("Continue Upgrade");
public TestDialog( String title ) {
super( (JDialog)null, title );
setContentPane(createContent());
}
private JPanel createContent() {
JPanel content = new JPanel();
content.setPreferredSize( new Dimension(400, 100));
content.setBackground(Color.WHITE);
content.setLayout(new MigLayout("", "[400px,grow][pref!]", "[grow][pref!]"));
this.label.setVerticalAlignment(SwingConstants.TOP);
content.add(this.label, "cell 0 0 2 1,grow");
content.add(this.restoreButton, "cell 1 1,alignx left,aligny top");
content.add(this.ugradeButton, "cell 0 1,alignx right,aligny top");
return content;
}
// very simplified test
public static void main(String[] args) {
TestDialog dlg = new TestDialog("Popup Dialog");
dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dlg.pack();
dlg.setLocationRelativeTo(null);
dlg.setVisible(true);
}
}
There are a lot of much more elegant solutions out there .. ;)
You should really never use GridbagLayout if not absolutely required (or only with a gui editor)! It's simply a pain in the ass!
Rather I suggest using one of the following LayoutManagers:
MigLayout: http://www.miglayout.com/
TableLayout: https://tablelayout.dev.java.net/
Creating a pleasing layout is much simpler and intuitive than with the GridbagLayout and its configuration overhead.