Hi everyone Im on to the last part now which is file reading. i have tried writing a fileReader but seem to not be changing the value of my variable rNum?
any ideas on why it wont change in the following statements? thanks
public void readStartFile(String fileName){
int rowNumber=-1;
int colNumber = -1;
int rN= 0;
int cN = 0;
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("start.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
String[] temp = strLine.split(" ");
rowNumber = Integer.parseInt(temp[0].substring(1, temp[0].length()));
colNumber = Integer.parseInt(temp[1].substring(1, temp[1].length()));
String colour = temp[2];
if(rowNumber == 0)
rN =0;
else if(rowNumber == 1)
rN =1;
else if(rowNumber == 2)
rN =2;
else if(rowNumber == 3)
rN =3;
else if(rowNumber == 4)
rN =4;
else if(rowNumber == 5)
rN =5;
if(colNumber == 0)
cN =0;
else if(colNumber == 1)
cN =1;
else if(colNumber == 2)
cN =2;
else if(colNumber == 3)
cN =3;
else if(colNumber == 4)
cN =4;
else if(colNumber == 5)
cN =5;
if (colour == "Red")
buttons[rN][cN].setBackground(Color.RED);
System.out.println(""+rN);
System.out.println(""+cN);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
this is a method from the ButtonColours class. Now how would i set the buttons to the specified colour as what i am doing at the minute does not seem to work.
Unfortunately, there is no reliable way to change the color of any JButton. Some "look and feel" implementations don't honor the color set by setBackground(). You'd be better off just adding a MouseListener to the panel(s) to listen for mouse-up events, and responding to those, rather than using buttons at all.
In order to change the Colour of your JButton, first of all you must keep one thing in mind, always to use buttonObject.setOpaque(true); as very much adviced to me once by #Robin :-). As taken from Java Docs the call to setOpaque(true/false)
Sets the background color of this component. The background color
is used only if the component is opaque
Here I had modified your code a bit, and added some comments as to what I had added, see is this what you wanted.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class ButtonColours extends JFrame
{
private static ButtonColours buttonColours;
/*
* Access Specifier is public, so that they can be
* accessed by the ColourDialog class.
*/
public JButton[][] buttons;
private static final int GRID_SIZE = 600;
public static final int ROW = 6;
public static final int COLUMN = 6;
// Gap between each cell.
private static final int GAP = 2;
private static final Color DEFAULT_COLOUR = new Color(100,100,100);
public static final String DEFAULT_COMMAND = "6";
// Instance Variable for the ColourDialog class.
private ColourDialog dialog = null;
private BufferedReader input;
private DataInputStream dataInputStream;
private FileInputStream fileInputStream;
private String line= "";
/*
* Event Handler for each JButton, inside
* the buttons ARRAY.
*/
public ActionListener buttonActions = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
System.out.println(ae.getActionCommand());
if (dialog != null && dialog.isShowing())
dialog.dispose();
dialog = new ColourDialog(buttonColours, "COLOUR CHOOSER", false, button);
dialog.setVisible(true);
button.setBackground(DEFAULT_COLOUR);
button.setName("6");
}
};
public ButtonColours()
{
buttons = new JButton[ROW][COLUMN];
try
{
fileInputStream = new FileInputStream("start.txt");
dataInputStream = new DataInputStream(fileInputStream);
input = new BufferedReader(new InputStreamReader(dataInputStream));
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
/*
* Instead of explicitly calling getPreferredSize() method
* we will override that method instead, for good
* visual appearance fo the Program on different
* Platforms, i.e. Windows, MAC OS, LINUX
*/
public Dimension getPreferredSize()
{
return (new Dimension(GRID_SIZE, GRID_SIZE));
}
private void readFile()
{
int rowNumber = -1;
int columnNumber = -1;
try
{
while((line = input.readLine()) != null)
{
String[] temp = line.split(" ");
rowNumber = Integer.parseInt(temp[0].substring(1, temp[0].length()));
columnNumber = Integer.parseInt(temp[1].substring(1, temp[1].length()));
String colour = temp[2].trim();
System.out.println("Row is : " + rowNumber);
System.out.println("Column is : " + columnNumber);
System.out.println("Colour is : " + colour);
if (colour.equals("RED") && rowNumber < ROW && columnNumber < COLUMN)
{
System.out.println("I am working !");
buttons[rowNumber][columnNumber].setBackground(Color.RED);
buttons[rowNumber][columnNumber].setName("0");
}
else if (colour.equals("YELLOW") && rowNumber < ROW && columnNumber < COLUMN)
{
buttons[rowNumber][columnNumber].setBackground(Color.YELLOW);
buttons[rowNumber][columnNumber].setName("1");
}
else if (colour.equals("BLUE") && rowNumber < ROW && columnNumber < COLUMN)
{
buttons[rowNumber][columnNumber].setBackground(Color.BLUE);
buttons[rowNumber][columnNumber].setName("2");
}
else if (colour.equals("GREEN") && rowNumber < ROW && columnNumber < COLUMN)
{
buttons[rowNumber][columnNumber].setBackground(Color.GREEN);
buttons[rowNumber][columnNumber].setName("3");
}
else if (colour.equals("PURPLE") && rowNumber < ROW && columnNumber < COLUMN)
{
buttons[rowNumber][columnNumber].setBackground(new Color(102,0,102));
buttons[rowNumber][columnNumber].setName("4");
}
else if (colour.equals("BROWN") && rowNumber < ROW && columnNumber < COLUMN)
{
buttons[rowNumber][columnNumber].setBackground(new Color(102,51,0));
buttons[rowNumber][columnNumber].setName("5");
}
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
private void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
JComponent contentPane = (JComponent) getContentPane();
contentPane.setLayout(new GridLayout(ROW, COLUMN, GAP, GAP));
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COLUMN; j++)
{
buttons[i][j] = new JButton();
buttons[i][j].setOpaque(true);
buttons[i][j].setBackground(DEFAULT_COLOUR);
buttons[i][j].setActionCommand(i + " " + j);
buttons[i][j].setName("6");
buttons[i][j].addActionListener(buttonActions);
contentPane.add(buttons[i][j]);
}
}
pack();
setVisible(true);
readFile();
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
buttonColours = new ButtonColours();
buttonColours.createAndDisplayGUI();
}
});
}
}
class ColourDialog extends JDialog
{
private Color[] colours = {
Color.RED,
Color.YELLOW,
Color.BLUE,
Color.GREEN,
new Color(102,0,102),
new Color(102,51,0)
};
private int[] colourIndices = new int[6];
private JButton redButton;
private JButton yellowButton;
private JButton blueButton;
private JButton greenButton;
private JButton purpleButton;
private JButton brownButton;
private JButton clickedButton;
private int leftRowButtons;
private int leftColumnButtons;
public ColourDialog(final ButtonColours frame, String title, boolean isModal, JButton button)
{
super(frame, title, isModal);
leftRowButtons = 0;
leftColumnButtons = 0;
clickedButton = button;
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setLocationByPlatform(true);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
redButton = new JButton("RED");
redButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String possibleColour = "0";
/*
* Here we will check, if RED is clicked,
* do we have any block with the same colour
* or not, if yes then nothing will happen
* else we will change the background
* to RED.
*/
if (checkBlockColours(frame, possibleColour))
{
clickedButton.setBackground(Color.RED);
clickedButton.setName("0");
dispose();
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
}
});
yellowButton = new JButton("YELLOW");
yellowButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String possibleColour = "1";
if (checkBlockColours(frame, possibleColour))
{
clickedButton.setBackground(Color.YELLOW);
clickedButton.setName("1");
dispose();
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
}
});
blueButton = new JButton("BLUE");
blueButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String possibleColour = "2";
if (checkBlockColours(frame, possibleColour))
{
clickedButton.setBackground(Color.BLUE);
clickedButton.setName("2");
dispose();
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
}
});
greenButton = new JButton("GREEN");
greenButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String possibleColour = "3";
if (checkBlockColours(frame, possibleColour))
{
clickedButton.setBackground(Color.GREEN);
clickedButton.setName("3");
dispose();
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
}
});
purpleButton = new JButton("PURPLE");
purpleButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String possibleColour = "4";
if (checkBlockColours(frame, possibleColour))
{
clickedButton.setBackground(new Color(102,0,102));
clickedButton.setName("4");
dispose();
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
}
});
brownButton = new JButton("BROWN");
brownButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String possibleColour = "5";
if (checkBlockColours(frame, possibleColour))
{
clickedButton.setBackground(new Color(102,51,0));
clickedButton.setName("5");
dispose();
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
}
});
panel.add(redButton);
panel.add(yellowButton);
panel.add(blueButton);
panel.add(greenButton);
panel.add(purpleButton);
panel.add(brownButton);
add(panel);
pack();
}
private boolean checkBlockColours(ButtonColours frame, String possibleColour)
{
leftRowButtons = 0;
leftColumnButtons = 0;
String command = clickedButton.getActionCommand();
String[] array = command.split(" ");
int row = Integer.parseInt(array[0]);
int column = Integer.parseInt(array[1]);
// First we will check in ROW. for the same colour, that is clicked.
for (int i = 0; i < ButtonColours.COLUMN; i++)
{
if (i != column)
{
JButton button = frame.buttons[row][i];
if (button.getName().equals(possibleColour))
return false;
else if (button.getName().equals(ButtonColours.DEFAULT_COMMAND))
leftRowButtons++;
}
}
// Now we will check in COLUMN, for the same colour, that is clicked.
for (int i = 0; i < ButtonColours.ROW; i++)
{
if (i != row)
{
JButton button = frame.buttons[i][column];
if (button.getName().equals(possibleColour))
return false;
else if (button.getName().equals(ButtonColours.DEFAULT_COMMAND))
leftColumnButtons++;
}
}
return true;
}
private void fillRemaining(ButtonColours frame)
{
String command = clickedButton.getActionCommand();
String[] array = command.split(" ");
int row = Integer.parseInt(array[0]);
int column = Integer.parseInt(array[1]);
int emptyRow = -1;
int emptyColumn = -1;
if (leftRowButtons == 1)
{
for (int i = 0; i < ButtonColours.COLUMN; i++)
{
JButton button = frame.buttons[row][i];
int colourIndex = Integer.parseInt(button.getName());
switch(colourIndex)
{
case 0:
colourIndices[0] = 1;
break;
case 1:
colourIndices[1] = 1;
break;
case 2:
colourIndices[2] = 1;
break;
case 3:
colourIndices[3] = 1;
break;
case 4:
colourIndices[4] = 1;
break;
case 5:
colourIndices[5] = 1;
break;
default:
emptyRow = row;
emptyColumn = i;
}
}
for (int i = 0; i < colourIndices.length; i++)
{
if (colourIndices[i] == 0)
{
frame.buttons[emptyRow][emptyColumn].setBackground(colours[i]);
setButtonName(frame.buttons[emptyRow][emptyColumn], i);
System.out.println("Automatic Button Name : " + frame.buttons[emptyRow][emptyColumn].getName());
System.out.println("Automatic Row : " + emptyRow);
System.out.println("Automatic Column : " + emptyColumn);
disableListenersRow(frame, row);
if (checkBlockColours(frame, ButtonColours.DEFAULT_COMMAND))
{
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
break;
}
}
}
if (leftColumnButtons == 1)
{
for (int i = 0; i < ButtonColours.ROW; i++)
{
JButton button = frame.buttons[i][column];
int colourIndex = Integer.parseInt(button.getName());
switch(colourIndex)
{
case 0:
colourIndices[0] = 1;
break;
case 1:
colourIndices[1] = 1;
break;
case 2:
colourIndices[2] = 1;
break;
case 3:
colourIndices[3] = 1;
break;
case 4:
colourIndices[4] = 1;
break;
case 5:
colourIndices[5] = 1;
break;
default:
emptyRow = i;
emptyColumn = column;
}
}
for (int i = 0; i < colourIndices.length; i++)
{
if (colourIndices[i] == 0)
{
frame.buttons[emptyRow][emptyColumn].setBackground(colours[i]);
setButtonName(frame.buttons[emptyRow][emptyColumn], i);
System.out.println("Automatic Button Name : " + frame.buttons[emptyRow][emptyColumn].getName());
System.out.println("Automatic Row : " + emptyRow);
System.out.println("Automatic Column : " + emptyColumn);
disableListenersColumn(frame, column);
if (checkBlockColours(frame, ButtonColours.DEFAULT_COMMAND))
{
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
break;
}
}
}
}
private void setButtonName(JButton button, int index)
{
switch(index)
{
case 0:
button.setName("0");
break;
case 1:
button.setName("1");
break;
case 2:
button.setName("2");
break;
case 3:
button.setName("3");
break;
case 4:
button.setName("4");
break;
case 5:
button.setName("5");
break;
}
}
private void disableListenersRow(ButtonColours frame, int row)
{
System.out.println("Disabled ROW : " + row);
for (int i = 0; i < ButtonColours.ROW; i++)
{
frame.buttons[row][i].removeActionListener(frame.buttonActions);
System.out.println("DISABLED BUTTONS : " + row + " " + i);
}
}
private void disableListenersColumn(ButtonColours frame, int column)
{
System.out.println("Disabled COLUMN : " + column);
for (int i = 0; i < ButtonColours.COLUMN; i++)
{
frame.buttons[i][column].removeActionListener(frame.buttonActions);
System.out.println("DISABLED BUTTONS : " + i + " " + column);
}
}
}
Here is the output of this thingy :-)
(maybe use JColorChooser directly)
don't use two JFrames
use putClientProperty
use ButtonModel or MouseListener
use JOptionsPane put there JButtons that returns Color, or create JDialog(parent, true) with JButtons layed by GridLayout
One convenient and reliable way to alter a button's appearance in any L&F is to implement the Icon interface, as shown in this example.
Related
Every time a new swing windows opens in code that is executed in a for loop.
I have some code that is runned in a for loop.
The for loop gives every time a new value to my multidimensional array.
But, every time my for loop creates open's a new windows but does not close the old window.
How can I solve this issues? I want to close the old windows and refresh my window with the new actual values or that only one Windows is opened and that the new values of the for loop refreshes the values inside the table based on the multidimensional array names data.
Because now more than 200 (every second a new windows is opened) windows are opened and after 1 minute I don’t see new values appearing on my window and the computer freezes.
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.Timer;
public class UAppWin {
private static final int Status_COL = 1;
String[][] data = new String[3][3];
int dptr;
String[] cols = { "Feature", "Status", "Value" };
public UAppWin(String label, int nphases) {
System.out.println("UApp \"" + label + "\" (" + nphases + " phases)");
}
void newCycle(int phasenr) {
System.out.println("UApp =============================");
dptr = 0;
}
void addEntry(int index, double tim, String label, int status, double dval) {
System.out.println("Uapp [" + index + "] " + label + "(" + status + ") " + dval);
data[dptr][0] = label;
data[dptr][1] = "" + status;
data[dptr][2] = "" + dval;
dptr++;
}
void addMessage(String msg) {
System.out.println("Uapp alert: " + msg);
// rode balk met bericht
}
void deleteMessage() {
}
void endCycle() {
System.out.println("UApp =============================");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, new JScrollPane(getNewRenderedTable(getTable())));
}
});
}
private JTable getTable() {
DefaultTableModel model = new DefaultTableModel(data, cols);
return new JTable(model) {
#Override
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(300, 150);
}
};
}
private static JTable getNewRenderedTable(final JTable table) {
table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int col) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
String Status = (String) table.getModel().getValueAt(row, Status_COL);
if ("0".equals(Status)) {
setBackground(Color.GREEN);
setForeground(Color.BLACK);
} else if ("2".equals(Status)) {
setBackground(Color.RED);
setForeground(Color.BLACK);
} else {
setBackground(Color.YELLOW);
setForeground(Color.BLACK);
}
return this;
}
});
return table;
}
}
The second part of the code edited:
public class HmOpIntf {
static final String DFLT_IP_ADDR = "127.0.0.1";
static final int DFLT_IP_PORT = 9502;
static final int DFLT_MB_UNIT = 1;
static final int DFLT_POLL_TM = 2;
public static ModbusClient connectPLC(String ipAddr, int port, int unitNr)
{
ModbusClient mc = null;
System.out.println("Connecting to " + ipAddr + " port " + port + " unit " + unitNr);
try {
mc = new ModbusClient(ipAddr, port);
mc.Connect();
mc.setUnitIdentifier((byte)unitNr);
mc.WriteSingleCoil(0, true);
} catch (Exception e) {
System.err.println("*** connectPLC: exception caught");
return null;
}
System.out.println("Connected!");
return mc;
}
public static void disconnectPLC(ModbusClient mc)
{
mc = null;
}
public static String MyConvertRegistersToString(int[] regs, int startIx, int len) {
char[] ca = new char[len];
for (int i = 0; i < len; i++) {
ca[i] = (char) regs[startIx + i];
}
return new String(ca);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
ModbusClient mc = null;
String ipAddr = DFLT_IP_ADDR;
int ipPort = DFLT_IP_PORT;
int mbUnit = DFLT_MB_UNIT;
int pollTime = DFLT_POLL_TM;
int tlBase = 2000; /* Offset in PLC's holding registry */
int tlBlocksz = 84;
String[] tlLabel = {"T4 mould", "T injection valve"}; /* Default */
int trafLightNum = tlLabel.length;
String[] colors = { "green", "yellow", "red" };
int status;
// Notifications.infoBox("Hello world!", "Welcome message");
if (args != null && args.length > 0) {
if (args.length < 4) {
System.err.println("*** Error (" + args.length +"): arguments are: ip-addr port unit polltime label-1 ...");
System.exit(1);
}
ipAddr = args[0];
ipPort = Integer.parseInt(args[1]);
mbUnit = Integer.parseInt(args[2]);
pollTime = Integer.parseInt(args[3]);
}
if (args.length > 4) {
trafLightNum = args.length - 4;
tlLabel = new String[trafLightNum];
for (int i = 0; i < trafLightNum; i++) {
tlLabel[i] = args[i + 4];
}
}
// Scope sc = new Scope();
// sc.runScope();
if ((mc = connectPLC(ipAddr, ipPort, mbUnit)) == null) {
System.out.println("*** Failed to connect to PLC");
System.exit(1);
}
TrafficLight tlLast = null;
int[] values = new int[tlBlocksz];
TrafficLight[] tl = new TrafficLight[trafLightNum];
Scope[] sc = new Scope[trafLightNum];
Notifications nots = new Notifications(trafLightNum);
int locX, locY;
for (int i = 0; i < tl.length; i++) {
tl[i] = new TrafficLight();
tl[i].setLbl(tlLabel[i]);
tl[i].setVisible(true);
if (tlLast != null) {
locX = tlLast.getLocation().x;
locY = tlLast.getLocation().y + tlLast.getHeight();
} else {
locX = tl[i].getLocation().x;
locY = tl[i].getLocation().y;
}
tl[i].setLocation(locX, locY);
sc[i] = new Scope(tlLabel[i], locX + tl[i].getWidth(), locY, 320, 290 /* tl[i].getHeight()-80 */ );
sc[i].setGrid(10, 5);
tlLast = tl[i];
}
UAppWin uw = new UAppWin("RTM Facility", 5);
int phase = 1;
// tl2.setVisible(true); tl2.setLocation(tl.getWidth(), 0);
try {
double t = 0.0;
int[] dreg = new int[2];
for (;;) {
uw.newCycle(phase);
for (int i = 0; i < tl.length; i++) {
values = mc.ReadHoldingRegisters(tlBase + i * tlBlocksz, values.length);
status = values[0];
if (status >= 0 && status < colors.length) {
// System.out.println(i + ": " + colors[status]);
if (status == 0) tl[i].greenOn();
else if (status == 1) tl[i].yellowOn();
else tl[i].redOn();
}
else
System.out.println("Status value " + i + " out of range: " + status);
dreg[0] = values[1]; dreg[1] = values[2];
double dval = (double) ModbusClient.ConvertRegistersToFloat(dreg);
sc[i].addValue(t, dval);
sc[i].drawSignal();
// w.addEntry(int i, float t, String label, int status (o = groen, 1 = yellow, 2 = red), float dval);
uw.addEntry(i, t, tlLabel[i], status, dval);
int msglen = values[3];
if (msglen > 0) {
String msg = MyConvertRegistersToString(values, 4, msglen);
System.out.println("DEBUG: received message for " + tlLabel[i] + ": " + msg);
nots.notify(i, msg);
uw.addMessage(msg);
}
else {
nots.notify(i, null);
uw.deleteMessage();
}
// System.out.println("Received for set " + i + ": status=" + status + " dval=" + dval + " msglen=" + msglen);
}
uw.endCycle();
t += 1.0;
Thread.sleep(pollTime * 500);
}
} catch (Exception e) {
System.out.println("*** Failed to communicate with PLC - exit");
System.exit(1);
}
try {
mc.Disconnect();
} catch (IOException e) {
System.out.println("*** Failed to disconnect from PLC");
}
}
}
The UappWin seems to be tied to a window. So when you create it, also create a JFrame. Then nothing else would need to change except the run method and declaring the JFrame.
public class UAppWin {
private JFrame frame;
public UAppWin(String label, int nphases) {
//System.out.println("UApp \"" + label + "\" (" + nphases + " phases)");
JLabel label = new JLabel("UApp \"" + label + "\" (" + nphases + " phases)");
frame = new JFrame("title");
frame.add(label);
frame.setVisible(true);
}
Then when you create the window.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//JOptionPane.showMessageDialog(null, new JScrollPane(getNewRenderedTable(getTable())));
frame.setContentPane( new JScrollPane( getNewRenderedTable( getTable() ) );
frame.setVisible(true);
}
});
I am trying to make a JFrame program that interfaces a binary-decimal-hexadecimal converter with buttons. A part of this, I would like to draw circles to represent binary numbers in a row of circles with a filled circle representing a one and an empty circle representing a zero. However, when I try to call repaint to draw anything, it does not execute the paintComponent() method, which I know because it does not perform the print statement inside of it. Full code below:
package e2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.FlowLayout;
public class DecBin extends JPanel {
String theText = "IT WORKS";
int style = Font.BOLD; // bold only
Font font = new Font("Arial", style, 40);
DecBin() {
JFrame f = new JFrame("Decimal to binary and binary to decimal converter");
f.setSize(1000, 1000);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
Font font = new Font("Arial", style, 40);
JLabel textLabel = new JLabel(theText);
textLabel.setFont(font);
JButton b = new JButton("DectoBin");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a decimal number");
int num = Integer.parseInt(msg);
theText = num + " is " + decToBin(num) + " in binary";
textLabel.setText(theText);
}
});
f.add(b);
JButton d = new JButton("BintoDec");
d.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a binary number");
System.out.print("The decimal form of " + msg + " is " + binToDec(msg));
theText = msg + " is " + binToDec(msg) + " in decimal";
textLabel.setText(theText);
}
});
f.add(d);
JButton hd = new JButton("hexToDec");
hd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a hexadecimal number");
theText = msg + " is " + hexToDec(msg) + " in decimal";
textLabel.setText(theText);
}
});
f.add(hd);
JButton dh = new JButton("DectoHex");
dh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a decimal number");
int num = Integer.parseInt(msg);
theText = num + " is " + decToHex(num) + " in hexadecimal";
textLabel.setText(theText);
}
});
f.add(dh);
JButton bh = new JButton("BinToHex");
bh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a binary number");
theText = msg + " is " + decToHex(binToDec(msg)) + " in hexadecimal";
textLabel.setText(theText);
}
});
f.add(bh);
JButton hb = new JButton("HexToBin");
hb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a Hexadecimal number");
theText = msg + " is " + decToBin(hexToDec(msg)) + " in hexadecimal";
textLabel.setText(theText);
}
});
f.add(hb);
JButton c = new JButton("Draw");
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.print("test1");
validate();
repaint();
}
});
f.add(c);
f.add(textLabel, BorderLayout.SOUTH);
f.setVisible(true);
}
public static void main(String[] args) {
new DecBin();
}
static String decToBin(int d) {
StringBuilder binary = new StringBuilder("");
while (d != 0) {
binary.insert(0, d % 2);
d = d / 2;
}
return binary.toString();
}
static int binToDec(String b) {
int total = 0;
int x;
for (int i = b.length(); i > 0; i--) {
x = Integer.parseInt(Character.toString(b.charAt(i - 1)));
if (x == 1) {
total += Math.pow(2, b.length() - i);
}
}
return total;
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.fillOval(100, 100, 20, 20);
System.out.print("painted components");
}
static String decToHex(int d) {
StringBuilder Hex = new StringBuilder("");
while (d != 0) {
int remainder = d % 16;
if (remainder < 10) {
Hex.insert(0, d % 16);
} else if (remainder == 10) {
Hex.insert(0, 'A');
} else if (remainder == 11) {
Hex.insert(0, 'B');
} else if (remainder == 12) {
Hex.insert(0, 'C');
} else if (remainder == 13) {
Hex.insert(0, 'D');
} else if (remainder == 14) {
Hex.insert(0, 'E');
} else if (remainder == 15) {
Hex.insert(0, 'F');
}
d = d / 16;
}
return Hex.toString();
}
static int hexToDec(String b) {
int total = 0;
int len = b.length();
for (int i = len - 1; i >= 0; i--) {
if (b.charAt(i) == 'A') {
total += 10 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'B') {
total += 11 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'C') {
total += 12 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'D') {
total += 13 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'E') {
total += 14 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'F') {
total += 15 * Math.pow(16, len - i - 1);
} else {
total += Character.getNumericValue(b.charAt(i)) * Math.pow(16, len - i - 1);
}
}
return total;
}
}
Pertinent code in my opinion is:
DecBin() {
JFrame f=new JFrame("Decimal to binary and binary to decimal converter");
f.setSize(1000,1000);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
JButton c =new JButton("Draw");
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.print("test1");
validate();
repaint();
}
});
f.add(c);
f.setVisible(true);
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.fillOval(100, 100, 20, 20);
System.out.print("painted components");
}
public static void main(String[] args) {
new DecBin();
}
I have spent hours researching this and have yet to find a solution that will get "painted components" to print.
You do not appear to be adding your DecBin panel to any other UI element. It therefore has no reason to be painted.
You should avoid initializing JFrames inside the constructor of your JPanel child class - it should really be the other way around. That will make things easier to understand (and to debug).
I have a jTextField, jLabel and a jButton. I want to set the jTextField to empty and update the jLabel to some new text after I perform jButton action.
This my code for jButtonActionPerformed(ActionEvent e) method:
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {
BufferedWriter fw;
StringBuilder guessword = new StringBuilder(word);
try {
fw = new BufferedWriter(new FileWriter("C:\\Users\\Arihant\\JavaApplication1\\src\\javaapplication1\\scores.txt", true));
while(guesses != 0) {
jLabel26.setText(Integer.toString(guesses));
guesschar = jTextField2.getText().charAt(0);
flag = 0;
for(int j = 0; j < word.length() / 2; j++) {
if(Character.toLowerCase(guesschar) == temp[j] && (guessword.toString().indexOf(Character.toLowerCase(guesschar)) < 0)) {
flag = 1;
for(int k = 0; k < word.length(); k++) {
if(Character.toLowerCase(guesschar) == word.charAt(k))
guessword.setCharAt(k, Character.toLowerCase(guesschar));
}
if(guessword.toString().equals(word)) {
switch (difficulty) {
case "EASY":
points = guesses * 50;
break;
case "MODERATE":
points = guesses * 100;
break;
case "HARD":
points = guesses * 200;
break;
default:
points = 0;
break;
}
try {
fw.append(name + " " + points);
fw.newLine();
fw.close();
} catch (IOException ex) {
Logger.getLogger(HangMan.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
}
jPanel13.removeAll();
jPanel13.add(jPanel4);
jPanel13.repaint();
jPanel13.revalidate();
jLabel29.setText("<html>YOU WIN!<br/> The word was: </html>" + word);
jLabel31.setText("You scored: " + points + " points.");
jLabel28.setText("Play again?");
}
}
}
if(flag == 0) {
guesses--;
}
jPanel13.repaint();
jPanel13.revalidate();
jLabel1.setText(guessword.toString());
jTextField2.setText("");
Document document = jTextField2.getDocument();
document.addDocumentListener(new JButtonStateController(jButton8, 0));
((AbstractDocument) jTextField2.getDocument()).setDocumentFilter(new JTextFieldFilter(0));
}
} catch (IOException ex) {
Logger.getLogger(HangMan.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
}
}
When I click jButton8, it just skips the entire code in try-catch block and goes directly to jPanel13.removeAll();.
I want to set the jTextField2 to empty and jButton8 to disabled, each time I click jButton8.
Tell me, where I am wrong and how can I improve my code?
In my code, I'm trying to use a JScrollPane and add it into a JOptionPane.showMessageDialog. I don't know if this is possible to start with but I don't know how to do it if it is, and how to add the whole array into the one message and not multiple. Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Iterator;
public class CulminatingPro implements ActionListener
{
//Create an array of buttons
static JButton[][] buttons = new JButton[10][4];
static JButton jbtList = new JButton("List");
ArrayList<Culminating> flyers = new ArrayList<Culminating>();
String fn;
String ln;
String pn;
String adress;
int column;
int row;
int reply;
int v;
Object[] options = {"First Name",
"Last Name",
"Phone Number",
"Adress"};
public static void main(String[] args)
{
JFrame frame = new JFrame("Fly By Buddies");
frame.setSize(900, 900);
JPanel mainPanel = new JPanel();
mainPanel.setLayout( new GridLayout(1,2));
JPanel paneSeats = new JPanel();
JPanel paneInfo = new JPanel();
paneSeats.setLayout( new GridLayout(11, 4, 5,5));
mainPanel.add(paneSeats);
mainPanel.add(paneInfo);
frame.setContentPane(mainPanel);
for (int i = 0; i < buttons.length; i++)
{
for(int j = 0; j < buttons[0].length; j++)
{
if (j + 1 == 1)
{
buttons[i][j] = new JButton("Seat " + (i + 1) + "A");
buttons[i][j].setBackground(Color.GREEN);
paneSeats.add(buttons[i][j]);
buttons[i][j].addActionListener(new CulminatingPro());
}
else if (j + 1 == 2)
{
buttons[i][j] = new JButton("Seat " + (i + 1) + "B");
buttons[i][j].setBackground(Color.GREEN);
paneSeats.add(buttons[i][j]);
buttons[i][j].addActionListener(new CulminatingPro());
}
else if (j + 1== 3)
{
buttons[i][j] = new JButton("Seat " + (i + 1) + "C");
buttons[i][j].setBackground(Color.GREEN);
paneSeats.add(buttons[i][j]);
buttons[i][j].addActionListener(new CulminatingPro());
}
else if (j + 1== 4)
{
buttons[i][j] = new JButton("Seat " + (i + 1) + "D");
buttons[i][j].setBackground(Color.GREEN);
paneSeats.add(buttons[i][j]);
buttons[i][j].addActionListener(new CulminatingPro());
}
}
}
jbtList.setPreferredSize(new Dimension(400, 40));
jbtList.addActionListener(new CulminatingPro());
paneInfo.add(jbtList, BorderLayout.SOUTH);
frame.setVisible(true);
frame.toFront();
}
public void actionPerformed(ActionEvent event)
{
for (int i = 0; i < buttons.length; i++)
{
for(int j = 0; j < buttons[0].length; j++)
{
if (event.getSource() == buttons[i][j])
{
v = 0;
for (int k = 0; k < flyers.size();k++)
{
if((flyers.get(k).getColumn() == (j) && (flyers.get(k).getColumn() == (j))))
{
if (!flyers.get(k).getFirstName().equals(""))
{
reply = JOptionPane.showConfirmDialog(null,
"Would you like to delete the info on the passenger?", "Deletion", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
{
flyers.remove(k);
buttons[i][j].setBackground(Color.GREEN);
}
else if (reply == JOptionPane.NO_OPTION)
{
reply = JOptionPane.showConfirmDialog(null,
"Would you like to modify the info on the passenger?", "Modification", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
{
int n = JOptionPane.showOptionDialog(null, "Message", "Title",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
n = n + 1;
if(n == 0)
{
fn = JOptionPane.showInputDialog(null,"Re-enter passenger's first name: ");
flyers.get(k).setFirstName(fn);
}
if(n == 2)
{
ln = JOptionPane.showInputDialog(null,"Re-enter passenger's last name: ");
flyers.get(k).setLastName(ln);
}
if(n == 3)
{
pn = JOptionPane.showInputDialog(null,"Re-enter passenger's phone number: ");
flyers.get(k).setPhoneNumber(pn);
}
if(n == 4)
{
adress = JOptionPane.showInputDialog(null,"Re-enter passenger's adress: ");
flyers.get(k).setAdress(adress);
}
}
}
v = 1;
}
}
}
if(v == 0)
{
fn = JOptionPane.showInputDialog(null,"Passenger's first name (Necessary): ");
ln = JOptionPane.showInputDialog(null,"Passenger's last name (Necessary): ");
pn = JOptionPane.showInputDialog(null,"Passenger's phone number: ");
adress = JOptionPane.showInputDialog(null,"Passenger's adress: ");
column = j;
row = i;
flyers.add(new Culminating(fn,ln,pn,adress,column,row));
buttons[i][j].setBackground(Color.RED);
}
}
}
}
if (event.getSource().equals("List"))
{
JScrollPane[] scroll = new JScrollPane[flyers.size()];
for(int p = 0; p < flyers.size(); p++)
{
JTextArea text = new JTextArea(flyers.get(p).toString(), 10, 40);
scroll[p] = new JScrollPane(text);
}
for(int p = 0; p < flyers.size(); p++)
{
JOptionPane.showMessageDialog(null,scroll[p]);
}
}
}
}
Hi. I need some help. JScrollPane working vertically good but horizontally not. And I cant find whats the problem. I know that its a little big project and there is a lot of confusing codes but I cant delete any of that function.
public final class Salary extends javax.swing.JFrame {
private SalaryTableModel tableModel;
public int selectedRow = -1;
public static String bolme;
public static String ay;
public static int il = 0;
private final String selectedItem_Bolme;
private final String selectedItem_Ay;
private final int selectedItem_Il;
private List<Pojo> sortedList;
public TableColumn date;
public static int bolmeId = 0;
public static String ad;
public static int row2;
public void visible(String bolme2, String ay2, int il2) {
il = il2;
ay = ay2;
bolme = bolme2;
new Salary().setVisible(true);
}
public RXTable autoResizeColWidth(RXTable table, SalaryTableModel model) {
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setModel(model);
int margin = 5;
for (int i = 0; i < table.getColumnCount(); i++) {
int vColIndex = i;
DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
TableColumn col = colModel.getColumn(vColIndex);
int width;
TableCellRenderer renderer = col.getHeaderRenderer();
if (renderer == null) {
renderer = table.getTableHeader().getDefaultRenderer();
}
Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0);
width = comp.getPreferredSize().width;
for (int r = 0; r < table.getRowCount(); r++) {
renderer = table.getCellRenderer(r, vColIndex);
comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), false, false,
r, vColIndex);
width = Math.max(width, comp.getPreferredSize().width);
}
width += 2 * margin;
col.setPreferredWidth(width);
}
((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(
SwingConstants.LEFT);
table.getTableHeader().setReorderingAllowed(false);
return table;
}
public Salary() {
initComponents();
Toolkit.getDefaultToolkit().getImage(getClass().getResource("/images/db.png"));
setDefaultCloseOperation(EXIT_ON_CLOSE);
List<Pojo> model = DBO.findBolme();
HashSet hs = new HashSet();
ArrayList al = new ArrayList();
model.stream().forEach((model1) -> {
hs.add(model1.getBolme());
});
al.addAll(hs);
comboBolme.addItem("Butun Bolmeler");
al.stream().forEach((al1) -> {
comboBolme.addItem(al1);
bolmeId++;
});
comboBolme.removeItem("null");
if (bolme == null) {
comboBolme.setSelectedIndex(0);
} else {
comboBolme.setSelectedItem(bolme);
}
if (ay == null) {
comboAy.setSelectedIndex(0);
} else {
comboAy.setSelectedItem(ay);
}
List<Pojo> model2 = DBO.findIl();
HashSet hs2 = new HashSet();
ArrayList al2 = new ArrayList();
model2.stream().forEach((model1) -> {
hs2.add(model1.getIl());
});
al2.addAll(hs2);
comboIl.addItem(0000);
al2.stream().forEach((al1) -> {
comboIl.addItem(al1);
});
comboIl.removeItem(0);
if (il == 0) {
comboIl.setSelectedIndex(0);
} else {
comboIl.setSelectedItem(il);
}
selectedItem_Bolme = (String) comboBolme.getSelectedItem();
selectedItem_Ay = (String) comboAy.getSelectedItem();
selectedItem_Il = Integer.parseInt(comboIl.getSelectedItem().toString());
Pojo tempVar;
sortedList = DBO.salary_Find(selectedItem_Bolme, selectedItem_Ay, selectedItem_Il);
for (int i = 0; i < sortedList.size(); i++) {
if (sortedList.get(i).getIsleyir() == 1) {
sortedList.remove(i);
i--;
}
}
for (int i = 0; i < sortedList.size(); i++) {
for (int j = 0; j < sortedList.size(); j++) {
if (sortedList.get(i).getCem() == sortedList.get(j).getCem()) {
}
if (sortedList.get(i).getCem() > sortedList.get(j).getCem()) {
tempVar = sortedList.get(j);
sortedList.set(j, sortedList.get(i));
sortedList.set(i, tempVar);
}
}
}
tableModel = new SalaryTableModel(sortedList) {
#Override
public boolean isCellEditable(int row, int column) {
ad = tableModel.getTopic(row).getAd();
selectedRow = tableModel.getTopic(row).getId();
row2 = row;
return (column != 0) && (column != 17);
}
};
table.setModel(tableModel);
table = autoResizeColWidth(table, tableModel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM");
DatePickerCellEditor datePicker = new DatePickerCellEditor(formatter);
datePicker.setFormats(formatter);
date = table.getColumnModel().getColumn(18);
date.setCellEditor(datePicker);
table = new RXTable(tableModel);
JScrollPane pane = new JScrollPane(table);
add(pane);
table.setSelectAllForEdit(true);
table.getColumnModel().getColumn(0).setMinWidth(100);
table.getColumnModel().getColumn(1).setMinWidth(100);
table.getColumnModel().getColumn(2).setMinWidth(100);
table.getColumnModel().getColumn(3).setMinWidth(100);
table.getColumnModel().getColumn(4).setMinWidth(100);
table.getColumnModel().getColumn(5).setMinWidth(100);
table.getColumnModel().getColumn(6).setMinWidth(100);
table.getColumnModel().getColumn(7).setMinWidth(100);
table.getColumnModel().getColumn(8).setMinWidth(100);
table.getColumnModel().getColumn(9).setMinWidth(100);
table.getColumnModel().getColumn(10).setMinWidth(100);
table.getColumnModel().getColumn(11).setMinWidth(100);
table.getColumnModel().getColumn(12).setMinWidth(100);
table.getColumnModel().getColumn(13).setMinWidth(100);
table.getColumnModel().getColumn(14).setMinWidth(100);
table.getColumnModel().getColumn(15).setMinWidth(100);
table.getColumnModel().getColumn(16).setMinWidth(100);
table.getColumnModel().getColumn(17).setMinWidth(100);
table.getColumnModel().getColumn(18).setMinWidth(100);
table.getColumnModel().getColumn(19).setMinWidth(100);
table.getColumnModel().getColumn(20).setMinWidth(100);
table.getColumnModel().getColumn(21).setMinWidth(100);
table.getColumnModel().getColumn(21).setMaxWidth(10000);
setLocationRelativeTo(null);
double x = 0;
for (int i = 0; i < tableModel.getRowCount(); i++) {
x += tableModel.getTopic(i).getArtim();
}
lblArtiminCemi.setText(String.valueOf((x)));
double y = 0;
for (int i = 0; i < tableModel.getRowCount(); i++) {
y += tableModel.getTopic(i).getCem();
}
lblTotal.setText(String.valueOf((y)));
comboBolme.addActionListener((ActionEvent e) -> {
String selectedBolme = (String) comboBolme.getSelectedItem();
visible(selectedBolme, ay, il);
setVisible(false);
});
comboAy.addActionListener((ActionEvent e) -> {
String selectedAy = (String) comboAy.getSelectedItem();
visible(bolme, selectedAy, il);
setVisible(false);
});
comboIl.addActionListener((ActionEvent e) -> {
int selectedIl = Integer.parseInt(comboIl.getSelectedItem().toString());
visible(bolme, ay, selectedIl);
setVisible(false);
});
table.getModel().addTableModelListener((TableModelEvent e) -> {
int row = e.getFirstRow();
int column = e.getColumn();
TableModel model1 = (TableModel) e.getSource();
String columnName = model1.getColumnName(column);
Object value = model1.getValueAt(row, column);
Pojo temp;
sortedList = DBO.salary_Find(selectedItem_Bolme, selectedItem_Ay, selectedItem_Il);
for (int i = 0; i < sortedList.size(); i++) {
if (sortedList.get(i).getIsleyir() == 1) {
sortedList.remove(i);
i--;
}
}
for (int i = 0; i < sortedList.size(); i++) {
for (int j = 0; j < sortedList.size(); j++) {
if (sortedList.get(i).getCem() > sortedList.get(j).getCem()) {
temp = sortedList.get(j);
sortedList.set(j, sortedList.get(i));
sortedList.set(i, temp);
}
}
}
List<Pojo> list = sortedList;
Pojo data = list.get(row);
switch (column) {
case 0:
data.setId((int) value);
break;
case 1:
data.setAd((String) value);
break;
case 2:
data.setCins((int) value);
break;
case 3:
data.setBank((Double) value);
data.setCem(data.getBank() + data.getIlk_maas() + data.getSon_maas() + data.getArtim());
break;
case 4:
data.setIlk_maas((Double) value);
data.setCem(data.getBank() + data.getIlk_maas() + data.getSon_maas() + data.getArtim());
break;
case 5:
data.setSon_maas((Double) value);
data.setCem(data.getBank() + data.getIlk_maas() + data.getSon_maas() + data.getArtim());
break;
case 6:
data.setArtim((Double) value);
data.setCem(data.getBank() + data.getIlk_maas() + data.getSon_maas() + data.getArtim());
break;
case 7:
data.setCem((Double) value);
break;
case 8:
data.setElave_is((int) value);
break;
case 9:
data.setMukafatlandirma((Double) value);
break;
case 10:
data.setQayib_gunu((int) value);
break;
case 11:
data.setDetal_xetasi((Double) value);
break;
case 12:
data.setSatin_alma((Double) value);
break;
case 13:
data.setBolme(value.toString().toUpperCase());
break;
case 14:
data.setAy((String) value);
break;
case 15:
data.setIl((Integer) value);
break;
case 16:
data.setIsleyir((int) value);
break;
case 17:
data.setNe_qeder_isleyib((String) value);
break;
case 18:
try {
String time = value.toString();
Date date3 = new Date();
SimpleDateFormat format2 = new SimpleDateFormat("yyyy/MM");
Date date4 = format2.parse(time);
SimpleDateFormat format3 = new SimpleDateFormat("yyyy/MM");
data.setBaslama_tarixi(format3.format(date4));
Calendar cal = Calendar.getInstance();
cal.setTime(date3);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date4);
int diffYear = cal.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
int diffMonth = cal.get(Calendar.MONTH) - cal2.get(Calendar.MONTH);
if (diffMonth < 0) {
diffMonth += 12;
diffYear--;
}
data.setNe_qeder_isleyib(diffYear + " il " + diffMonth + " ay");
} catch (NumberFormatException | IndexOutOfBoundsException | ParseException ex) {
Logger.getLogger(Salary.class.getName()).log(Level.SEVERE, null, ex);
}
break;
case 19:
data.setBorc((Double) value);
break;
case 20:
data.setYekun_maas((Double) value);
data.setCem(data.getBank() + data.getIlk_maas() + data.getSon_maas() + data.getArtim());
data.setYekun_maas(data.getCem() - data.getBorc()
- ((data.getCem() / 26) * data.getQayib_gunu()) - data.getDetal_xetasi()
+ data.getSatin_alma() + ((data.getCem() / 26) * data.getElave_is()));
break;
case 21:
data.setQeyd((String) value);
break;
}
DBO.salary_Update(data, selectedRow);
visible(bolme, ay, il);
setVisible(false);
});
}`
If what you want is to display the full text of the cells instead of an abbreviation, you can use the Table Column Adjuster. e.g.:
String[] columnNames = {"Colum1", "Colum2", "Colum2"};
String[][] data = {
{"ABCDEFGHIJKLMNOPQRSTUVWXYZ", "-", "-"},
{"-", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "-"},
{"-", "-", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"}
};
TableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable();
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumnAdjuster tca = new TableColumnAdjuster(table);
tca.adjustColumns();
JScrollPane pane = new JScrollPane(table);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pane);
frame.setSize(400, 300);
frame.setVisible(true);
You can get the code for the class TableColumnAdjuster from http://www.camick.com/java/source/TableColumnAdjuster.java
Found a way )
table.setModel(tableModel);
table = autoResizeColWidth(table, tableModel);
//table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM");
DatePickerCellEditor datePicker = new DatePickerCellEditor(formatter);
datePicker.setFormats(formatter);
date = table.getColumnModel().getColumn(18);
date.setCellEditor(datePicker);
table = new RXTable(tableModel) {
#Override
public boolean getScrollableTracksViewportWidth() {
return getPreferredSize().width < getParent().getWidth();
}
};
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane pane = new JScrollPane(table);
add(pane);
//table.setSelectAllForEdit(true);
//table.getColumnModel().getColumn(0).setMinWidth(100);
//table.getColumnModel().getColumn(1).setMinWidth(100);
//....
//table.getColumnModel().getColumn(21).setMinWidth(100);
//table.getColumnModel().getColumn(21).setMaxWidth(10000);
setLocationRelativeTo(null);