Changing parameters within (multiple) Jlabels
I've a Swing GUI with 50 or so Jlabels:
{
jLabel1 = new JLabel();
getContentPane().add(jLabel1, "0, 0");
jLabel1.setText("AAPL 1453.54 2334.34 3234.32");
jLabel1.setForeground(new java.awt.Color(0,249,0));
}
I want to be able to change the txt and colour without having to write a large bunch of conditional statements. What's the best way to do this?
I was thinking to write a method overWrite(String text, int hPos, i开发者_StackOverflow中文版nt vPos){} to just add a new label in the place.
There might be a much better way to do this, I'm trying to make a crude stock display that changes stock prices and colour depending on an increase or decrease.
Okey, the solution below is ugly so I just came up with another solution... You can set a name of each of your labels so that you can get a specific label. And you do not need any other structure to hold the information.
JLabel label = new JLabel();
label.setName("the_name");
You can then iterate (just like the other solution) over the components and get the specific one like this:
for (Component c : frame.getContentPane().getComponents()) {
if (c.getName().equals("the_name")) {
// do the modifications...
}
}
Old solution: This is ugly but works.. :)
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Test");
frame.setLayout(new GridLayout(0, 1));
frame.add(new JButton("Hello"));
frame.add(new JLabel("World", JLabel.CENTER));
frame.add(new JButton("Hello"));
frame.add(new JLabel("World", JLabel.CENTER));
for (Component c : frame.getContentPane().getComponents()) {
if (c instanceof JLabel) {
((JLabel) c).setText("Friend");
c.setForeground(Color.RED);
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}
Output:
Store your JLabels in a Map. Maybe key them on stock symbol, like this:
Map<String, JLabel> labelMap = new HashMap<String, JLabel>;
labelMap.put("AAPL", jLabel1);
When you need to update a label, look it up using it's key and change its colour:
JLabel label = labelMap.get("AAPL");
label.setForeground(Color.RED);
Also, think about using a JTable. Most stock tickers I have seen are implemented using one.
精彩评论