I am trying to make a JFrame scrollable by using Palette. In Netbeans if I make a panel with dimensions (300, 500) and a ScrollPane with dimensions (200,200) then if I drag and drop the panel into the ScrollPane it creates automatically the bars.
In eclipse I tried it with the same way and I cannot make it. Moreover the final code in eclipse after the attempt is the following:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
public class InsertWaterRawData extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
InsertWaterRawData frame = new InsertWaterRawData();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public InsertWaterRawData() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 577, 383);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(236, 87, 200, 200);
contentPane.add(scrollPane);
JPanel panel = new JPanel();
scrollPane.setViewportView(panel);
panel.setLayout(null);
}
}
Is there any way to make it with the palette ??
Thanks in advance
panel.setLayout(null);
Don't use a null layout!!!
The scrollbars will appear automatically when the preferred size of the panel is greater than the size of the scrollpane.
When you use a layout manager the preferred size of the panel will be calculated automatically as you add components to the panel.
If you are doing custom painting on your panel, then you need to override the getPreferredSize() method of your panel to return an appropriate size.
Based on the code you posted there is no need for scrollbars because no components have been added to the panel.
Related
I am using SWT to create an application GUI, and I don't really need to resize the components, but it does bother me that when the window is maximized, the components stay left-aligned. Is there a way to fix this with SWT or do I need to utilize a different set of GUI tools?
Thanks in advance. I am using SWT 4.8 for this application.
EDIT: Images
Small: https://imgur.com/CPbAlaZ
Maximized: https://imgur.com/4d6YXcl
Provided images are a basic application using the following code
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
public class TestWindow {
protected Shell shlSwtApplicationExample;
private Text text;
/**
* Launch the application.
* #param args
*/
public static void main(String[] args) {
try {
TestWindow window = new TestWindow();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shlSwtApplicationExample.open();
shlSwtApplicationExample.layout();
while (!shlSwtApplicationExample.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shlSwtApplicationExample = new Shell();
shlSwtApplicationExample.setSize(705, 529);
shlSwtApplicationExample.setText("SWT Application Example");
Composite composite = new Composite(shlSwtApplicationExample, SWT.NONE);
composite.setBounds(10, 10, 669, 465);
text = new Text(composite, SWT.BORDER);
text.setBounds(22, 10, 334, 295);
Button btnNewButton = new Button(composite, SWT.NONE);
btnNewButton.setBounds(49, 384, 137, 26);
btnNewButton.setText("New Button");
Button button = new Button(composite, SWT.NONE);
button.setText("New Button");
button.setBounds(300, 384, 137, 26);
}
}
I would not recommend using setBounds since it does not resize the components when you resize the application. Use Layouts, like for example below I have used GridLayout for both the Shell and the Composite which will properly arrange the UI when resize happens.
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
public class TestWindow {
protected Shell shlSwtApplicationExample;
private Text text;
/**
* Launch the application.
* #param args
*/
public static void main(String[] args) {
try {
TestWindow window = new TestWindow();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents(display);
shlSwtApplicationExample.open();
shlSwtApplicationExample.layout();
shlSwtApplicationExample.setLayout(new GridLayout(1, false));
while (!shlSwtApplicationExample.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
* #param display
*/
protected void createContents(Display display) {
shlSwtApplicationExample = new Shell(display);
shlSwtApplicationExample.setLayout(new GridLayout(1, false));
Composite txtcomposite = new Composite(shlSwtApplicationExample, SWT.NONE);
txtcomposite.setLayout(new GridLayout(1, false));
txtcomposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
Composite btncomposite = new Composite(shlSwtApplicationExample, SWT.NONE);
btncomposite.setLayout(new GridLayout(2, false));
btncomposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
text = new Text(txtcomposite, SWT.BORDER);
text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
Button btnNewButton = new Button(btncomposite, SWT.NONE);
btnNewButton.setText("New Button");
Button button = new Button(btncomposite, SWT.NONE);
button.setText("New Button");
shlSwtApplicationExample.setText("SWT Application Example");
//shlSwtApplicationExample.setSize(705, 529);
}
}
Since you are using setBounds you will need to add a Control listener to the shell to be told about resize and move events. You will then have to recalculate the positions on each resize event.
shlSwtApplicationExample.addControlListener(
new ControlListener() {
#Override
public void controlMoved(ControlEvent event) {
// No action
}
#Override
public void controlResized(ControlEvent event) {
Rectangle rect = shlSwtApplicationExample.getClientArea();
// TODO Call new `setBounds` on each control based on the
// client area size
}
});
This might be a good time to learn about using Layouts instead of setBounds (see here). Layouts will automatically deal with resizes.
I am developing a desktop application in which I want Admin have option to delete users, for which I planned that whenever Admin clicks on 'delete users' button a new tab will open in which check boxes with the name of all existing users in my database should appear(so that he can delete multiple users simultaneously); so basically I need to generate dynamic check boxes as per my database.
I am using Netbeans 7.0.1, jdk 1.6, sqlite3.
After searching on google I got two links which match to my problem:
http://www.coderanch.com/t/345949/GUI/java/create-dynamic-checkboxes#2805277
Creating dcheckbox dynamically in Java-NetBeans
I have tried to follow the code from above first link but it does not working for me properly. What I does is just created new JFrame in netbeans and called a method inside constructor which create checkboxes as per needed, method's code is as below:
public class Work extends javax.swing.JFrame {
/** Creates new form Work */
public Work() {
initComponents();
checks = new java.util.ArrayList<>();
createCheckboxes();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void createCheckboxes(){
panel = new javax.swing.JPanel();
this.add(panel);
for(int i = 0; i<4; i++){
javax.swing.JCheckBox box = new javax.swing.JCheckBox("check"+i);
panel.add(box);
checks.add(box);
panel.revalidate();
panel.repaint();
}
panel.setVisible(true);
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Work().setVisible(true);
}
});
}
// Variables declaration - do not modify
// End of variables declaration
private java.util.ArrayList <javax.swing.JCheckBox> checks;
private javax.swing.JPanel panel;
}
The output is just a blank frame. Please help me to know where I am wrong!!
And yes this code is not connected to database yet, once it will work then I can modify it to work with database.
Also is their any other betterway to accomplish my task or am on right path?`
I think it might help if u call the following function whenever to wanna create a new checkbox..
public class CheckBox extends JFrame{
//private static final long serialVersionUID = 1L;
public CheckBox() {
// set flow layout for the frame
this.getContentPane().setLayout(new FlowLayout(FlowLayout.TRAILING, 50, 20)); //(default) centered alignment and a default 5-unit horizontal and vertical gap.
JCheckBox checkBox1 = new JCheckBox("Checkbox 1");
checkBox1.setSelected(true);
JCheckBox checkBox2 = new JCheckBox("Checkbox 2", true);
JCheckBox checkBox3 = new JCheckBox("Checkbox 3");
// add checkboxes to frame
add(checkBox1);
add(checkBox2);
add(checkBox3);
}
private static void createAndShowGUI() {
//Create and set up the window.
//JFrame frame = new CreateCheckedUncheckedJCheckBox();
CheckBox cb = new CheckBox();
//Display the window.
cb.pack();
cb.setVisible(true);
cb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
You add the new checkboxes as if your frame was using some simple layout such as FlowLayout, but it is not - it is using GroupLayout - see the generated initComponents() method.
If you want to handle ALL components in the frame dynamically, you can do this (it is better to create an empty class file and then paste the code below; do not ask NB to create a JFrame as it would again create a form to be designed in the visual designer; if you still do it then r-click it and change the layout to something simpler):
public class Work extends javax.swing.JFrame {
private java.util.List <javax.swing.JCheckBox> checks = new java.util.ArrayList<>();;
public Work() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new java.awt.FlowLayout()); // simply put the components next to each other
createCheckboxes();
}
private void createCheckboxes(){
for(int i=0; i<4; i++) {
javax.swing.JCheckBox box = new javax.swing.JCheckBox("check"+i);
add(box);
checks.add(box);
}
pack(); // this will tell the JFrame's panel to layout all the components
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Work().setVisible(true);
}
});
}
}
Or you can design part of your frame with the visual designer and then add the checkboxes. In that case add an empty panel in the designer, set the panel's layout to something like flow or grid layout and then add the checkboxes to that panel from your code in the same way as above.
You validate needs to be called only if the panel/frame is already visible. Calling pack works even then, but might change the size of the frame. Also validating can be done after all components were added not after adding each one.
To add check boxes or any other component dynamically in Netbeans JFrame one need to manage Layout Managers, by default netbeans frames use Free Design Layout, follow steps below:
Create blank JFrame -->Add Jpanel to it-->right click to the panel, select setLayout and change it to GridLayout.
Now we are free to add ant components on this panel.
Also don't forgate to add revalidate() and repaint() methods.
This worked for me.
How to create a click event search button in Eclipse?? Can someone help me. This is the code im working with.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
listContent1 = (ListView)findViewById(R.id.lFoodlist1);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();
Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);
String[] from = new String[]{SQLiteAdapter.KEY_FOODNAME,SQLiteAdapter.KEY_CALORIES};
int[] to = new int[]{R.id.tv1, R.id.tv2};
SimpleCursorAdapter cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent1.setAdapter(cursorAdapter);
//listContent.setOnItemClickListener(listContentOnItemClickListener);*/
}
This code was taken from Here and was modified/commented to help the poseter with his scenario.
You can implement swing to help with the GUI aspect of your application. Others may prefer AWT
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class myTest {
public static void main(String[] args) {
//This will create the JFrame/JPanel/JButton
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button1 = new JButton();
//Add your panel and button and make them visable
frame.add(panel);
panel.add(button1);
frame.setVisible(true);
//This adds the actionListener to the Button
button1.addActionListener(new ActionListener() {
//When the button is clicked this action will be performed
public void actionPerformed(ActionEvent arg0) {
//Add your code here.
}
});
}
}
I am trying to add an expand bar to an Eclipse viewpart. When I click the expand button I would like the viewpart to move items below the expand bar down and show the expanded items. What currently happens is the expand bar items just disappear below the items below the expand bar. Any thoughts?
final ExpandBar expandBar = new ExpandBar(parent, SWT.NONE);
expandBar.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
expandBar.setSpacing(0);
fd_toolBar.top = new FormAttachment(expandBar, 6);
FormData fd_expandBar = new FormData();
fd_expandBar.top = new FormAttachment(0, 62);
fd_expandBar.left = new FormAttachment(0, 3);
expandBar.setLayoutData(fd_expandBar);
formToolkit.paintBordersFor(expandBar);
final ExpandItem xpndtmWarningDetails = new ExpandItem(expandBar, SWT.NONE);
xpndtmWarningDetails.setExpanded(true);
xpndtmWarningDetails.setText("Warning Details");
final Composite composite_1 = new Composite(expandBar, SWT.NONE);
composite_1.setBackground(SWTResourceManager.getColor(SWT.COLOR_YELLOW));
xpndtmWarningDetails.setControl(composite_1);
formToolkit.paintBordersFor(composite_1);
xpndtmWarningDetails.setHeight(xpndtmWarningDetails.getControl().computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
Label lblTest = new Label(composite_1, SWT.NONE);
lblTest.setBounds(10, 10, 55, 15);
lblTest.setText("Test");
expandBar.addExpandListener(new ExpandListener(){
#Override
public void itemCollapsed(ExpandEvent e) {
expandBar.setSize(expandBar.getSize().x, xpndtmWarningDetails.getHeaderHeight());
parent.layout(true);
}
#Override
public void itemExpanded(ExpandEvent e) {
expandBar.setSize(expandBar.getSize().x, 300);
expandBar.layout(true);
parent.layout(true);
}
});
I think the ExpandBar works best when used like it is in this example...
http://git.eclipse.org/c/platform/eclipse.platform.swt.git/tree/examples/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet343.java
... with several expand bars stacked on top of each other, and nothing else mixed in.
I think the functionality your looking for can be accomplished with an ExpandableComposite object. It depends on what else is going on in your ViewPart.
Here's a quick example of an ExpandableComposite.
package com.amx.designsuite.rcp;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
public class ExpandableCompositeExample extends Composite {
/**
* Create the composite.
* #param parent
* #param style
*/
public ExpandableCompositeExample(final Composite parent, int style) {
super(parent, style);
FormToolkit toolkit;
toolkit = new FormToolkit(parent.getDisplay());
final ScrolledForm form = toolkit.createScrolledForm(parent);
form.setText("Title for Form holding Expandable Composite (optional)");
TableWrapLayout layout = new TableWrapLayout();
form.getBody().setLayout(layout);
ExpandableComposite expandableCompsite = toolkit.createExpandableComposite(form.getBody(), ExpandableComposite.TREE_NODE | ExpandableComposite.SHORT_TITLE_BAR);
toolkit.paintBordersFor(expandableCompsite);
expandableCompsite.setText("Expandable Composite Title (Optional)");
expandableCompsite.setExpanded(true);
Text txtMyNewText = toolkit.createText(expandableCompsite, "Text to show when composite is expanded", SWT.NONE);
expandableCompsite.setClient(txtMyNewText);
}
#Override
protected void checkSubclass() {
// Disable the check that prevents subclassing of SWT components
}
}
I'm working on a JFrame interface to interact easily with a large amount of data. The data is saved in a .txt file, and when a name is selected from the JList, my program reads the appropriate lines of data, converts them into an Object I've defined (CounterParty), and displays the appropriate fields of the objects in JLabels. This all works well. I've also written code to launch a new JPanel that edits the selected Object. The JPanel opens, already populated with the data, and when a button is clicked the existing information on the .txt file is deleted and replaced with the new, edited data. This also works well.
However, I would like to make this a bit more user-friendly. I want the JLabels where the information is initially displayed to convert into JTextFields populated with the data from the jLabels when the Edit button is clicked. This would remove needing to launch the new JPanel window altogether. I assume is would change the visibility to false of the JLabels and create new JTextField objects. I'm having trouble with this. Can JLabel objects be converted to JTextFields? Can I maybe have both objects in the exact same spot, but alternate visibility? I'm not sure how to go about this.
I'm using NetBeans.
Thank you for your help! Let me know if any additional information is needed.
This is one way to do that:
Assuming that JLabel is your label and textfield your JTextField
textfield = new JTextField(label.getText());
This will create a with the text of the JLabel.
You should place your JLabel in a dedicated JPanel, so you remove the JLabel from it and replace it with the JTextField, then repaint()/revalidate()
I created a small example which I think demonstrates what you want. It uses a button which when pressed will either remove the JTextField and add the JLabel and vice versa and then it will call revalidate() and repaint() to show changes to the frame after each button click:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JLabelToJTextField extends JFrame {
JLabel jLabel;
JTextField jTextField;
JButton jButton;
JPanel mainPanel;
public JLabelToJTextField() {
jLabel = new JLabel("Name");
jTextField = new JTextField(15);
jButton = new JButton("Edit");
mainPanel = new JPanel(new BorderLayout());
createUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JLabelToJTextField().setVisible(true);
}
});
}
private void createUI() {
setTitle("JLabel to JtextField");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPanel();
setLocationRelativeTo(null);
pack();
}
private void addComponentsToPanel() {
mainPanel.add(jLabel, BorderLayout.CENTER);
mainPanel.add(jButton, BorderLayout.SOUTH);
addActionListeners();
getContentPane().add(mainPanel);
}
private void addActionListeners() {
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
switch (jButton.getText()) {
case "Edit":
mainPanel.remove(jLabel);//remove component
mainPanel.add(jTextField, BorderLayout.CENTER);//add new component
jButton.setText("Done");
//refresh JFrame
revalidate();
repaint();
break;
case "Done":
mainPanel.remove(jTextField);//remove component
mainPanel.add(jLabel, BorderLayout.CENTER);//add new component
jButton.setText("Edit");//set button text to original
//refresh JFrame
revalidate();
repaint();
break;
}
}
});
}
}