Label connection with textField in java - swing

I wanted to take some value in currently available in label and add(calculate) with number
and display on the text field but there is errors
private void ch13ActionPerformed(java.awt.event.ActionEvent evt)
r1=Integer.parseInt(tLabel.getText()); //r2 and r1 are integers
// error .. It says "Void type not allowed here"
r2 = Integer.parseInt(tLabel.setText(String.valueOf("3")));
result=r1+r2;
creaditTxt.setText(result+"");
}
Then how do i solve this problem?

setText() returns void. So by doing this
r2 = Integer.parseInt(tLabel.setText(String.valueOf("3")));
you're saying that r2 = void. That's not possible.
You may want to have 2 textfields instead and a label to display the result
public class AddFrame extends JFrame {
private JLabel result = new JLabel();
private JTextField number1 = new JTextField(10);
private JTextField number2 = new JTextField(10);
private JButton addBut = new JButton("Add");
public AddFrame(){
setLayout(new GridLayout(4, 1));
add(result);
add(number1);
add(number2);
add(addBut);
addBut.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int num1 = Integer.parseInt(number1.getText());
int num2 = Integer.parseInt(number2.gettext());
int total = num1 + num2;
result.setText(String.valueOf(total));
}
});
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
AddFrame frame = new AddFrame();
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

Related

D/Volley: [1] 5.onErrorResponse: Product

How do I insert data from MySQL into Gridview on Fragments? I've tried it with a coding method used for Activity. I've changed a lot but it's still wrong. This is my coding:
/**
* A simple {#link Fragment} subclass.
*/
public class Product extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
GridView grid_product;
SwipeRefreshLayout swipe;
List<ProductData> newsList = new ArrayList<ProductData>();
private static final String TAG = Product.class.getSimpleName();
private static String url_list = Server.URL + "news.php?offset=";
private int offSet = 0;
int no;
ProductAdapter adapter;
public static final String TAG_NO = "no";
public static final String TAG_ID = "id";
public static final String TAG_JUDUL = "judul";
public static final String TAG_TGL = "tgl";
public static final String TAG_ISI = "isi";
public static final String TAG_GAMBAR = "gambar";
Handler handler;
Runnable runnable;
public Product() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_product, container, false);
swipe = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
grid_product = (GridView) view.findViewById(R.id.grid_product);
setProduct();
return view;
}
private void setProduct(){
adapter = new ProductAdapter(getActivity(), newsList);
grid_product.setAdapter(adapter);
grid_product.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//pindah activity
startActivity(new Intent(
getActivity(), DetailActivity.class
));
}
});
I don't know where the mistake is:
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
newsList.clear();
adapter.notifyDataSetChanged();
callNews(0);
}
}
);
grid_product.setOnScrollListener(new AbsListView.OnScrollListener() {
private int currentVisibleItemCount;
private int currentScrollState;
private int currentFirstVisibleItem;
private int totalItem;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.totalItem = totalItemCount;
}
private void isScrollCompleted() {
if (totalItem - currentFirstVisibleItem == currentVisibleItemCount
&& this.currentScrollState == SCROLL_STATE_IDLE) {
swipe.setRefreshing(true);
handler = new Handler();
runnable = new Runnable() {
public void run() {
callNews(offSet);
}
};
handler.postDelayed(runnable, 3000);
}
}
});
}
#Override
public void onRefresh() {
newsList.clear();
adapter.notifyDataSetChanged();
callNews(0);
}
I don't know where the mistake is:
private void callNews(int page){
swipe.setRefreshing(true);
// Creating volley request obj
JsonArrayRequest arrReq = new JsonArrayRequest(url_list + page,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
ProductData news = new ProductData();
no = obj.getInt(TAG_NO);
news.addId(obj.getString(TAG_ID));
news.addJudul(obj.getString(TAG_JUDUL));
if (obj.getString(TAG_GAMBAR) != "") {
news.addGambar(obj.getString(TAG_GAMBAR));
}
news.addDatetime(obj.getString(TAG_TGL));
news.addIsi(obj.getString(TAG_ISI));
// adding news to news array
newsList.add(news);
if (no > offSet)
offSet = no;
Log.d(TAG, "offSet " + offSet);
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(arrReq);
}
}

JavaFX tableview showing only last row of data repeatedly from MySQL database

I have a windows application where I want to populate my table of from MySQL database. I have written the code below to get data in table. I am able to get the database but while adding the rows in table it shows only last row (repeatedly as much the rows of in MySQL) from MySQL database.
public class ShowDatabase{
private static ObservableList<UserMaster> row;
private static ObservableList<String> col;
public static void buildData(TableView<UserMaster> tableview){
Connection c;
String SQL = "SELECT * from user_info";
UserMaster cm = new UserMaster();
try{
String colHeading[]={"Name","Course","e-mail","City"};
col = FXCollections.observableArrayList(colHeading);
row= FXCollections.observableArrayList();
c= DBConnection.connect();
ResultSet rs = c.createStatement().executeQuery(SQL);
TableColumn<UserMaster,String> colName = new TableColumn<UserMaster, String>(col.get(0));
colName.setMinWidth(200);
colName.setCellValueFactory(new PropertyValueFactory<UserMaster,String>("name"));
TableColumn<UserMaster, String> colCourse = new TableColumn<UserMaster, String>(col.get(1));
colCourse.setMinWidth(200);
colCourse.setCellValueFactory(new PropertyValueFactory<UserMaster,String>("course"));
TableColumn<UserMaster, String> colEmail = new TableColumn<UserMaster, String>(col.get(2));
colEmail.setMinWidth(200);
colEmail.setCellValueFactory(new PropertyValueFactory<UserMaster,String>("email"));
TableColumn<UserMaster, String> colCity = new TableColumn<UserMaster, String>(col.get(3));
colCity.setMinWidth(200);
colCity.setCellValueFactory(new PropertyValueFactory<UserMaster,String>("city"));
tableview.getColumns().addAll(colName,colCourse,colEmail,colCity);
//colMobile,colEmail,colDoj,colCity);
while(rs.next()){
ObservableList<UserMaster> data = FXCollections.observableArrayList();
cm.name.set(rs.getString("name"));
cm.course.set(rs.getString("course_name"));
cm.email.set(rs.getString("email"));
cm.city.set(rs.getString("city"));
row.add(cm);
System.out.println(row.get(0).getName());
}
tableview.setItems(row);
}catch(SQLException sqex){
sqex.printStackTrace();
System.out.println("Error on Building Data");
}
}
}
Code to build table (Application):
public class DisplayDatabase extends Application{
#Override
public void start(Stage stage) throws Exception {
stage.setFullScreen(false);
TableView tableview;
//TableView
tableview = new TableView();
DisplayDatabase.buildData(tableview);
//Adding GridPane
GridPane gridPane = new GridPane();
gridPane.setPadding(new Insets(20,20,20,20));
gridPane.setHgap(5);
gridPane.setVgap(5);
//Main Scene
Scene scene = new Scene(tableview);
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
And the class to format Observable List:
public class UserMaster{
public SimpleStringProperty name = new SimpleStringProperty();
public SimpleStringProperty course = new SimpleStringProperty();
public SimpleIntegerProperty mobile = new SimpleIntegerProperty();
public SimpleStringProperty email = new SimpleStringProperty();
public ObjectProperty<Date> doj = new SimpleObjectProperty<Date>();
public SimpleStringProperty city = new SimpleStringProperty();
public String getName() {
return name.get();
}
public String getEmail() {
return email.get();
}
public String getCity() {
return city.get();
}
public String getCourse() {
return course.get();
}
}
Though I have 2 unique rows of data but it is showing only last row (same data) form database table repeatedly.
Here is the picture attachment for more clarity about problem.
Create new UserMaster on every iteration:
while(rs.next()){
UserMaster cm = new UserMaster();
cm.name.set(rs.getString("name"));
cm.course.set(rs.getString("course_name"));
cm.email.set(rs.getString("email"));
cm.city.set(rs.getString("city"));
row.add(cm);
}
tableview.setItems(row);
while(rs.next()){
cm.name.set(rs.getString("name"));
cm.course.set(rs.getString("course_name"));
cm.email.set(rs.getString("email"));
cm.city.set(rs.getString("city"));
row.add(new UserMaster(name,course,email,city));
}
tableview.setItems(row);
try this :)

Repaint() not working with other JPanel?

I am trying to make a program with 2 panels, and when the first panel is clicked it displays another color, and in the second panel the word changes to the color that is currently displayed
The problem is repaint() doesn't call paintComponent() again
class Fun extends JPanel{
public int i = 0;
A a = new A();
B b = new B();
public Fun(){
setLayout(new GridLayout(2, 2, 10, 10));
add(a);
add(b);
}
public void paintComponent(Graphics g){
setBackground(Color.WHITE);
super.paintComponent(g);
}
class A extends JPanel implements MouseListener{
public Color c = Color.BLUE;
CardLayout cl = new CardLayout();
JPanel c1 = new JPanel();
JPanel c2 = new JPanel();
JPanel c3 = new JPanel();
Color[] colors = {Color.BLUE, Color.GREEN, Color.RED};
public A(){
addMouseListener(this);
setLayout(cl);
c1.setBackground(Color.BLUE);
c2.setBackground(Color.GREEN);
c3.setBackground(Color.RED);
add(c1);
add(c2);
add(c3);
}
public void mouseClicked(MouseEvent e){
cl.next(this);
if (i==2){
i = 0;
}
else{
i++;
}
c = colors[i];
new B().go();
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
}
class B extends JPanel{
JLabel l = new JLabel("Play Baby!");
public B(){
add(l);
}
public void paintComponent(Graphics g){
System.out.println("repainted");
A apple = new A();
g.setColor(apple.colors[i]);
super.paintComponent(g);
}
public void go(){
repaint();
}
}
}
In your mouseClicked, you are calling go() on a new B. But the new B is never added to another component. You probably want to say, b.repaint(), using the B that was defined as a member variable.

JComboBox inside Jtable with GlazedLists AutocompleteSupport - getSelectedItem returns null

I'm using GlazedLists' AutoCompleteSupport to wrap a JComboBox used as cell editor for a JTable and am facing a problem to get selectedItem when I type a value in the editor that is not in the model.
The problem appears inside the stopCellEditing method, after you type something in the ComboBox that is not in the list. Even if something was typed in the editor, when invoking getItem() from stopCellEditing, null will be returned. Please see like 65 from the code below.
I would like to get the item from the editor to be able to add it to the ComboBox model.
import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.TextFilterator;
import ca.odell.glazedlists.swing.AutoCompleteSupport;
import java.awt.Component;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.util.HashMap;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
public class TestComboBoxGlazedLists {
public static void main(String[] args) {
TestComboBoxGlazedLists test = new TestComboBoxGlazedLists();
test.go();
}
public void go() {
//create the frame
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create and add a tabbed pane to the frame
JTabbedPane tabbedPane = new JTabbedPane();
frame.getContentPane().add(tabbedPane);
//create a table and add it to a scroll pane in a new tab
JTable table = new JTable(new DefaultTableModel(new Object[]{"A", "B"}, 5));
JScrollPane scrollPane = new JScrollPane(table);
tabbedPane.addTab("test", scrollPane);
// create a simple JComboBox and set is as table cell editor on column A
TestComboBoxGlazedLists.UserRepository rep = new TestComboBoxGlazedLists.UserRepository();
TestComboBoxGlazedLists.UserInfo[] comboElements = rep.getAllUsers();
DefaultComboBoxModel model = new DefaultComboBoxModel(comboElements);
JComboBox comboBox = new JComboBox(model);
// GlazedLists
DefaultCellEditor cellEditor = new DefaultCellEditor(comboBox) {
private Object originalValue;
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
originalValue = value;
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
#Override
public boolean stopCellEditing() {
JComboBox comboBox = (JComboBox) getComponent();
ComboBoxModel comboModel = comboBox.getModel();
// this value is null when the selected item is not from the list
Object editingValue = getCellEditorValue();
// Needed because your TableModel is empty
if (editingValue == null) {
return super.stopCellEditing();
}
int selectedIndex = -1;
int modelSize = comboModel.getSize();
for (int i = 0; i < modelSize; i++) {
if (editingValue.equals(comboModel.getElementAt(i))) {
selectedIndex = i;
}
}
// Selecting item from model
if (!(selectedIndex == -1)) {
return super.stopCellEditing();
}
if (!(editingValue instanceof TestComboBoxGlazedLists.UserInfo)) {
// Confirm addition of new value
int result = JOptionPane.showConfirmDialog(
comboBox.getParent(),
"Add (" + editingValue + ") to table?",
"Update Model",
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
TestComboBoxGlazedLists.UserInfo newUser = new TestComboBoxGlazedLists.UserInfo(editingValue.toString(), null);
comboBox.addItem(newUser);
comboBox.setSelectedItem(newUser);
return super.stopCellEditing();
}
}
return false;
}
};
// needs to be invoked from Event Dispatch Thread
SwingUtilities.invokeLater(new TestComboBoxGlazedLists.AutocompleteComboRunnable(table, comboBox));
// end GlazedLists
table.getColumn("A").setCellEditor(cellEditor);
table.getColumn("A").setCellRenderer(new TestComboBoxGlazedLists.CustomTableCellRenderer());
// pack and show frame
frame.pack();
frame.setVisible(true);
}
public class AutocompleteComboRunnable implements Runnable {
private JTable mTable;
private JComboBox mComboBox;
public AutocompleteComboRunnable(JTable table, JComboBox comboBox) {
mTable = table;
mComboBox = comboBox;
}
#Override
public void run() {
TextFilterator textFilterator = GlazedLists.textFilterator("firstName");
// ComboBoxCellEditor cellEditor = new ComboBoxCellEditor(comboBox);
TestComboBoxGlazedLists.UserRepository rep = new TestComboBoxGlazedLists.UserRepository();
AutoCompleteSupport support = AutoCompleteSupport.install(mComboBox,
GlazedLists.eventListOf(rep.getAllUsers()),
textFilterator,
new TestComboBoxGlazedLists.UserInfoFormat());
support.setStrict(false);
}
}
public class CustomTableCellRenderer extends DefaultTableCellRenderer {
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value != null) {
// this is used to extract the data you want to display in the table from your "custom model"
TestComboBoxGlazedLists.UserInfo user = (TestComboBoxGlazedLists.UserInfo) value;
return super.getTableCellRendererComponent(table, user.getFirstName(), isSelected, hasFocus, row, column);
} else {
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
}
}
public class UserInfo {
private String firstName;
private String lastName;
public UserInfo(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
public class UserRepository {
TestComboBoxGlazedLists.UserInfo[] comboElements;
HashMap<String, TestComboBoxGlazedLists.UserInfo> objectsMap;
public UserRepository() {
comboElements = new TestComboBoxGlazedLists.UserInfo[5];
comboElements[0] = new TestComboBoxGlazedLists.UserInfo("John", "Doe");
comboElements[1] = new TestComboBoxGlazedLists.UserInfo("Betty", "Doe");
comboElements[2] = new TestComboBoxGlazedLists.UserInfo("Elenor", "Smith");
comboElements[3] = new TestComboBoxGlazedLists.UserInfo("Helen", "Kelly");
comboElements[4] = new TestComboBoxGlazedLists.UserInfo("Joe", "Black");
objectsMap = new HashMap<>();
for (int i = 0; i < 5; i++) {
objectsMap.put(comboElements[i].getFirstName(), comboElements[i]);
}
}
public TestComboBoxGlazedLists.UserInfo getUserInfo(String name) {
return objectsMap.get(name);
}
public TestComboBoxGlazedLists.UserInfo[] getAllUsers() {
return comboElements;
}
}
private class UserInfoFormat extends Format {
#Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
if (obj != null) {
toAppendTo.append(((TestComboBoxGlazedLists.UserInfo) obj).getFirstName());
}
return toAppendTo;
}
#Override
public Object parseObject(String source, ParsePosition pos) {
TestComboBoxGlazedLists.UserRepository rep = new TestComboBoxGlazedLists.UserRepository();
return rep.getUserInfo(source.substring(pos.getIndex()));
}
}
}

Adding JTextArea to JFrame

If I have 1 main class and 2 subclasses
subclass 1: public class JPanel1 extends JPanel {....properly initialized}
subclass 2: public class JTextArea1 extends JTextArea {... properly initialized}
Why can I do jframe1.add(new JPanel1()) but not jframe1.add(new JTextArea1())? for a properly initialized JFrame jframe1 = new JFrame();?
My goal is to output data into both the jpanel and the jtextarea
Here on my side, the issue you raising, is working fine. Do let me know, if you think, this is not what you mean :-)
import java.awt.*;
import javax.swing.*;
public class SwingExample
{
private CustomPanel customPanel;
private CustomTextArea customTextArea;
private void displayGUI()
{
JFrame frame = new JFrame("Swing Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setBorder(
BorderFactory.createLineBorder(
Color.DARK_GRAY, 5));
customPanel = new CustomPanel();
customTextArea = new CustomTextArea();
contentPane.add(customPanel, BorderLayout.CENTER);
contentPane.add(customTextArea, BorderLayout.LINE_START);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
#Override
public void run()
{
new SwingExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class CustomPanel extends JPanel
{
private static final int GAP = 5;
public CustomPanel()
{
setOpaque(true);
setBackground(Color.WHITE);
setBorder(BorderFactory.createLineBorder(
Color.BLUE, GAP, true));
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(300, 300));
}
}
class CustomTextArea extends JTextArea
{
private static final int GAP = 5;
public CustomTextArea()
{
setBorder(BorderFactory.createLineBorder(
Color.RED, GAP, true));
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(100, 30));
}
}
OUTPUT :